xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 48bc00d6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/iptun/iptun_impl.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_setqfull(conn_t *);
823 static void	conn_clrqfull(conn_t *);
824 
825 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
826 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
827 static void	ip_stack_fini(netstackid_t stackid, void *arg);
828 
829 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
830     zoneid_t);
831 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
832     void *dummy_arg);
833 
834 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
835 
836 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
837     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
838     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
839 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
840 
841 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
842 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
843     caddr_t, cred_t *);
844 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
845     cred_t *, boolean_t);
846 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
847     caddr_t cp, cred_t *cr);
848 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
849     cred_t *);
850 static int	ip_squeue_switch(int);
851 
852 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
853 static void	ip_kstat_fini(netstackid_t, kstat_t *);
854 static int	ip_kstat_update(kstat_t *kp, int rw);
855 static void	*icmp_kstat_init(netstackid_t);
856 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
857 static int	icmp_kstat_update(kstat_t *kp, int rw);
858 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
859 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
860 
861 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
862     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
863 
864 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
865     ipha_t *, ill_t *, boolean_t, boolean_t);
866 
867 static void ipobs_init(ip_stack_t *);
868 static void ipobs_fini(ip_stack_t *);
869 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
870 
871 /* How long, in seconds, we allow frags to hang around. */
872 #define	IP_FRAG_TIMEOUT		15
873 #define	IPV6_FRAG_TIMEOUT	60
874 
875 /*
876  * Threshold which determines whether MDT should be used when
877  * generating IP fragments; payload size must be greater than
878  * this threshold for MDT to take place.
879  */
880 #define	IP_WPUT_FRAG_MDT_MIN	32768
881 
882 /* Setable in /etc/system only */
883 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
884 
885 static long ip_rput_pullups;
886 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
887 
888 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
889 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
890 
891 int	ip_debug;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
901 
902 /*
903  * XXX following really should only be in a header. Would need more
904  * header and .c clean up first.
905  */
906 extern optdb_obj_t	ip_opt_obj;
907 
908 ulong_t ip_squeue_enter_unbound = 0;
909 
910 /*
911  * Named Dispatch Parameter Table.
912  * All of these are alterable, within the min/max values given, at run time.
913  */
914 static ipparam_t	lcl_param_arr[] = {
915 	/* min	max	value	name */
916 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
918 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp"},
920 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
921 	{  0,	1,	1,	"ip_send_redirects"},
922 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
923 	{  0,	10,	0,	"ip_mrtdebug"},
924 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
925 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
926 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
927 	{  1,	255,	255,	"ip_def_ttl" },
928 	{  0,	1,	0,	"ip_forward_src_routed"},
929 	{  0,	256,	32,	"ip_wroff_extra" },
930 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
931 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
932 	{  0,	1,	1,	"ip_path_mtu_discovery" },
933 	{  0,	240,	30,	"ip_ignore_delete_time" },
934 	{  0,	1,	0,	"ip_ignore_redirect" },
935 	{  0,	1,	1,	"ip_output_queue" },
936 	{  1,	254,	1,	"ip_broadcast_ttl" },
937 	{  0,	99999,	100,	"ip_icmp_err_interval" },
938 	{  1,	99999,	10,	"ip_icmp_err_burst" },
939 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
940 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
941 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
942 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
943 	{  0,	1,	1,	"icmp_accept_clear_messages" },
944 	{  0,	1,	1,	"igmp_accept_clear_messages" },
945 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
946 				"ip_ndp_delay_first_probe_time"},
947 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
948 				"ip_ndp_max_unicast_solicit"},
949 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
950 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
951 	{  0,	1,	0,	"ip6_forward_src_routed"},
952 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
953 	{  0,	1,	1,	"ip6_send_redirects"},
954 	{  0,	1,	0,	"ip6_ignore_redirect" },
955 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
956 
957 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
958 
959 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
960 
961 	{  0,	1,	1,	"pim_accept_clear_messages" },
962 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
963 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
964 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
965 	{  0,	15,	0,	"ip_policy_mask" },
966 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
967 	{  0,	255,	1,	"ip_multirt_ttl" },
968 	{  0,	1,	1,	"ip_multidata_outbound" },
969 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
970 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
971 	{  0,	1000,	1,	"ip_max_temp_defend" },
972 	{  0,	1000,	3,	"ip_max_defend" },
973 	{  0,	999999,	30,	"ip_defend_interval" },
974 	{  0,	3600000, 300000, "ip_dup_recovery" },
975 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
976 	{  0,	1,	1,	"ip_lso_outbound" },
977 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
978 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
979 	{ 68,	65535,	576,	"ip_pmtu_min" },
980 #ifdef DEBUG
981 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
982 #else
983 	{  0,	0,	0,	"" },
984 #endif
985 };
986 
987 /*
988  * Extended NDP table
989  * The addresses for the first two are filled in to be ips_ip_g_forward
990  * and ips_ipv6_forward at init time.
991  */
992 static ipndp_t	lcl_ndp_arr[] = {
993 	/* getf			setf		data			name */
994 #define	IPNDP_IP_FORWARDING_OFFSET	0
995 	{  ip_param_generic_get,	ip_forward_set,	NULL,
996 	    "ip_forwarding" },
997 #define	IPNDP_IP6_FORWARDING_OFFSET	1
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip6_forwarding" },
1000 	{ ip_param_generic_get, ip_input_proc_set,
1001 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1002 	{ ip_param_generic_get, ip_int_set,
1003 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1004 #define	IPNDP_CGTP_FILTER_OFFSET	4
1005 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1006 	    "ip_cgtp_filter" },
1007 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1008 	    "ip_debug" },
1009 };
1010 
1011 /*
1012  * Table of IP ioctls encoding the various properties of the ioctl and
1013  * indexed based on the last byte of the ioctl command. Occasionally there
1014  * is a clash, and there is more than 1 ioctl with the same last byte.
1015  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1016  * ioctls are encoded in the misc table. An entry in the ndx table is
1017  * retrieved by indexing on the last byte of the ioctl command and comparing
1018  * the ioctl command with the value in the ndx table. In the event of a
1019  * mismatch the misc table is then searched sequentially for the desired
1020  * ioctl command.
1021  *
1022  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1023  */
1024 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1025 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1037 			MISC_CMD, ip_siocaddrt, NULL },
1038 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1039 			MISC_CMD, ip_siocdelrt, NULL },
1040 
1041 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1042 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1043 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1044 			IF_CMD, ip_sioctl_get_addr, NULL },
1045 
1046 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1047 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1048 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1049 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1050 
1051 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1052 			IPI_PRIV | IPI_WR,
1053 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1054 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1055 			IPI_MODOK | IPI_GET_CMD,
1056 			IF_CMD, ip_sioctl_get_flags, NULL },
1057 
1058 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* copyin size cannot be coded for SIOCGIFCONF */
1062 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1063 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1064 
1065 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_mtu, NULL },
1067 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1068 			IF_CMD, ip_sioctl_get_mtu, NULL },
1069 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1070 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1071 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1072 			IF_CMD, ip_sioctl_brdaddr, NULL },
1073 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1074 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1075 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1076 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1077 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1078 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1079 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1080 			IF_CMD, ip_sioctl_metric, NULL },
1081 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* See 166-168 below for extended SIOC*XARP ioctls */
1084 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1085 			ARP_CMD, ip_sioctl_arp, NULL },
1086 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1087 			ARP_CMD, ip_sioctl_arp, NULL },
1088 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1089 			ARP_CMD, ip_sioctl_arp, NULL },
1090 
1091 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1114 			MISC_CMD, if_unitsel, if_unitsel_restart },
1115 
1116 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1136 			IPI_PRIV | IPI_WR | IPI_MODOK,
1137 			IF_CMD, ip_sioctl_sifname, NULL },
1138 
1139 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 
1153 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1154 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1155 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1156 			IF_CMD, ip_sioctl_get_muxid, NULL },
1157 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1158 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1159 
1160 	/* Both if and lif variants share same func */
1161 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1162 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1163 	/* Both if and lif variants share same func */
1164 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1165 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1166 
1167 	/* copyin size cannot be coded for SIOCGIFCONF */
1168 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1169 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1170 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1190 			ip_sioctl_removeif_restart },
1191 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_addif, NULL },
1194 #define	SIOCLIFADDR_NDX 112
1195 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1197 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1198 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1199 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1201 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1202 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1203 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1204 			IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1206 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1207 			IPI_GET_CMD | IPI_MODOK,
1208 			LIF_CMD, ip_sioctl_get_flags, NULL },
1209 
1210 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 
1213 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1214 			ip_sioctl_get_lifconf, NULL },
1215 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1216 			LIF_CMD, ip_sioctl_mtu, NULL },
1217 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1218 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1219 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1220 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1221 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1222 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1223 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1224 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1225 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1227 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1228 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1229 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_metric, NULL },
1231 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR | IPI_MODOK,
1233 			LIF_CMD, ip_sioctl_slifname,
1234 			ip_sioctl_slifname_restart },
1235 
1236 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1237 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1238 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1239 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1240 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1241 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1242 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1244 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1246 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 			LIF_CMD, ip_sioctl_token, NULL },
1248 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1249 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1250 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1251 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1252 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1253 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1254 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1256 
1257 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1258 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1259 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1260 			LIF_CMD, ip_siocdelndp_v6, NULL },
1261 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1262 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1263 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1264 			LIF_CMD, ip_siocsetndp_v6, NULL },
1265 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1266 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1267 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1268 			MISC_CMD, ip_sioctl_tonlink, NULL },
1269 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1270 			MISC_CMD, ip_sioctl_tmysite, NULL },
1271 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1272 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1273 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1274 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1275 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1276 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1277 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1278 
1279 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1280 
1281 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1282 			LIF_CMD, ip_sioctl_get_binding, NULL },
1283 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1284 			IPI_PRIV | IPI_WR,
1285 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1286 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1287 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1288 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1289 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1290 
1291 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1292 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1293 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1294 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1295 
1296 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 
1298 	/* These are handled in ip_sioctl_copyin_setup itself */
1299 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1300 			MISC_CMD, NULL, NULL },
1301 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1302 			MISC_CMD, NULL, NULL },
1303 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1304 
1305 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1306 			ip_sioctl_get_lifconf, NULL },
1307 
1308 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1309 			XARP_CMD, ip_sioctl_arp, NULL },
1310 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1311 			XARP_CMD, ip_sioctl_arp, NULL },
1312 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1313 			XARP_CMD, ip_sioctl_arp, NULL },
1314 
1315 	/* SIOCPOPSOCKFS is not handled by IP */
1316 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1317 
1318 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1319 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1320 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1321 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1322 			ip_sioctl_slifzone_restart },
1323 	/* 172-174 are SCTP ioctls and not handled by IP */
1324 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1325 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1326 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1327 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1328 			IPI_GET_CMD, LIF_CMD,
1329 			ip_sioctl_get_lifusesrc, 0 },
1330 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1331 			IPI_PRIV | IPI_WR,
1332 			LIF_CMD, ip_sioctl_slifusesrc,
1333 			NULL },
1334 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1335 			ip_sioctl_get_lifsrcof, NULL },
1336 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1337 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1338 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1339 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1340 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1341 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1342 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1343 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1344 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1345 	/* SIOCSENABLESDP is handled by SDP */
1346 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1347 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1348 };
1349 
1350 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1351 
1352 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1353 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1354 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1355 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1356 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1357 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1358 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1359 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1360 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1361 		MISC_CMD, mrt_ioctl},
1362 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1363 		MISC_CMD, mrt_ioctl},
1364 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1365 		MISC_CMD, mrt_ioctl}
1366 };
1367 
1368 int ip_misc_ioctl_count =
1369     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1370 
1371 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1372 					/* Settable in /etc/system */
1373 /* Defined in ip_ire.c */
1374 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1375 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1376 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1377 
1378 static nv_t	ire_nv_arr[] = {
1379 	{ IRE_BROADCAST, "BROADCAST" },
1380 	{ IRE_LOCAL, "LOCAL" },
1381 	{ IRE_LOOPBACK, "LOOPBACK" },
1382 	{ IRE_CACHE, "CACHE" },
1383 	{ IRE_DEFAULT, "DEFAULT" },
1384 	{ IRE_PREFIX, "PREFIX" },
1385 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1386 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1387 	{ IRE_HOST, "HOST" },
1388 	{ 0 }
1389 };
1390 
1391 nv_t	*ire_nv_tbl = ire_nv_arr;
1392 
1393 /* Simple ICMP IP Header Template */
1394 static ipha_t icmp_ipha = {
1395 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1396 };
1397 
1398 struct module_info ip_mod_info = {
1399 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1400 	IP_MOD_LOWAT
1401 };
1402 
1403 /*
1404  * Duplicate static symbols within a module confuses mdb; so we avoid the
1405  * problem by making the symbols here distinct from those in udp.c.
1406  */
1407 
1408 /*
1409  * Entry points for IP as a device and as a module.
1410  * FIXME: down the road we might want a separate module and driver qinit.
1411  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1412  */
1413 static struct qinit iprinitv4 = {
1414 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1415 	&ip_mod_info
1416 };
1417 
1418 struct qinit iprinitv6 = {
1419 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1420 	&ip_mod_info
1421 };
1422 
1423 static struct qinit ipwinitv4 = {
1424 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1425 	&ip_mod_info
1426 };
1427 
1428 struct qinit ipwinitv6 = {
1429 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1430 	&ip_mod_info
1431 };
1432 
1433 static struct qinit iplrinit = {
1434 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1435 	&ip_mod_info
1436 };
1437 
1438 static struct qinit iplwinit = {
1439 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1440 	&ip_mod_info
1441 };
1442 
1443 /* For AF_INET aka /dev/ip */
1444 struct streamtab ipinfov4 = {
1445 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1446 };
1447 
1448 /* For AF_INET6 aka /dev/ip6 */
1449 struct streamtab ipinfov6 = {
1450 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1451 };
1452 
1453 #ifdef	DEBUG
1454 static boolean_t skip_sctp_cksum = B_FALSE;
1455 #endif
1456 
1457 /*
1458  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1459  * ip_rput_v6(), ip_output(), etc.  If the message
1460  * block already has a M_CTL at the front of it, then simply set the zoneid
1461  * appropriately.
1462  */
1463 mblk_t *
1464 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1465 {
1466 	mblk_t		*first_mp;
1467 	ipsec_out_t	*io;
1468 
1469 	ASSERT(zoneid != ALL_ZONES);
1470 	if (mp->b_datap->db_type == M_CTL) {
1471 		io = (ipsec_out_t *)mp->b_rptr;
1472 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1473 		io->ipsec_out_zoneid = zoneid;
1474 		return (mp);
1475 	}
1476 
1477 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1478 	if (first_mp == NULL)
1479 		return (NULL);
1480 	io = (ipsec_out_t *)first_mp->b_rptr;
1481 	/* This is not a secure packet */
1482 	io->ipsec_out_secure = B_FALSE;
1483 	io->ipsec_out_zoneid = zoneid;
1484 	first_mp->b_cont = mp;
1485 	return (first_mp);
1486 }
1487 
1488 /*
1489  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1490  */
1491 mblk_t *
1492 ip_copymsg(mblk_t *mp)
1493 {
1494 	mblk_t *nmp;
1495 	ipsec_info_t *in;
1496 
1497 	if (mp->b_datap->db_type != M_CTL)
1498 		return (copymsg(mp));
1499 
1500 	in = (ipsec_info_t *)mp->b_rptr;
1501 
1502 	/*
1503 	 * Note that M_CTL is also used for delivering ICMP error messages
1504 	 * upstream to transport layers.
1505 	 */
1506 	if (in->ipsec_info_type != IPSEC_OUT &&
1507 	    in->ipsec_info_type != IPSEC_IN)
1508 		return (copymsg(mp));
1509 
1510 	nmp = copymsg(mp->b_cont);
1511 
1512 	if (in->ipsec_info_type == IPSEC_OUT) {
1513 		return (ipsec_out_tag(mp, nmp,
1514 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1515 	} else {
1516 		return (ipsec_in_tag(mp, nmp,
1517 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1518 	}
1519 }
1520 
1521 /* Generate an ICMP fragmentation needed message. */
1522 static void
1523 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1524     ip_stack_t *ipst)
1525 {
1526 	icmph_t	icmph;
1527 	mblk_t *first_mp;
1528 	boolean_t mctl_present;
1529 
1530 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1531 
1532 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1533 		if (mctl_present)
1534 			freeb(first_mp);
1535 		return;
1536 	}
1537 
1538 	bzero(&icmph, sizeof (icmph_t));
1539 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1540 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1541 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1542 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1543 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1544 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1545 	    ipst);
1546 }
1547 
1548 /*
1549  * icmp_inbound deals with ICMP messages in the following ways.
1550  *
1551  * 1) It needs to send a reply back and possibly delivering it
1552  *    to the "interested" upper clients.
1553  * 2) It needs to send it to the upper clients only.
1554  * 3) It needs to change some values in IP only.
1555  * 4) It needs to change some values in IP and upper layers e.g TCP.
1556  *
1557  * We need to accomodate icmp messages coming in clear until we get
1558  * everything secure from the wire. If icmp_accept_clear_messages
1559  * is zero we check with the global policy and act accordingly. If
1560  * it is non-zero, we accept the message without any checks. But
1561  * *this does not mean* that this will be delivered to the upper
1562  * clients. By accepting we might send replies back, change our MTU
1563  * value etc. but delivery to the ULP/clients depends on their policy
1564  * dispositions.
1565  *
1566  * We handle the above 4 cases in the context of IPsec in the
1567  * following way :
1568  *
1569  * 1) Send the reply back in the same way as the request came in.
1570  *    If it came in encrypted, it goes out encrypted. If it came in
1571  *    clear, it goes out in clear. Thus, this will prevent chosen
1572  *    plain text attack.
1573  * 2) The client may or may not expect things to come in secure.
1574  *    If it comes in secure, the policy constraints are checked
1575  *    before delivering it to the upper layers. If it comes in
1576  *    clear, ipsec_inbound_accept_clear will decide whether to
1577  *    accept this in clear or not. In both the cases, if the returned
1578  *    message (IP header + 8 bytes) that caused the icmp message has
1579  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1580  *    sending up. If there are only 8 bytes of returned message, then
1581  *    upper client will not be notified.
1582  * 3) Check with global policy to see whether it matches the constaints.
1583  *    But this will be done only if icmp_accept_messages_in_clear is
1584  *    zero.
1585  * 4) If we need to change both in IP and ULP, then the decision taken
1586  *    while affecting the values in IP and while delivering up to TCP
1587  *    should be the same.
1588  *
1589  * 	There are two cases.
1590  *
1591  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1592  *	   failed), we will not deliver it to the ULP, even though they
1593  *	   are *willing* to accept in *clear*. This is fine as our global
1594  *	   disposition to icmp messages asks us reject the datagram.
1595  *
1596  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1597  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1598  *	   to deliver it to ULP (policy failed), it can lead to
1599  *	   consistency problems. The cases known at this time are
1600  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1601  *	   values :
1602  *
1603  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1604  *	     and Upper layer rejects. Then the communication will
1605  *	     come to a stop. This is solved by making similar decisions
1606  *	     at both levels. Currently, when we are unable to deliver
1607  *	     to the Upper Layer (due to policy failures) while IP has
1608  *	     adjusted ire_max_frag, the next outbound datagram would
1609  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1610  *	     will be with the right level of protection. Thus the right
1611  *	     value will be communicated even if we are not able to
1612  *	     communicate when we get from the wire initially. But this
1613  *	     assumes there would be at least one outbound datagram after
1614  *	     IP has adjusted its ire_max_frag value. To make things
1615  *	     simpler, we accept in clear after the validation of
1616  *	     AH/ESP headers.
1617  *
1618  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1619  *	     upper layer depending on the level of protection the upper
1620  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1621  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1622  *	     should be accepted in clear when the Upper layer expects secure.
1623  *	     Thus the communication may get aborted by some bad ICMP
1624  *	     packets.
1625  *
1626  * IPQoS Notes:
1627  * The only instance when a packet is sent for processing is when there
1628  * isn't an ICMP client and if we are interested in it.
1629  * If there is a client, IPPF processing will take place in the
1630  * ip_fanout_proto routine.
1631  *
1632  * Zones notes:
1633  * The packet is only processed in the context of the specified zone: typically
1634  * only this zone will reply to an echo request, and only interested clients in
1635  * this zone will receive a copy of the packet. This means that the caller must
1636  * call icmp_inbound() for each relevant zone.
1637  */
1638 static void
1639 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1640     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1641     ill_t *recv_ill, zoneid_t zoneid)
1642 {
1643 	icmph_t	*icmph;
1644 	ipha_t	*ipha;
1645 	int	iph_hdr_length;
1646 	int	hdr_length;
1647 	boolean_t	interested;
1648 	uint32_t	ts;
1649 	uchar_t	*wptr;
1650 	ipif_t	*ipif;
1651 	mblk_t *first_mp;
1652 	ipsec_in_t *ii;
1653 	timestruc_t now;
1654 	uint32_t ill_index;
1655 	ip_stack_t *ipst;
1656 
1657 	ASSERT(ill != NULL);
1658 	ipst = ill->ill_ipst;
1659 
1660 	first_mp = mp;
1661 	if (mctl_present) {
1662 		mp = first_mp->b_cont;
1663 		ASSERT(mp != NULL);
1664 	}
1665 
1666 	ipha = (ipha_t *)mp->b_rptr;
1667 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1668 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1669 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1670 		if (first_mp == NULL)
1671 			return;
1672 	}
1673 
1674 	/*
1675 	 * On a labeled system, we have to check whether the zone itself is
1676 	 * permitted to receive raw traffic.
1677 	 */
1678 	if (is_system_labeled()) {
1679 		if (zoneid == ALL_ZONES)
1680 			zoneid = tsol_packet_to_zoneid(mp);
1681 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1682 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1683 			    zoneid));
1684 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1685 			freemsg(first_mp);
1686 			return;
1687 		}
1688 	}
1689 
1690 	/*
1691 	 * We have accepted the ICMP message. It means that we will
1692 	 * respond to the packet if needed. It may not be delivered
1693 	 * to the upper client depending on the policy constraints
1694 	 * and the disposition in ipsec_inbound_accept_clear.
1695 	 */
1696 
1697 	ASSERT(ill != NULL);
1698 
1699 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1700 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1701 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1702 		/* Last chance to get real. */
1703 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1704 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1705 			freemsg(first_mp);
1706 			return;
1707 		}
1708 		/* Refresh iph following the pullup. */
1709 		ipha = (ipha_t *)mp->b_rptr;
1710 	}
1711 	/* ICMP header checksum, including checksum field, should be zero. */
1712 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1713 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1714 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1715 		freemsg(first_mp);
1716 		return;
1717 	}
1718 	/* The IP header will always be a multiple of four bytes */
1719 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1720 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1721 	    icmph->icmph_code));
1722 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1723 	/* We will set "interested" to "true" if we want a copy */
1724 	interested = B_FALSE;
1725 	switch (icmph->icmph_type) {
1726 	case ICMP_ECHO_REPLY:
1727 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1728 		break;
1729 	case ICMP_DEST_UNREACHABLE:
1730 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1731 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1732 		interested = B_TRUE;	/* Pass up to transport */
1733 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1734 		break;
1735 	case ICMP_SOURCE_QUENCH:
1736 		interested = B_TRUE;	/* Pass up to transport */
1737 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1738 		break;
1739 	case ICMP_REDIRECT:
1740 		if (!ipst->ips_ip_ignore_redirect)
1741 			interested = B_TRUE;
1742 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1743 		break;
1744 	case ICMP_ECHO_REQUEST:
1745 		/*
1746 		 * Whether to respond to echo requests that come in as IP
1747 		 * broadcasts or as IP multicast is subject to debate
1748 		 * (what isn't?).  We aim to please, you pick it.
1749 		 * Default is do it.
1750 		 */
1751 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1752 			/* unicast: always respond */
1753 			interested = B_TRUE;
1754 		} else if (CLASSD(ipha->ipha_dst)) {
1755 			/* multicast: respond based on tunable */
1756 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1757 		} else if (broadcast) {
1758 			/* broadcast: respond based on tunable */
1759 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1760 		}
1761 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1762 		break;
1763 	case ICMP_ROUTER_ADVERTISEMENT:
1764 	case ICMP_ROUTER_SOLICITATION:
1765 		break;
1766 	case ICMP_TIME_EXCEEDED:
1767 		interested = B_TRUE;	/* Pass up to transport */
1768 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1769 		break;
1770 	case ICMP_PARAM_PROBLEM:
1771 		interested = B_TRUE;	/* Pass up to transport */
1772 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1773 		break;
1774 	case ICMP_TIME_STAMP_REQUEST:
1775 		/* Response to Time Stamp Requests is local policy. */
1776 		if (ipst->ips_ip_g_resp_to_timestamp &&
1777 		    /* So is whether to respond if it was an IP broadcast. */
1778 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1779 			int tstamp_len = 3 * sizeof (uint32_t);
1780 
1781 			if (wptr +  tstamp_len > mp->b_wptr) {
1782 				if (!pullupmsg(mp, wptr + tstamp_len -
1783 				    mp->b_rptr)) {
1784 					BUMP_MIB(ill->ill_ip_mib,
1785 					    ipIfStatsInDiscards);
1786 					freemsg(first_mp);
1787 					return;
1788 				}
1789 				/* Refresh ipha following the pullup. */
1790 				ipha = (ipha_t *)mp->b_rptr;
1791 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1792 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1793 			}
1794 			interested = B_TRUE;
1795 		}
1796 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1797 		break;
1798 	case ICMP_TIME_STAMP_REPLY:
1799 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1800 		break;
1801 	case ICMP_INFO_REQUEST:
1802 		/* Per RFC 1122 3.2.2.7, ignore this. */
1803 	case ICMP_INFO_REPLY:
1804 		break;
1805 	case ICMP_ADDRESS_MASK_REQUEST:
1806 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1807 		    !broadcast) &&
1808 		    /* TODO m_pullup of complete header? */
1809 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1810 			interested = B_TRUE;
1811 		}
1812 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1813 		break;
1814 	case ICMP_ADDRESS_MASK_REPLY:
1815 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1816 		break;
1817 	default:
1818 		interested = B_TRUE;	/* Pass up to transport */
1819 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1820 		break;
1821 	}
1822 	/* See if there is an ICMP client. */
1823 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1824 		/* If there is an ICMP client and we want one too, copy it. */
1825 		mblk_t *first_mp1;
1826 
1827 		if (!interested) {
1828 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1829 			    ip_policy, recv_ill, zoneid);
1830 			return;
1831 		}
1832 		first_mp1 = ip_copymsg(first_mp);
1833 		if (first_mp1 != NULL) {
1834 			ip_fanout_proto(q, first_mp1, ill, ipha,
1835 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1836 		}
1837 	} else if (!interested) {
1838 		freemsg(first_mp);
1839 		return;
1840 	} else {
1841 		/*
1842 		 * Initiate policy processing for this packet if ip_policy
1843 		 * is true.
1844 		 */
1845 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1846 			ill_index = ill->ill_phyint->phyint_ifindex;
1847 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1848 			if (mp == NULL) {
1849 				if (mctl_present) {
1850 					freeb(first_mp);
1851 				}
1852 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1853 				return;
1854 			}
1855 		}
1856 	}
1857 	/* We want to do something with it. */
1858 	/* Check db_ref to make sure we can modify the packet. */
1859 	if (mp->b_datap->db_ref > 1) {
1860 		mblk_t	*first_mp1;
1861 
1862 		first_mp1 = ip_copymsg(first_mp);
1863 		freemsg(first_mp);
1864 		if (!first_mp1) {
1865 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1866 			return;
1867 		}
1868 		first_mp = first_mp1;
1869 		if (mctl_present) {
1870 			mp = first_mp->b_cont;
1871 			ASSERT(mp != NULL);
1872 		} else {
1873 			mp = first_mp;
1874 		}
1875 		ipha = (ipha_t *)mp->b_rptr;
1876 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1877 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1878 	}
1879 	switch (icmph->icmph_type) {
1880 	case ICMP_ADDRESS_MASK_REQUEST:
1881 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1882 		if (ipif == NULL) {
1883 			freemsg(first_mp);
1884 			return;
1885 		}
1886 		/*
1887 		 * outging interface must be IPv4
1888 		 */
1889 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1890 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1891 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1892 		ipif_refrele(ipif);
1893 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1894 		break;
1895 	case ICMP_ECHO_REQUEST:
1896 		icmph->icmph_type = ICMP_ECHO_REPLY;
1897 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1898 		break;
1899 	case ICMP_TIME_STAMP_REQUEST: {
1900 		uint32_t *tsp;
1901 
1902 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1903 		tsp = (uint32_t *)wptr;
1904 		tsp++;		/* Skip past 'originate time' */
1905 		/* Compute # of milliseconds since midnight */
1906 		gethrestime(&now);
1907 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1908 		    now.tv_nsec / (NANOSEC / MILLISEC);
1909 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1910 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1911 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1912 		break;
1913 	}
1914 	default:
1915 		ipha = (ipha_t *)&icmph[1];
1916 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1917 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1918 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1919 				freemsg(first_mp);
1920 				return;
1921 			}
1922 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1923 			ipha = (ipha_t *)&icmph[1];
1924 		}
1925 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1926 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1927 			freemsg(first_mp);
1928 			return;
1929 		}
1930 		hdr_length = IPH_HDR_LENGTH(ipha);
1931 		if (hdr_length < sizeof (ipha_t)) {
1932 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1933 			freemsg(first_mp);
1934 			return;
1935 		}
1936 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1937 			if (!pullupmsg(mp,
1938 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1939 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1940 				freemsg(first_mp);
1941 				return;
1942 			}
1943 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1944 			ipha = (ipha_t *)&icmph[1];
1945 		}
1946 		switch (icmph->icmph_type) {
1947 		case ICMP_REDIRECT:
1948 			/*
1949 			 * As there is no upper client to deliver, we don't
1950 			 * need the first_mp any more.
1951 			 */
1952 			if (mctl_present) {
1953 				freeb(first_mp);
1954 			}
1955 			icmp_redirect(ill, mp);
1956 			return;
1957 		case ICMP_DEST_UNREACHABLE:
1958 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1959 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1960 				    zoneid, mp, iph_hdr_length, ipst)) {
1961 					freemsg(first_mp);
1962 					return;
1963 				}
1964 				/*
1965 				 * icmp_inbound_too_big() may alter mp.
1966 				 * Resynch ipha and icmph accordingly.
1967 				 */
1968 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1969 				ipha = (ipha_t *)&icmph[1];
1970 			}
1971 			/* FALLTHRU */
1972 		default :
1973 			/*
1974 			 * IPQoS notes: Since we have already done IPQoS
1975 			 * processing we don't want to do it again in
1976 			 * the fanout routines called by
1977 			 * icmp_inbound_error_fanout, hence the last
1978 			 * argument, ip_policy, is B_FALSE.
1979 			 */
1980 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1981 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1982 			    B_FALSE, recv_ill, zoneid);
1983 		}
1984 		return;
1985 	}
1986 	/* Send out an ICMP packet */
1987 	icmph->icmph_checksum = 0;
1988 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1989 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1990 		ipif_t	*ipif_chosen;
1991 		/*
1992 		 * Make it look like it was directed to us, so we don't look
1993 		 * like a fool with a broadcast or multicast source address.
1994 		 */
1995 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1996 		/*
1997 		 * Make sure that we haven't grabbed an interface that's DOWN.
1998 		 */
1999 		if (ipif != NULL) {
2000 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2001 			    ipha->ipha_src, zoneid);
2002 			if (ipif_chosen != NULL) {
2003 				ipif_refrele(ipif);
2004 				ipif = ipif_chosen;
2005 			}
2006 		}
2007 		if (ipif == NULL) {
2008 			ip0dbg(("icmp_inbound: "
2009 			    "No source for broadcast/multicast:\n"
2010 			    "\tsrc 0x%x dst 0x%x ill %p "
2011 			    "ipif_lcl_addr 0x%x\n",
2012 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2013 			    (void *)ill,
2014 			    ill->ill_ipif->ipif_lcl_addr));
2015 			freemsg(first_mp);
2016 			return;
2017 		}
2018 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2019 		ipha->ipha_dst = ipif->ipif_src_addr;
2020 		ipif_refrele(ipif);
2021 	}
2022 	/* Reset time to live. */
2023 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2024 	{
2025 		/* Swap source and destination addresses */
2026 		ipaddr_t tmp;
2027 
2028 		tmp = ipha->ipha_src;
2029 		ipha->ipha_src = ipha->ipha_dst;
2030 		ipha->ipha_dst = tmp;
2031 	}
2032 	ipha->ipha_ident = 0;
2033 	if (!IS_SIMPLE_IPH(ipha))
2034 		icmp_options_update(ipha);
2035 
2036 	if (!mctl_present) {
2037 		/*
2038 		 * This packet should go out the same way as it
2039 		 * came in i.e in clear. To make sure that global
2040 		 * policy will not be applied to this in ip_wput_ire,
2041 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2042 		 */
2043 		ASSERT(first_mp == mp);
2044 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2045 		if (first_mp == NULL) {
2046 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2047 			freemsg(mp);
2048 			return;
2049 		}
2050 		ii = (ipsec_in_t *)first_mp->b_rptr;
2051 
2052 		/* This is not a secure packet */
2053 		ii->ipsec_in_secure = B_FALSE;
2054 		first_mp->b_cont = mp;
2055 	} else {
2056 		ii = (ipsec_in_t *)first_mp->b_rptr;
2057 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2058 	}
2059 	ii->ipsec_in_zoneid = zoneid;
2060 	ASSERT(zoneid != ALL_ZONES);
2061 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2062 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2063 		return;
2064 	}
2065 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2066 	put(WR(q), first_mp);
2067 }
2068 
2069 static ipaddr_t
2070 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2071 {
2072 	conn_t *connp;
2073 	connf_t *connfp;
2074 	ipaddr_t nexthop_addr = INADDR_ANY;
2075 	int hdr_length = IPH_HDR_LENGTH(ipha);
2076 	uint16_t *up;
2077 	uint32_t ports;
2078 	ip_stack_t *ipst = ill->ill_ipst;
2079 
2080 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2081 	switch (ipha->ipha_protocol) {
2082 		case IPPROTO_TCP:
2083 		{
2084 			tcph_t *tcph;
2085 
2086 			/* do a reverse lookup */
2087 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2088 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2089 			    TCPS_LISTEN, ipst);
2090 			break;
2091 		}
2092 		case IPPROTO_UDP:
2093 		{
2094 			uint32_t dstport, srcport;
2095 
2096 			((uint16_t *)&ports)[0] = up[1];
2097 			((uint16_t *)&ports)[1] = up[0];
2098 
2099 			/* Extract ports in net byte order */
2100 			dstport = htons(ntohl(ports) & 0xFFFF);
2101 			srcport = htons(ntohl(ports) >> 16);
2102 
2103 			connfp = &ipst->ips_ipcl_udp_fanout[
2104 			    IPCL_UDP_HASH(dstport, ipst)];
2105 			mutex_enter(&connfp->connf_lock);
2106 			connp = connfp->connf_head;
2107 
2108 			/* do a reverse lookup */
2109 			while ((connp != NULL) &&
2110 			    (!IPCL_UDP_MATCH(connp, dstport,
2111 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2112 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2113 				connp = connp->conn_next;
2114 			}
2115 			if (connp != NULL)
2116 				CONN_INC_REF(connp);
2117 			mutex_exit(&connfp->connf_lock);
2118 			break;
2119 		}
2120 		case IPPROTO_SCTP:
2121 		{
2122 			in6_addr_t map_src, map_dst;
2123 
2124 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2125 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2126 			((uint16_t *)&ports)[0] = up[1];
2127 			((uint16_t *)&ports)[1] = up[0];
2128 
2129 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2130 			    zoneid, ipst->ips_netstack->netstack_sctp);
2131 			if (connp == NULL) {
2132 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2133 				    zoneid, ports, ipha, ipst);
2134 			} else {
2135 				CONN_INC_REF(connp);
2136 				SCTP_REFRELE(CONN2SCTP(connp));
2137 			}
2138 			break;
2139 		}
2140 		default:
2141 		{
2142 			ipha_t ripha;
2143 
2144 			ripha.ipha_src = ipha->ipha_dst;
2145 			ripha.ipha_dst = ipha->ipha_src;
2146 			ripha.ipha_protocol = ipha->ipha_protocol;
2147 
2148 			connfp = &ipst->ips_ipcl_proto_fanout[
2149 			    ipha->ipha_protocol];
2150 			mutex_enter(&connfp->connf_lock);
2151 			connp = connfp->connf_head;
2152 			for (connp = connfp->connf_head; connp != NULL;
2153 			    connp = connp->conn_next) {
2154 				if (IPCL_PROTO_MATCH(connp,
2155 				    ipha->ipha_protocol, &ripha, ill,
2156 				    0, zoneid)) {
2157 					CONN_INC_REF(connp);
2158 					break;
2159 				}
2160 			}
2161 			mutex_exit(&connfp->connf_lock);
2162 		}
2163 	}
2164 	if (connp != NULL) {
2165 		if (connp->conn_nexthop_set)
2166 			nexthop_addr = connp->conn_nexthop_v4;
2167 		CONN_DEC_REF(connp);
2168 	}
2169 	return (nexthop_addr);
2170 }
2171 
2172 /* Table from RFC 1191 */
2173 static int icmp_frag_size_table[] =
2174 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2175 
2176 /*
2177  * Process received ICMP Packet too big.
2178  * After updating any IRE it does the fanout to any matching transport streams.
2179  * Assumes the message has been pulled up till the IP header that caused
2180  * the error.
2181  *
2182  * Returns B_FALSE on failure and B_TRUE on success.
2183  */
2184 static boolean_t
2185 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2186     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2187     ip_stack_t *ipst)
2188 {
2189 	ire_t	*ire, *first_ire;
2190 	int	mtu, orig_mtu;
2191 	int	hdr_length;
2192 	ipaddr_t nexthop_addr;
2193 	boolean_t disable_pmtud;
2194 
2195 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2196 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2197 	ASSERT(ill != NULL);
2198 
2199 	hdr_length = IPH_HDR_LENGTH(ipha);
2200 
2201 	/* Drop if the original packet contained a source route */
2202 	if (ip_source_route_included(ipha)) {
2203 		return (B_FALSE);
2204 	}
2205 	/*
2206 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2207 	 * header.
2208 	 */
2209 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2210 	    mp->b_wptr) {
2211 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2212 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2213 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2214 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2215 			return (B_FALSE);
2216 		}
2217 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2218 		ipha = (ipha_t *)&icmph[1];
2219 	}
2220 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2221 	if (nexthop_addr != INADDR_ANY) {
2222 		/* nexthop set */
2223 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2224 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2225 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2226 	} else {
2227 		/* nexthop not set */
2228 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2229 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2230 	}
2231 
2232 	if (!first_ire) {
2233 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2234 		    ntohl(ipha->ipha_dst)));
2235 		return (B_FALSE);
2236 	}
2237 
2238 	/* Check for MTU discovery advice as described in RFC 1191 */
2239 	mtu = ntohs(icmph->icmph_du_mtu);
2240 	orig_mtu = mtu;
2241 	disable_pmtud = B_FALSE;
2242 
2243 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2244 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2245 	    ire = ire->ire_next) {
2246 		/*
2247 		 * Look for the connection to which this ICMP message is
2248 		 * directed. If it has the IP_NEXTHOP option set, then the
2249 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2250 		 * option. Else the search is limited to regular IREs.
2251 		 */
2252 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2253 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2254 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2255 		    (nexthop_addr != INADDR_ANY)))
2256 			continue;
2257 
2258 		mutex_enter(&ire->ire_lock);
2259 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2260 			uint32_t length;
2261 			int	i;
2262 
2263 			/*
2264 			 * Use the table from RFC 1191 to figure out
2265 			 * the next "plateau" based on the length in
2266 			 * the original IP packet.
2267 			 */
2268 			length = ntohs(ipha->ipha_length);
2269 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2270 			    uint32_t, length);
2271 			if (ire->ire_max_frag <= length &&
2272 			    ire->ire_max_frag >= length - hdr_length) {
2273 				/*
2274 				 * Handle broken BSD 4.2 systems that
2275 				 * return the wrong iph_length in ICMP
2276 				 * errors.
2277 				 */
2278 				length -= hdr_length;
2279 			}
2280 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2281 				if (length > icmp_frag_size_table[i])
2282 					break;
2283 			}
2284 			if (i == A_CNT(icmp_frag_size_table)) {
2285 				/* Smaller than 68! */
2286 				disable_pmtud = B_TRUE;
2287 				mtu = ipst->ips_ip_pmtu_min;
2288 			} else {
2289 				mtu = icmp_frag_size_table[i];
2290 				if (mtu < ipst->ips_ip_pmtu_min) {
2291 					mtu = ipst->ips_ip_pmtu_min;
2292 					disable_pmtud = B_TRUE;
2293 				}
2294 			}
2295 			/* Fool the ULP into believing our guessed PMTU. */
2296 			icmph->icmph_du_zero = 0;
2297 			icmph->icmph_du_mtu = htons(mtu);
2298 		}
2299 		if (disable_pmtud)
2300 			ire->ire_frag_flag = 0;
2301 		/* Reduce the IRE max frag value as advised. */
2302 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2303 		if (ire->ire_max_frag == mtu) {
2304 			/* Decreased it */
2305 			ire->ire_marks |= IRE_MARK_PMTU;
2306 		}
2307 		mutex_exit(&ire->ire_lock);
2308 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2309 		    ire, int, orig_mtu, int, mtu);
2310 	}
2311 	rw_exit(&first_ire->ire_bucket->irb_lock);
2312 	ire_refrele(first_ire);
2313 	return (B_TRUE);
2314 }
2315 
2316 /*
2317  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2318  * calls this function.
2319  */
2320 static mblk_t *
2321 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2322 {
2323 	ipha_t *ipha;
2324 	icmph_t *icmph;
2325 	ipha_t *in_ipha;
2326 	int length;
2327 
2328 	ASSERT(mp->b_datap->db_type == M_DATA);
2329 
2330 	/*
2331 	 * For Self-encapsulated packets, we added an extra IP header
2332 	 * without the options. Inner IP header is the one from which
2333 	 * the outer IP header was formed. Thus, we need to remove the
2334 	 * outer IP header. To do this, we pullup the whole message
2335 	 * and overlay whatever follows the outer IP header over the
2336 	 * outer IP header.
2337 	 */
2338 
2339 	if (!pullupmsg(mp, -1))
2340 		return (NULL);
2341 
2342 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2343 	ipha = (ipha_t *)&icmph[1];
2344 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2345 
2346 	/*
2347 	 * The length that we want to overlay is following the inner
2348 	 * IP header. Subtracting the IP header + icmp header + outer
2349 	 * IP header's length should give us the length that we want to
2350 	 * overlay.
2351 	 */
2352 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2353 	    hdr_length;
2354 	/*
2355 	 * Overlay whatever follows the inner header over the
2356 	 * outer header.
2357 	 */
2358 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2359 
2360 	/* Set the wptr to account for the outer header */
2361 	mp->b_wptr -= hdr_length;
2362 	return (mp);
2363 }
2364 
2365 /*
2366  * Fanout for ICMP errors containing IP-in-IPv4 packets.  Returns B_TRUE if a
2367  * tunnel consumed the message, and B_FALSE otherwise.
2368  */
2369 static boolean_t
2370 icmp_inbound_iptun_fanout(mblk_t *first_mp, ipha_t *ripha, ill_t *ill,
2371     ip_stack_t *ipst)
2372 {
2373 	conn_t	*connp;
2374 
2375 	if ((connp = ipcl_iptun_classify_v4(&ripha->ipha_src, &ripha->ipha_dst,
2376 	    ipst)) == NULL)
2377 		return (B_FALSE);
2378 
2379 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
2380 	connp->conn_recv(connp, first_mp, NULL);
2381 	CONN_DEC_REF(connp);
2382 	return (B_TRUE);
2383 }
2384 
2385 /*
2386  * Try to pass the ICMP message upstream in case the ULP cares.
2387  *
2388  * If the packet that caused the ICMP error is secure, we send
2389  * it to AH/ESP to make sure that the attached packet has a
2390  * valid association. ipha in the code below points to the
2391  * IP header of the packet that caused the error.
2392  *
2393  * For IPsec cases, we let the next-layer-up (which has access to
2394  * cached policy on the conn_t, or can query the SPD directly)
2395  * subtract out any IPsec overhead if they must.  We therefore make no
2396  * adjustments here for IPsec overhead.
2397  *
2398  * IFN could have been generated locally or by some router.
2399  *
2400  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2401  *	    This happens because IP adjusted its value of MTU on an
2402  *	    earlier IFN message and could not tell the upper layer,
2403  *	    the new adjusted value of MTU e.g. Packet was encrypted
2404  *	    or there was not enough information to fanout to upper
2405  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2406  *	    generates the IFN, where IPsec processing has *not* been
2407  *	    done.
2408  *
2409  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2410  *	    could have generated this. This happens because ire_max_frag
2411  *	    value in IP was set to a new value, while the IPsec processing
2412  *	    was being done and after we made the fragmentation check in
2413  *	    ip_wput_ire. Thus on return from IPsec processing,
2414  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2415  *	    and generates the IFN. As IPsec processing is over, we fanout
2416  *	    to AH/ESP to remove the header.
2417  *
2418  *	    In both these cases, ipsec_in_loopback will be set indicating
2419  *	    that IFN was generated locally.
2420  *
2421  * ROUTER : IFN could be secure or non-secure.
2422  *
2423  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2424  *	      packet in error has AH/ESP headers to validate the AH/ESP
2425  *	      headers. AH/ESP will verify whether there is a valid SA or
2426  *	      not and send it back. We will fanout again if we have more
2427  *	      data in the packet.
2428  *
2429  *	      If the packet in error does not have AH/ESP, we handle it
2430  *	      like any other case.
2431  *
2432  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2433  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2434  *	      for validation. AH/ESP will verify whether there is a
2435  *	      valid SA or not and send it back. We will fanout again if
2436  *	      we have more data in the packet.
2437  *
2438  *	      If the packet in error does not have AH/ESP, we handle it
2439  *	      like any other case.
2440  */
2441 static void
2442 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2443     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2444     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2445     zoneid_t zoneid)
2446 {
2447 	uint16_t *up;	/* Pointer to ports in ULP header */
2448 	uint32_t ports;	/* reversed ports for fanout */
2449 	ipha_t ripha;	/* With reversed addresses */
2450 	mblk_t *first_mp;
2451 	ipsec_in_t *ii;
2452 	tcph_t	*tcph;
2453 	conn_t	*connp;
2454 	ip_stack_t *ipst;
2455 
2456 	ASSERT(ill != NULL);
2457 
2458 	ASSERT(recv_ill != NULL);
2459 	ipst = recv_ill->ill_ipst;
2460 
2461 	first_mp = mp;
2462 	if (mctl_present) {
2463 		mp = first_mp->b_cont;
2464 		ASSERT(mp != NULL);
2465 
2466 		ii = (ipsec_in_t *)first_mp->b_rptr;
2467 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2468 	} else {
2469 		ii = NULL;
2470 	}
2471 
2472 	/*
2473 	 * We need a separate IP header with the source and destination
2474 	 * addresses reversed to do fanout/classification because the ipha in
2475 	 * the ICMP error is in the form we sent it out.
2476 	 */
2477 	ripha.ipha_src = ipha->ipha_dst;
2478 	ripha.ipha_dst = ipha->ipha_src;
2479 	ripha.ipha_protocol = ipha->ipha_protocol;
2480 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2481 
2482 	ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2483 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2484 	    ntohl(ipha->ipha_dst),
2485 	    icmph->icmph_type, icmph->icmph_code));
2486 
2487 	switch (ipha->ipha_protocol) {
2488 	case IPPROTO_UDP:
2489 		/*
2490 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2491 		 * transport header.
2492 		 */
2493 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2494 		    mp->b_wptr) {
2495 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2496 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2497 				goto discard_pkt;
2498 			}
2499 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2500 			ipha = (ipha_t *)&icmph[1];
2501 		}
2502 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2503 
2504 		/* Attempt to find a client stream based on port. */
2505 		((uint16_t *)&ports)[0] = up[1];
2506 		((uint16_t *)&ports)[1] = up[0];
2507 		ip2dbg(("icmp_inbound_error: UDP ports %d to %d\n",
2508 		    ntohs(up[0]), ntohs(up[1])));
2509 
2510 		/* Have to change db_type after any pullupmsg */
2511 		DB_TYPE(mp) = M_CTL;
2512 
2513 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2514 		    mctl_present, ip_policy, recv_ill, zoneid);
2515 		return;
2516 
2517 	case IPPROTO_TCP:
2518 		/*
2519 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2520 		 * transport header.
2521 		 */
2522 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2523 		    mp->b_wptr) {
2524 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2525 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2526 				goto discard_pkt;
2527 			}
2528 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2529 			ipha = (ipha_t *)&icmph[1];
2530 		}
2531 		/*
2532 		 * Find a TCP client stream for this packet.
2533 		 * Note that we do a reverse lookup since the header is
2534 		 * in the form we sent it out.
2535 		 */
2536 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2537 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2538 		    ipst);
2539 		if (connp == NULL)
2540 			goto discard_pkt;
2541 
2542 		/* Have to change db_type after any pullupmsg */
2543 		DB_TYPE(mp) = M_CTL;
2544 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2545 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2546 		return;
2547 
2548 	case IPPROTO_SCTP:
2549 		/*
2550 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2551 		 * transport header.
2552 		 */
2553 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2554 		    mp->b_wptr) {
2555 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2556 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2557 				goto discard_pkt;
2558 			}
2559 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2560 			ipha = (ipha_t *)&icmph[1];
2561 		}
2562 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2563 		/* Find a SCTP client stream for this packet. */
2564 		((uint16_t *)&ports)[0] = up[1];
2565 		((uint16_t *)&ports)[1] = up[0];
2566 
2567 		/* Have to change db_type after any pullupmsg */
2568 		DB_TYPE(mp) = M_CTL;
2569 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2570 		    mctl_present, ip_policy, zoneid);
2571 		return;
2572 
2573 	case IPPROTO_ESP:
2574 	case IPPROTO_AH: {
2575 		int ipsec_rc;
2576 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2577 
2578 		/*
2579 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2580 		 * We will re-use the IPSEC_IN if it is already present as
2581 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2582 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2583 		 * one and attach it in the front.
2584 		 */
2585 		if (ii != NULL) {
2586 			/*
2587 			 * ip_fanout_proto_again converts the ICMP errors
2588 			 * that come back from AH/ESP to M_DATA so that
2589 			 * if it is non-AH/ESP and we do a pullupmsg in
2590 			 * this function, it would work. Convert it back
2591 			 * to M_CTL before we send up as this is a ICMP
2592 			 * error. This could have been generated locally or
2593 			 * by some router. Validate the inner IPsec
2594 			 * headers.
2595 			 *
2596 			 * NOTE : ill_index is used by ip_fanout_proto_again
2597 			 * to locate the ill.
2598 			 */
2599 			ASSERT(ill != NULL);
2600 			ii->ipsec_in_ill_index =
2601 			    ill->ill_phyint->phyint_ifindex;
2602 			ii->ipsec_in_rill_index =
2603 			    recv_ill->ill_phyint->phyint_ifindex;
2604 			DB_TYPE(first_mp->b_cont) = M_CTL;
2605 		} else {
2606 			/*
2607 			 * IPSEC_IN is not present. We attach a ipsec_in
2608 			 * message and send up to IPsec for validating
2609 			 * and removing the IPsec headers. Clear
2610 			 * ipsec_in_secure so that when we return
2611 			 * from IPsec, we don't mistakenly think that this
2612 			 * is a secure packet came from the network.
2613 			 *
2614 			 * NOTE : ill_index is used by ip_fanout_proto_again
2615 			 * to locate the ill.
2616 			 */
2617 			ASSERT(first_mp == mp);
2618 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2619 			if (first_mp == NULL) {
2620 				freemsg(mp);
2621 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2622 				return;
2623 			}
2624 			ii = (ipsec_in_t *)first_mp->b_rptr;
2625 
2626 			/* This is not a secure packet */
2627 			ii->ipsec_in_secure = B_FALSE;
2628 			first_mp->b_cont = mp;
2629 			DB_TYPE(mp) = M_CTL;
2630 			ASSERT(ill != NULL);
2631 			ii->ipsec_in_ill_index =
2632 			    ill->ill_phyint->phyint_ifindex;
2633 			ii->ipsec_in_rill_index =
2634 			    recv_ill->ill_phyint->phyint_ifindex;
2635 		}
2636 
2637 		if (!ipsec_loaded(ipss)) {
2638 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2639 			return;
2640 		}
2641 
2642 		if (ipha->ipha_protocol == IPPROTO_ESP)
2643 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2644 		else
2645 			ipsec_rc = ipsecah_icmp_error(first_mp);
2646 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2647 			return;
2648 
2649 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2650 		return;
2651 	}
2652 	case IPPROTO_ENCAP:
2653 	case IPPROTO_IPV6:
2654 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2655 			ipha_t *in_ipha;
2656 
2657 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2658 			    mp->b_wptr) {
2659 				if (!pullupmsg(mp, (uchar_t *)ipha +
2660 				    hdr_length + sizeof (ipha_t) -
2661 				    mp->b_rptr)) {
2662 					goto discard_pkt;
2663 				}
2664 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2665 				ipha = (ipha_t *)&icmph[1];
2666 			}
2667 			/*
2668 			 * Caller has verified that length has to be
2669 			 * at least the size of IP header.
2670 			 */
2671 			ASSERT(hdr_length >= sizeof (ipha_t));
2672 			/*
2673 			 * Check the sanity of the inner IP header like
2674 			 * we did for the outer header.
2675 			 */
2676 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2677 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION) ||
2678 			    IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t))
2679 				goto discard_pkt;
2680 			/* Check for Self-encapsulated tunnels */
2681 			if (in_ipha->ipha_src == ipha->ipha_src &&
2682 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2683 
2684 				mp = icmp_inbound_self_encap_error(mp,
2685 				    iph_hdr_length, hdr_length);
2686 				if (mp == NULL)
2687 					goto discard_pkt;
2688 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2689 				ipha = (ipha_t *)&icmph[1];
2690 				hdr_length = IPH_HDR_LENGTH(ipha);
2691 				/*
2692 				 * The packet in error is self-encapsualted.
2693 				 * And we are finding it further encapsulated
2694 				 * which we could not have possibly generated.
2695 				 */
2696 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2697 					goto discard_pkt;
2698 				}
2699 				icmp_inbound_error_fanout(q, ill, first_mp,
2700 				    icmph, ipha, iph_hdr_length, hdr_length,
2701 				    mctl_present, ip_policy, recv_ill, zoneid);
2702 				return;
2703 			}
2704 		}
2705 
2706 		DB_TYPE(mp) = M_CTL;
2707 		if (icmp_inbound_iptun_fanout(first_mp, &ripha, ill, ipst))
2708 			return;
2709 		/*
2710 		 * No IP tunnel is interested, fallthrough and see
2711 		 * if a raw socket will want it.
2712 		 */
2713 		/* FALLTHRU */
2714 	default:
2715 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2716 		    ip_policy, recv_ill, zoneid);
2717 		return;
2718 	}
2719 	/* NOTREACHED */
2720 discard_pkt:
2721 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2722 drop_pkt:;
2723 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2724 	freemsg(first_mp);
2725 }
2726 
2727 /*
2728  * Common IP options parser.
2729  *
2730  * Setup routine: fill in *optp with options-parsing state, then
2731  * tail-call ipoptp_next to return the first option.
2732  */
2733 uint8_t
2734 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2735 {
2736 	uint32_t totallen; /* total length of all options */
2737 
2738 	totallen = ipha->ipha_version_and_hdr_length -
2739 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2740 	totallen <<= 2;
2741 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2742 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2743 	optp->ipoptp_flags = 0;
2744 	return (ipoptp_next(optp));
2745 }
2746 
2747 /*
2748  * Common IP options parser: extract next option.
2749  */
2750 uint8_t
2751 ipoptp_next(ipoptp_t *optp)
2752 {
2753 	uint8_t *end = optp->ipoptp_end;
2754 	uint8_t *cur = optp->ipoptp_next;
2755 	uint8_t opt, len, pointer;
2756 
2757 	/*
2758 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2759 	 * has been corrupted.
2760 	 */
2761 	ASSERT(cur <= end);
2762 
2763 	if (cur == end)
2764 		return (IPOPT_EOL);
2765 
2766 	opt = cur[IPOPT_OPTVAL];
2767 
2768 	/*
2769 	 * Skip any NOP options.
2770 	 */
2771 	while (opt == IPOPT_NOP) {
2772 		cur++;
2773 		if (cur == end)
2774 			return (IPOPT_EOL);
2775 		opt = cur[IPOPT_OPTVAL];
2776 	}
2777 
2778 	if (opt == IPOPT_EOL)
2779 		return (IPOPT_EOL);
2780 
2781 	/*
2782 	 * Option requiring a length.
2783 	 */
2784 	if ((cur + 1) >= end) {
2785 		optp->ipoptp_flags |= IPOPTP_ERROR;
2786 		return (IPOPT_EOL);
2787 	}
2788 	len = cur[IPOPT_OLEN];
2789 	if (len < 2) {
2790 		optp->ipoptp_flags |= IPOPTP_ERROR;
2791 		return (IPOPT_EOL);
2792 	}
2793 	optp->ipoptp_cur = cur;
2794 	optp->ipoptp_len = len;
2795 	optp->ipoptp_next = cur + len;
2796 	if (cur + len > end) {
2797 		optp->ipoptp_flags |= IPOPTP_ERROR;
2798 		return (IPOPT_EOL);
2799 	}
2800 
2801 	/*
2802 	 * For the options which require a pointer field, make sure
2803 	 * its there, and make sure it points to either something
2804 	 * inside this option, or the end of the option.
2805 	 */
2806 	switch (opt) {
2807 	case IPOPT_RR:
2808 	case IPOPT_TS:
2809 	case IPOPT_LSRR:
2810 	case IPOPT_SSRR:
2811 		if (len <= IPOPT_OFFSET) {
2812 			optp->ipoptp_flags |= IPOPTP_ERROR;
2813 			return (opt);
2814 		}
2815 		pointer = cur[IPOPT_OFFSET];
2816 		if (pointer - 1 > len) {
2817 			optp->ipoptp_flags |= IPOPTP_ERROR;
2818 			return (opt);
2819 		}
2820 		break;
2821 	}
2822 
2823 	/*
2824 	 * Sanity check the pointer field based on the type of the
2825 	 * option.
2826 	 */
2827 	switch (opt) {
2828 	case IPOPT_RR:
2829 	case IPOPT_SSRR:
2830 	case IPOPT_LSRR:
2831 		if (pointer < IPOPT_MINOFF_SR)
2832 			optp->ipoptp_flags |= IPOPTP_ERROR;
2833 		break;
2834 	case IPOPT_TS:
2835 		if (pointer < IPOPT_MINOFF_IT)
2836 			optp->ipoptp_flags |= IPOPTP_ERROR;
2837 		/*
2838 		 * Note that the Internet Timestamp option also
2839 		 * contains two four bit fields (the Overflow field,
2840 		 * and the Flag field), which follow the pointer
2841 		 * field.  We don't need to check that these fields
2842 		 * fall within the length of the option because this
2843 		 * was implicitely done above.  We've checked that the
2844 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2845 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2846 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2847 		 */
2848 		ASSERT(len > IPOPT_POS_OV_FLG);
2849 		break;
2850 	}
2851 
2852 	return (opt);
2853 }
2854 
2855 /*
2856  * Use the outgoing IP header to create an IP_OPTIONS option the way
2857  * it was passed down from the application.
2858  */
2859 int
2860 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2861 {
2862 	ipoptp_t	opts;
2863 	const uchar_t	*opt;
2864 	uint8_t		optval;
2865 	uint8_t		optlen;
2866 	uint32_t	len = 0;
2867 	uchar_t	*buf1 = buf;
2868 
2869 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2870 	len += IP_ADDR_LEN;
2871 	bzero(buf1, IP_ADDR_LEN);
2872 
2873 	/*
2874 	 * OK to cast away const here, as we don't store through the returned
2875 	 * opts.ipoptp_cur pointer.
2876 	 */
2877 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2878 	    optval != IPOPT_EOL;
2879 	    optval = ipoptp_next(&opts)) {
2880 		int	off;
2881 
2882 		opt = opts.ipoptp_cur;
2883 		optlen = opts.ipoptp_len;
2884 		switch (optval) {
2885 		case IPOPT_SSRR:
2886 		case IPOPT_LSRR:
2887 
2888 			/*
2889 			 * Insert ipha_dst as the first entry in the source
2890 			 * route and move down the entries on step.
2891 			 * The last entry gets placed at buf1.
2892 			 */
2893 			buf[IPOPT_OPTVAL] = optval;
2894 			buf[IPOPT_OLEN] = optlen;
2895 			buf[IPOPT_OFFSET] = optlen;
2896 
2897 			off = optlen - IP_ADDR_LEN;
2898 			if (off < 0) {
2899 				/* No entries in source route */
2900 				break;
2901 			}
2902 			/* Last entry in source route */
2903 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2904 			off -= IP_ADDR_LEN;
2905 
2906 			while (off > 0) {
2907 				bcopy(opt + off,
2908 				    buf + off + IP_ADDR_LEN,
2909 				    IP_ADDR_LEN);
2910 				off -= IP_ADDR_LEN;
2911 			}
2912 			/* ipha_dst into first slot */
2913 			bcopy(&ipha->ipha_dst,
2914 			    buf + off + IP_ADDR_LEN,
2915 			    IP_ADDR_LEN);
2916 			buf += optlen;
2917 			len += optlen;
2918 			break;
2919 
2920 		case IPOPT_COMSEC:
2921 		case IPOPT_SECURITY:
2922 			/* if passing up a label is not ok, then remove */
2923 			if (is_system_labeled())
2924 				break;
2925 			/* FALLTHROUGH */
2926 		default:
2927 			bcopy(opt, buf, optlen);
2928 			buf += optlen;
2929 			len += optlen;
2930 			break;
2931 		}
2932 	}
2933 done:
2934 	/* Pad the resulting options */
2935 	while (len & 0x3) {
2936 		*buf++ = IPOPT_EOL;
2937 		len++;
2938 	}
2939 	return (len);
2940 }
2941 
2942 /*
2943  * Update any record route or timestamp options to include this host.
2944  * Reverse any source route option.
2945  * This routine assumes that the options are well formed i.e. that they
2946  * have already been checked.
2947  */
2948 static void
2949 icmp_options_update(ipha_t *ipha)
2950 {
2951 	ipoptp_t	opts;
2952 	uchar_t		*opt;
2953 	uint8_t		optval;
2954 	ipaddr_t	src;		/* Our local address */
2955 	ipaddr_t	dst;
2956 
2957 	ip2dbg(("icmp_options_update\n"));
2958 	src = ipha->ipha_src;
2959 	dst = ipha->ipha_dst;
2960 
2961 	for (optval = ipoptp_first(&opts, ipha);
2962 	    optval != IPOPT_EOL;
2963 	    optval = ipoptp_next(&opts)) {
2964 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2965 		opt = opts.ipoptp_cur;
2966 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2967 		    optval, opts.ipoptp_len));
2968 		switch (optval) {
2969 			int off1, off2;
2970 		case IPOPT_SSRR:
2971 		case IPOPT_LSRR:
2972 			/*
2973 			 * Reverse the source route.  The first entry
2974 			 * should be the next to last one in the current
2975 			 * source route (the last entry is our address).
2976 			 * The last entry should be the final destination.
2977 			 */
2978 			off1 = IPOPT_MINOFF_SR - 1;
2979 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2980 			if (off2 < 0) {
2981 				/* No entries in source route */
2982 				ip1dbg((
2983 				    "icmp_options_update: bad src route\n"));
2984 				break;
2985 			}
2986 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2987 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2988 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2989 			off2 -= IP_ADDR_LEN;
2990 
2991 			while (off1 < off2) {
2992 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2993 				bcopy((char *)opt + off2, (char *)opt + off1,
2994 				    IP_ADDR_LEN);
2995 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2996 				off1 += IP_ADDR_LEN;
2997 				off2 -= IP_ADDR_LEN;
2998 			}
2999 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3000 			break;
3001 		}
3002 	}
3003 }
3004 
3005 /*
3006  * Process received ICMP Redirect messages.
3007  */
3008 static void
3009 icmp_redirect(ill_t *ill, mblk_t *mp)
3010 {
3011 	ipha_t	*ipha;
3012 	int	iph_hdr_length;
3013 	icmph_t	*icmph;
3014 	ipha_t	*ipha_err;
3015 	ire_t	*ire;
3016 	ire_t	*prev_ire;
3017 	ire_t	*save_ire;
3018 	ipaddr_t  src, dst, gateway;
3019 	iulp_t	ulp_info = { 0 };
3020 	int	error;
3021 	ip_stack_t *ipst;
3022 
3023 	ASSERT(ill != NULL);
3024 	ipst = ill->ill_ipst;
3025 
3026 	ipha = (ipha_t *)mp->b_rptr;
3027 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3028 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3029 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3030 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3031 		freemsg(mp);
3032 		return;
3033 	}
3034 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3035 	ipha_err = (ipha_t *)&icmph[1];
3036 	src = ipha->ipha_src;
3037 	dst = ipha_err->ipha_dst;
3038 	gateway = icmph->icmph_rd_gateway;
3039 	/* Make sure the new gateway is reachable somehow. */
3040 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3041 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3042 	/*
3043 	 * Make sure we had a route for the dest in question and that
3044 	 * that route was pointing to the old gateway (the source of the
3045 	 * redirect packet.)
3046 	 */
3047 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3048 	    NULL, MATCH_IRE_GW, ipst);
3049 	/*
3050 	 * Check that
3051 	 *	the redirect was not from ourselves
3052 	 *	the new gateway and the old gateway are directly reachable
3053 	 */
3054 	if (!prev_ire ||
3055 	    !ire ||
3056 	    ire->ire_type == IRE_LOCAL) {
3057 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3058 		freemsg(mp);
3059 		if (ire != NULL)
3060 			ire_refrele(ire);
3061 		if (prev_ire != NULL)
3062 			ire_refrele(prev_ire);
3063 		return;
3064 	}
3065 
3066 	/*
3067 	 * Should we use the old ULP info to create the new gateway?  From
3068 	 * a user's perspective, we should inherit the info so that it
3069 	 * is a "smooth" transition.  If we do not do that, then new
3070 	 * connections going thru the new gateway will have no route metrics,
3071 	 * which is counter-intuitive to user.  From a network point of
3072 	 * view, this may or may not make sense even though the new gateway
3073 	 * is still directly connected to us so the route metrics should not
3074 	 * change much.
3075 	 *
3076 	 * But if the old ire_uinfo is not initialized, we do another
3077 	 * recursive lookup on the dest using the new gateway.  There may
3078 	 * be a route to that.  If so, use it to initialize the redirect
3079 	 * route.
3080 	 */
3081 	if (prev_ire->ire_uinfo.iulp_set) {
3082 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3083 	} else {
3084 		ire_t *tmp_ire;
3085 		ire_t *sire;
3086 
3087 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3088 		    ALL_ZONES, 0, NULL,
3089 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3090 		    ipst);
3091 		if (sire != NULL) {
3092 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3093 			/*
3094 			 * If sire != NULL, ire_ftable_lookup() should not
3095 			 * return a NULL value.
3096 			 */
3097 			ASSERT(tmp_ire != NULL);
3098 			ire_refrele(tmp_ire);
3099 			ire_refrele(sire);
3100 		} else if (tmp_ire != NULL) {
3101 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3102 			    sizeof (iulp_t));
3103 			ire_refrele(tmp_ire);
3104 		}
3105 	}
3106 	if (prev_ire->ire_type == IRE_CACHE)
3107 		ire_delete(prev_ire);
3108 	ire_refrele(prev_ire);
3109 	/*
3110 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3111 	 * require TOS routing
3112 	 */
3113 	switch (icmph->icmph_code) {
3114 	case 0:
3115 	case 1:
3116 		/* TODO: TOS specificity for cases 2 and 3 */
3117 	case 2:
3118 	case 3:
3119 		break;
3120 	default:
3121 		freemsg(mp);
3122 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3123 		ire_refrele(ire);
3124 		return;
3125 	}
3126 	/*
3127 	 * Create a Route Association.  This will allow us to remember that
3128 	 * someone we believe told us to use the particular gateway.
3129 	 */
3130 	save_ire = ire;
3131 	ire = ire_create(
3132 	    (uchar_t *)&dst,			/* dest addr */
3133 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3134 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3135 	    (uchar_t *)&gateway,		/* gateway addr */
3136 	    &save_ire->ire_max_frag,		/* max frag */
3137 	    NULL,				/* no src nce */
3138 	    NULL,				/* no rfq */
3139 	    NULL,				/* no stq */
3140 	    IRE_HOST,
3141 	    NULL,				/* ipif */
3142 	    0,					/* cmask */
3143 	    0,					/* phandle */
3144 	    0,					/* ihandle */
3145 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3146 	    &ulp_info,
3147 	    NULL,				/* tsol_gc_t */
3148 	    NULL,				/* gcgrp */
3149 	    ipst);
3150 
3151 	if (ire == NULL) {
3152 		freemsg(mp);
3153 		ire_refrele(save_ire);
3154 		return;
3155 	}
3156 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3157 	ire_refrele(save_ire);
3158 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3159 
3160 	if (error == 0) {
3161 		ire_refrele(ire);		/* Held in ire_add_v4 */
3162 		/* tell routing sockets that we received a redirect */
3163 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3164 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3165 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3166 	}
3167 
3168 	/*
3169 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3170 	 * This together with the added IRE has the effect of
3171 	 * modifying an existing redirect.
3172 	 */
3173 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3174 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3175 	if (prev_ire != NULL) {
3176 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3177 			ire_delete(prev_ire);
3178 		ire_refrele(prev_ire);
3179 	}
3180 
3181 	freemsg(mp);
3182 }
3183 
3184 /*
3185  * Generate an ICMP parameter problem message.
3186  */
3187 static void
3188 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3189 	ip_stack_t *ipst)
3190 {
3191 	icmph_t	icmph;
3192 	boolean_t mctl_present;
3193 	mblk_t *first_mp;
3194 
3195 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3196 
3197 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3198 		if (mctl_present)
3199 			freeb(first_mp);
3200 		return;
3201 	}
3202 
3203 	bzero(&icmph, sizeof (icmph_t));
3204 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3205 	icmph.icmph_pp_ptr = ptr;
3206 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3207 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3208 	    ipst);
3209 }
3210 
3211 /*
3212  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3213  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3214  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3215  * an icmp error packet can be sent.
3216  * Assigns an appropriate source address to the packet. If ipha_dst is
3217  * one of our addresses use it for source. Otherwise pick a source based
3218  * on a route lookup back to ipha_src.
3219  * Note that ipha_src must be set here since the
3220  * packet is likely to arrive on an ill queue in ip_wput() which will
3221  * not set a source address.
3222  */
3223 static void
3224 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3225     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3226 {
3227 	ipaddr_t dst;
3228 	icmph_t	*icmph;
3229 	ipha_t	*ipha;
3230 	uint_t	len_needed;
3231 	size_t	msg_len;
3232 	mblk_t	*mp1;
3233 	ipaddr_t src;
3234 	ire_t	*ire;
3235 	mblk_t *ipsec_mp;
3236 	ipsec_out_t	*io = NULL;
3237 
3238 	if (mctl_present) {
3239 		/*
3240 		 * If it is :
3241 		 *
3242 		 * 1) a IPSEC_OUT, then this is caused by outbound
3243 		 *    datagram originating on this host. IPsec processing
3244 		 *    may or may not have been done. Refer to comments above
3245 		 *    icmp_inbound_error_fanout for details.
3246 		 *
3247 		 * 2) a IPSEC_IN if we are generating a icmp_message
3248 		 *    for an incoming datagram destined for us i.e called
3249 		 *    from ip_fanout_send_icmp.
3250 		 */
3251 		ipsec_info_t *in;
3252 		ipsec_mp = mp;
3253 		mp = ipsec_mp->b_cont;
3254 
3255 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3256 		ipha = (ipha_t *)mp->b_rptr;
3257 
3258 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3259 		    in->ipsec_info_type == IPSEC_IN);
3260 
3261 		if (in->ipsec_info_type == IPSEC_IN) {
3262 			/*
3263 			 * Convert the IPSEC_IN to IPSEC_OUT.
3264 			 */
3265 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3266 				BUMP_MIB(&ipst->ips_ip_mib,
3267 				    ipIfStatsOutDiscards);
3268 				return;
3269 			}
3270 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3271 		} else {
3272 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3273 			io = (ipsec_out_t *)in;
3274 			/*
3275 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3276 			 * ire lookup.
3277 			 */
3278 			io->ipsec_out_proc_begin = B_FALSE;
3279 		}
3280 		ASSERT(zoneid != ALL_ZONES);
3281 		/*
3282 		 * The IPSEC_IN (now an IPSEC_OUT) didn't have its zoneid
3283 		 * initialized.  We need to do that now.
3284 		 */
3285 		io->ipsec_out_zoneid = zoneid;
3286 	} else {
3287 		/*
3288 		 * This is in clear. The icmp message we are building
3289 		 * here should go out in clear.
3290 		 *
3291 		 * Pardon the convolution of it all, but it's easier to
3292 		 * allocate a "use cleartext" IPSEC_IN message and convert
3293 		 * it than it is to allocate a new one.
3294 		 */
3295 		ipsec_in_t *ii;
3296 		ASSERT(DB_TYPE(mp) == M_DATA);
3297 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3298 		if (ipsec_mp == NULL) {
3299 			freemsg(mp);
3300 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3301 			return;
3302 		}
3303 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3304 
3305 		/* This is not a secure packet */
3306 		ii->ipsec_in_secure = B_FALSE;
3307 		/*
3308 		 * For trusted extensions using a shared IP address we can
3309 		 * send using any zoneid.
3310 		 */
3311 		if (zoneid == ALL_ZONES)
3312 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3313 		else
3314 			ii->ipsec_in_zoneid = zoneid;
3315 		ipsec_mp->b_cont = mp;
3316 		ipha = (ipha_t *)mp->b_rptr;
3317 		/*
3318 		 * Convert the IPSEC_IN to IPSEC_OUT.
3319 		 */
3320 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3321 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3322 			return;
3323 		}
3324 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3325 	}
3326 
3327 	/* Remember our eventual destination */
3328 	dst = ipha->ipha_src;
3329 
3330 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3331 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3332 	if (ire != NULL &&
3333 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3334 		src = ipha->ipha_dst;
3335 	} else {
3336 		if (ire != NULL)
3337 			ire_refrele(ire);
3338 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3339 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3340 		    ipst);
3341 		if (ire == NULL) {
3342 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3343 			freemsg(ipsec_mp);
3344 			return;
3345 		}
3346 		src = ire->ire_src_addr;
3347 	}
3348 
3349 	if (ire != NULL)
3350 		ire_refrele(ire);
3351 
3352 	/*
3353 	 * Check if we can send back more then 8 bytes in addition to
3354 	 * the IP header.  We try to send 64 bytes of data and the internal
3355 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3356 	 */
3357 	len_needed = IPH_HDR_LENGTH(ipha);
3358 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3359 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3360 
3361 		if (!pullupmsg(mp, -1)) {
3362 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3363 			freemsg(ipsec_mp);
3364 			return;
3365 		}
3366 		ipha = (ipha_t *)mp->b_rptr;
3367 
3368 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3369 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3370 			    len_needed));
3371 		} else {
3372 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3373 
3374 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3375 			len_needed += ip_hdr_length_v6(mp, ip6h);
3376 		}
3377 	}
3378 	len_needed += ipst->ips_ip_icmp_return;
3379 	msg_len = msgdsize(mp);
3380 	if (msg_len > len_needed) {
3381 		(void) adjmsg(mp, len_needed - msg_len);
3382 		msg_len = len_needed;
3383 	}
3384 	/* Make sure we propagate the cred/label for TX */
3385 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3386 	if (mp1 == NULL) {
3387 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3388 		freemsg(ipsec_mp);
3389 		return;
3390 	}
3391 	mp1->b_cont = mp;
3392 	mp = mp1;
3393 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3394 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3395 	    io->ipsec_out_type == IPSEC_OUT);
3396 	ipsec_mp->b_cont = mp;
3397 
3398 	/*
3399 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3400 	 * node generates be accepted in peace by all on-host destinations.
3401 	 * If we do NOT assume that all on-host destinations trust
3402 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3403 	 * (Look for ipsec_out_icmp_loopback).
3404 	 */
3405 	io->ipsec_out_icmp_loopback = B_TRUE;
3406 
3407 	ipha = (ipha_t *)mp->b_rptr;
3408 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3409 	*ipha = icmp_ipha;
3410 	ipha->ipha_src = src;
3411 	ipha->ipha_dst = dst;
3412 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3413 	msg_len += sizeof (icmp_ipha) + len;
3414 	if (msg_len > IP_MAXPACKET) {
3415 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3416 		msg_len = IP_MAXPACKET;
3417 	}
3418 	ipha->ipha_length = htons((uint16_t)msg_len);
3419 	icmph = (icmph_t *)&ipha[1];
3420 	bcopy(stuff, icmph, len);
3421 	icmph->icmph_checksum = 0;
3422 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3423 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3424 	put(q, ipsec_mp);
3425 }
3426 
3427 /*
3428  * Determine if an ICMP error packet can be sent given the rate limit.
3429  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3430  * in milliseconds) and a burst size. Burst size number of packets can
3431  * be sent arbitrarely closely spaced.
3432  * The state is tracked using two variables to implement an approximate
3433  * token bucket filter:
3434  *	icmp_pkt_err_last - lbolt value when the last burst started
3435  *	icmp_pkt_err_sent - number of packets sent in current burst
3436  */
3437 boolean_t
3438 icmp_err_rate_limit(ip_stack_t *ipst)
3439 {
3440 	clock_t now = TICK_TO_MSEC(lbolt);
3441 	uint_t refilled; /* Number of packets refilled in tbf since last */
3442 	/* Guard against changes by loading into local variable */
3443 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3444 
3445 	if (err_interval == 0)
3446 		return (B_FALSE);
3447 
3448 	if (ipst->ips_icmp_pkt_err_last > now) {
3449 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3450 		ipst->ips_icmp_pkt_err_last = 0;
3451 		ipst->ips_icmp_pkt_err_sent = 0;
3452 	}
3453 	/*
3454 	 * If we are in a burst update the token bucket filter.
3455 	 * Update the "last" time to be close to "now" but make sure
3456 	 * we don't loose precision.
3457 	 */
3458 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3459 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3460 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3461 			ipst->ips_icmp_pkt_err_sent = 0;
3462 		} else {
3463 			ipst->ips_icmp_pkt_err_sent -= refilled;
3464 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3465 		}
3466 	}
3467 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3468 		/* Start of new burst */
3469 		ipst->ips_icmp_pkt_err_last = now;
3470 	}
3471 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3472 		ipst->ips_icmp_pkt_err_sent++;
3473 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3474 		    ipst->ips_icmp_pkt_err_sent));
3475 		return (B_FALSE);
3476 	}
3477 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3478 	return (B_TRUE);
3479 }
3480 
3481 /*
3482  * Check if it is ok to send an IPv4 ICMP error packet in
3483  * response to the IPv4 packet in mp.
3484  * Free the message and return null if no
3485  * ICMP error packet should be sent.
3486  */
3487 static mblk_t *
3488 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3489 {
3490 	icmph_t	*icmph;
3491 	ipha_t	*ipha;
3492 	uint_t	len_needed;
3493 	ire_t	*src_ire;
3494 	ire_t	*dst_ire;
3495 
3496 	if (!mp)
3497 		return (NULL);
3498 	ipha = (ipha_t *)mp->b_rptr;
3499 	if (ip_csum_hdr(ipha)) {
3500 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3501 		freemsg(mp);
3502 		return (NULL);
3503 	}
3504 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3505 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3506 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3507 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3508 	if (src_ire != NULL || dst_ire != NULL ||
3509 	    CLASSD(ipha->ipha_dst) ||
3510 	    CLASSD(ipha->ipha_src) ||
3511 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3512 		/* Note: only errors to the fragment with offset 0 */
3513 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3514 		freemsg(mp);
3515 		if (src_ire != NULL)
3516 			ire_refrele(src_ire);
3517 		if (dst_ire != NULL)
3518 			ire_refrele(dst_ire);
3519 		return (NULL);
3520 	}
3521 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3522 		/*
3523 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3524 		 * errors in response to any ICMP errors.
3525 		 */
3526 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3527 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3528 			if (!pullupmsg(mp, len_needed)) {
3529 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3530 				freemsg(mp);
3531 				return (NULL);
3532 			}
3533 			ipha = (ipha_t *)mp->b_rptr;
3534 		}
3535 		icmph = (icmph_t *)
3536 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3537 		switch (icmph->icmph_type) {
3538 		case ICMP_DEST_UNREACHABLE:
3539 		case ICMP_SOURCE_QUENCH:
3540 		case ICMP_TIME_EXCEEDED:
3541 		case ICMP_PARAM_PROBLEM:
3542 		case ICMP_REDIRECT:
3543 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3544 			freemsg(mp);
3545 			return (NULL);
3546 		default:
3547 			break;
3548 		}
3549 	}
3550 	/*
3551 	 * If this is a labeled system, then check to see if we're allowed to
3552 	 * send a response to this particular sender.  If not, then just drop.
3553 	 */
3554 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3555 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3556 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3557 		freemsg(mp);
3558 		return (NULL);
3559 	}
3560 	if (icmp_err_rate_limit(ipst)) {
3561 		/*
3562 		 * Only send ICMP error packets every so often.
3563 		 * This should be done on a per port/source basis,
3564 		 * but for now this will suffice.
3565 		 */
3566 		freemsg(mp);
3567 		return (NULL);
3568 	}
3569 	return (mp);
3570 }
3571 
3572 /*
3573  * Generate an ICMP redirect message.
3574  */
3575 static void
3576 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3577 {
3578 	icmph_t	icmph;
3579 
3580 	/*
3581 	 * We are called from ip_rput where we could
3582 	 * not have attached an IPSEC_IN.
3583 	 */
3584 	ASSERT(mp->b_datap->db_type == M_DATA);
3585 
3586 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3587 		return;
3588 	}
3589 
3590 	bzero(&icmph, sizeof (icmph_t));
3591 	icmph.icmph_type = ICMP_REDIRECT;
3592 	icmph.icmph_code = 1;
3593 	icmph.icmph_rd_gateway = gateway;
3594 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3595 	/* Redirects sent by router, and router is global zone */
3596 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3597 }
3598 
3599 /*
3600  * Generate an ICMP time exceeded message.
3601  */
3602 void
3603 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3604     ip_stack_t *ipst)
3605 {
3606 	icmph_t	icmph;
3607 	boolean_t mctl_present;
3608 	mblk_t *first_mp;
3609 
3610 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3611 
3612 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3613 		if (mctl_present)
3614 			freeb(first_mp);
3615 		return;
3616 	}
3617 
3618 	bzero(&icmph, sizeof (icmph_t));
3619 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3620 	icmph.icmph_code = code;
3621 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3622 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3623 	    ipst);
3624 }
3625 
3626 /*
3627  * Generate an ICMP unreachable message.
3628  */
3629 void
3630 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3631     ip_stack_t *ipst)
3632 {
3633 	icmph_t	icmph;
3634 	mblk_t *first_mp;
3635 	boolean_t mctl_present;
3636 
3637 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3638 
3639 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3640 		if (mctl_present)
3641 			freeb(first_mp);
3642 		return;
3643 	}
3644 
3645 	bzero(&icmph, sizeof (icmph_t));
3646 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3647 	icmph.icmph_code = code;
3648 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3649 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3650 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3651 	    zoneid, ipst);
3652 }
3653 
3654 /*
3655  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3656  * duplicate.  As long as someone else holds the address, the interface will
3657  * stay down.  When that conflict goes away, the interface is brought back up.
3658  * This is done so that accidental shutdowns of addresses aren't made
3659  * permanent.  Your server will recover from a failure.
3660  *
3661  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3662  * user space process (dhcpagent).
3663  *
3664  * Recovery completes if ARP reports that the address is now ours (via
3665  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3666  *
3667  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3668  */
3669 static void
3670 ipif_dup_recovery(void *arg)
3671 {
3672 	ipif_t *ipif = arg;
3673 	ill_t *ill = ipif->ipif_ill;
3674 	mblk_t *arp_add_mp;
3675 	mblk_t *arp_del_mp;
3676 	ip_stack_t *ipst = ill->ill_ipst;
3677 
3678 	ipif->ipif_recovery_id = 0;
3679 
3680 	/*
3681 	 * No lock needed for moving or condemned check, as this is just an
3682 	 * optimization.
3683 	 */
3684 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3685 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3686 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3687 		/* No reason to try to bring this address back. */
3688 		return;
3689 	}
3690 
3691 	/* ACE_F_UNVERIFIED restarts DAD */
3692 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3693 		goto alloc_fail;
3694 
3695 	if (ipif->ipif_arp_del_mp == NULL) {
3696 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3697 			goto alloc_fail;
3698 		ipif->ipif_arp_del_mp = arp_del_mp;
3699 	}
3700 
3701 	putnext(ill->ill_rq, arp_add_mp);
3702 	return;
3703 
3704 alloc_fail:
3705 	/*
3706 	 * On allocation failure, just restart the timer.  Note that the ipif
3707 	 * is down here, so no other thread could be trying to start a recovery
3708 	 * timer.  The ill_lock protects the condemned flag and the recovery
3709 	 * timer ID.
3710 	 */
3711 	freemsg(arp_add_mp);
3712 	mutex_enter(&ill->ill_lock);
3713 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3714 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3715 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3716 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3717 	}
3718 	mutex_exit(&ill->ill_lock);
3719 }
3720 
3721 /*
3722  * This is for exclusive changes due to ARP.  Either tear down an interface due
3723  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3724  */
3725 /* ARGSUSED */
3726 static void
3727 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3728 {
3729 	ill_t	*ill = rq->q_ptr;
3730 	arh_t *arh;
3731 	ipaddr_t src;
3732 	ipif_t	*ipif;
3733 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3734 	char hbuf[MAC_STR_LEN];
3735 	char sbuf[INET_ADDRSTRLEN];
3736 	const char *failtype;
3737 	boolean_t bring_up;
3738 	ip_stack_t *ipst = ill->ill_ipst;
3739 
3740 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3741 	case AR_CN_READY:
3742 		failtype = NULL;
3743 		bring_up = B_TRUE;
3744 		break;
3745 	case AR_CN_FAILED:
3746 		failtype = "in use";
3747 		bring_up = B_FALSE;
3748 		break;
3749 	default:
3750 		failtype = "claimed";
3751 		bring_up = B_FALSE;
3752 		break;
3753 	}
3754 
3755 	arh = (arh_t *)mp->b_cont->b_rptr;
3756 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3757 
3758 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3759 	    sizeof (hbuf));
3760 	(void) ip_dot_addr(src, sbuf);
3761 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3762 
3763 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3764 		    ipif->ipif_lcl_addr != src) {
3765 			continue;
3766 		}
3767 
3768 		/*
3769 		 * If we failed on a recovery probe, then restart the timer to
3770 		 * try again later.
3771 		 */
3772 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3773 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3774 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3775 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3776 		    ipst->ips_ip_dup_recovery > 0 &&
3777 		    ipif->ipif_recovery_id == 0) {
3778 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3779 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3780 			continue;
3781 		}
3782 
3783 		/*
3784 		 * If what we're trying to do has already been done, then do
3785 		 * nothing.
3786 		 */
3787 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3788 			continue;
3789 
3790 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3791 
3792 		if (failtype == NULL) {
3793 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3794 			    ibuf);
3795 		} else {
3796 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3797 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3798 		}
3799 
3800 		if (bring_up) {
3801 			ASSERT(ill->ill_dl_up);
3802 			/*
3803 			 * Free up the ARP delete message so we can allocate
3804 			 * a fresh one through the normal path.
3805 			 */
3806 			freemsg(ipif->ipif_arp_del_mp);
3807 			ipif->ipif_arp_del_mp = NULL;
3808 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3809 			    EINPROGRESS) {
3810 				ipif->ipif_addr_ready = 1;
3811 				(void) ipif_up_done(ipif);
3812 				ASSERT(ill->ill_move_ipif == NULL);
3813 			}
3814 			continue;
3815 		}
3816 
3817 		mutex_enter(&ill->ill_lock);
3818 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3819 		ipif->ipif_flags |= IPIF_DUPLICATE;
3820 		ill->ill_ipif_dup_count++;
3821 		mutex_exit(&ill->ill_lock);
3822 		/*
3823 		 * Already exclusive on the ill; no need to handle deferred
3824 		 * processing here.
3825 		 */
3826 		(void) ipif_down(ipif, NULL, NULL);
3827 		ipif_down_tail(ipif);
3828 		mutex_enter(&ill->ill_lock);
3829 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3830 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3831 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3832 		    ipst->ips_ip_dup_recovery > 0) {
3833 			ASSERT(ipif->ipif_recovery_id == 0);
3834 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3835 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3836 		}
3837 		mutex_exit(&ill->ill_lock);
3838 	}
3839 	freemsg(mp);
3840 }
3841 
3842 /* ARGSUSED */
3843 static void
3844 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3845 {
3846 	ill_t	*ill = rq->q_ptr;
3847 	arh_t *arh;
3848 	ipaddr_t src;
3849 	ipif_t	*ipif;
3850 
3851 	arh = (arh_t *)mp->b_cont->b_rptr;
3852 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3853 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3854 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3855 			(void) ipif_resolver_up(ipif, Res_act_defend);
3856 	}
3857 	freemsg(mp);
3858 }
3859 
3860 /*
3861  * News from ARP.  ARP sends notification of interesting events down
3862  * to its clients using M_CTL messages with the interesting ARP packet
3863  * attached via b_cont.
3864  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3865  * queue as opposed to ARP sending the message to all the clients, i.e. all
3866  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3867  * table if a cache IRE is found to delete all the entries for the address in
3868  * the packet.
3869  */
3870 static void
3871 ip_arp_news(queue_t *q, mblk_t *mp)
3872 {
3873 	arcn_t		*arcn;
3874 	arh_t		*arh;
3875 	ire_t		*ire = NULL;
3876 	char		hbuf[MAC_STR_LEN];
3877 	char		sbuf[INET_ADDRSTRLEN];
3878 	ipaddr_t	src;
3879 	in6_addr_t	v6src;
3880 	boolean_t	isv6 = B_FALSE;
3881 	ipif_t		*ipif;
3882 	ill_t		*ill;
3883 	ip_stack_t	*ipst;
3884 
3885 	if (CONN_Q(q)) {
3886 		conn_t *connp = Q_TO_CONN(q);
3887 
3888 		ipst = connp->conn_netstack->netstack_ip;
3889 	} else {
3890 		ill_t *ill = (ill_t *)q->q_ptr;
3891 
3892 		ipst = ill->ill_ipst;
3893 	}
3894 
3895 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3896 		if (q->q_next) {
3897 			putnext(q, mp);
3898 		} else
3899 			freemsg(mp);
3900 		return;
3901 	}
3902 	arh = (arh_t *)mp->b_cont->b_rptr;
3903 	/* Is it one we are interested in? */
3904 	if (BE16_TO_U16(arh->arh_proto) == ETHERTYPE_IPV6) {
3905 		isv6 = B_TRUE;
3906 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3907 		    IPV6_ADDR_LEN);
3908 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3909 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3910 		    IP_ADDR_LEN);
3911 	} else {
3912 		freemsg(mp);
3913 		return;
3914 	}
3915 
3916 	ill = q->q_ptr;
3917 
3918 	arcn = (arcn_t *)mp->b_rptr;
3919 	switch (arcn->arcn_code) {
3920 	case AR_CN_BOGON:
3921 		/*
3922 		 * Someone is sending ARP packets with a source protocol
3923 		 * address that we have published and for which we believe our
3924 		 * entry is authoritative and (when ill_arp_extend is set)
3925 		 * verified to be unique on the network.
3926 		 *
3927 		 * The ARP module internally handles the cases where the sender
3928 		 * is just probing (for DAD) and where the hardware address of
3929 		 * a non-authoritative entry has changed.  Thus, these are the
3930 		 * real conflicts, and we have to do resolution.
3931 		 *
3932 		 * We back away quickly from the address if it's from DHCP or
3933 		 * otherwise temporary and hasn't been used recently (or at
3934 		 * all).  We'd like to include "deprecated" addresses here as
3935 		 * well (as there's no real reason to defend something we're
3936 		 * discarding), but IPMP "reuses" this flag to mean something
3937 		 * other than the standard meaning.
3938 		 *
3939 		 * If the ARP module above is not extended (meaning that it
3940 		 * doesn't know how to defend the address), then we just log
3941 		 * the problem as we always did and continue on.  It's not
3942 		 * right, but there's little else we can do, and those old ATM
3943 		 * users are going away anyway.
3944 		 */
3945 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3946 		    hbuf, sizeof (hbuf));
3947 		(void) ip_dot_addr(src, sbuf);
3948 		if (isv6) {
3949 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3950 			    ipst);
3951 		} else {
3952 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3953 		}
3954 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3955 			uint32_t now;
3956 			uint32_t maxage;
3957 			clock_t lused;
3958 			uint_t maxdefense;
3959 			uint_t defs;
3960 
3961 			/*
3962 			 * First, figure out if this address hasn't been used
3963 			 * in a while.  If it hasn't, then it's a better
3964 			 * candidate for abandoning.
3965 			 */
3966 			ipif = ire->ire_ipif;
3967 			ASSERT(ipif != NULL);
3968 			now = gethrestime_sec();
3969 			maxage = now - ire->ire_create_time;
3970 			if (maxage > ipst->ips_ip_max_temp_idle)
3971 				maxage = ipst->ips_ip_max_temp_idle;
3972 			lused = drv_hztousec(ddi_get_lbolt() -
3973 			    ire->ire_last_used_time) / MICROSEC + 1;
3974 			if (lused >= maxage && (ipif->ipif_flags &
3975 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3976 				maxdefense = ipst->ips_ip_max_temp_defend;
3977 			else
3978 				maxdefense = ipst->ips_ip_max_defend;
3979 
3980 			/*
3981 			 * Now figure out how many times we've defended
3982 			 * ourselves.  Ignore defenses that happened long in
3983 			 * the past.
3984 			 */
3985 			mutex_enter(&ire->ire_lock);
3986 			if ((defs = ire->ire_defense_count) > 0 &&
3987 			    now - ire->ire_defense_time >
3988 			    ipst->ips_ip_defend_interval) {
3989 				ire->ire_defense_count = defs = 0;
3990 			}
3991 			ire->ire_defense_count++;
3992 			ire->ire_defense_time = now;
3993 			mutex_exit(&ire->ire_lock);
3994 			ill_refhold(ill);
3995 			ire_refrele(ire);
3996 
3997 			/*
3998 			 * If we've defended ourselves too many times already,
3999 			 * then give up and tear down the interface(s) using
4000 			 * this address.  Otherwise, defend by sending out a
4001 			 * gratuitous ARP.
4002 			 */
4003 			if (defs >= maxdefense && ill->ill_arp_extend) {
4004 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4005 				    B_FALSE);
4006 			} else {
4007 				cmn_err(CE_WARN,
4008 				    "node %s is using our IP address %s on %s",
4009 				    hbuf, sbuf, ill->ill_name);
4010 				/*
4011 				 * If this is an old (ATM) ARP module, then
4012 				 * don't try to defend the address.  Remain
4013 				 * compatible with the old behavior.  Defend
4014 				 * only with new ARP.
4015 				 */
4016 				if (ill->ill_arp_extend) {
4017 					qwriter_ip(ill, q, mp, ip_arp_defend,
4018 					    NEW_OP, B_FALSE);
4019 				} else {
4020 					ill_refrele(ill);
4021 				}
4022 			}
4023 			return;
4024 		}
4025 		cmn_err(CE_WARN,
4026 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4027 		    hbuf, sbuf, ill->ill_name);
4028 		if (ire != NULL)
4029 			ire_refrele(ire);
4030 		break;
4031 	case AR_CN_ANNOUNCE:
4032 		if (isv6) {
4033 			/*
4034 			 * For XRESOLV interfaces.
4035 			 * Delete the IRE cache entry and NCE for this
4036 			 * v6 address
4037 			 */
4038 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4039 			/*
4040 			 * If v6src is a non-zero, it's a router address
4041 			 * as below. Do the same sort of thing to clean
4042 			 * out off-net IRE_CACHE entries that go through
4043 			 * the router.
4044 			 */
4045 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4046 				ire_walk_v6(ire_delete_cache_gw_v6,
4047 				    (char *)&v6src, ALL_ZONES, ipst);
4048 			}
4049 		} else {
4050 			nce_hw_map_t hwm;
4051 
4052 			/*
4053 			 * ARP gives us a copy of any packet where it thinks
4054 			 * the address has changed, so that we can update our
4055 			 * caches.  We're responsible for caching known answers
4056 			 * in the current design.  We check whether the
4057 			 * hardware address really has changed in all of our
4058 			 * entries that have cached this mapping, and if so, we
4059 			 * blow them away.  This way we will immediately pick
4060 			 * up the rare case of a host changing hardware
4061 			 * address.
4062 			 */
4063 			if (src == 0)
4064 				break;
4065 			hwm.hwm_addr = src;
4066 			hwm.hwm_hwlen = arh->arh_hlen;
4067 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4068 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4069 			ndp_walk_common(ipst->ips_ndp4, NULL,
4070 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4071 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4072 		}
4073 		break;
4074 	case AR_CN_READY:
4075 		/* No external v6 resolver has a contract to use this */
4076 		if (isv6)
4077 			break;
4078 		/* If the link is down, we'll retry this later */
4079 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4080 			break;
4081 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4082 		    NULL, NULL, ipst);
4083 		if (ipif != NULL) {
4084 			/*
4085 			 * If this is a duplicate recovery, then we now need to
4086 			 * go exclusive to bring this thing back up.
4087 			 */
4088 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4089 			    IPIF_DUPLICATE) {
4090 				ipif_refrele(ipif);
4091 				ill_refhold(ill);
4092 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4093 				    B_FALSE);
4094 				return;
4095 			}
4096 			/*
4097 			 * If this is the first notice that this address is
4098 			 * ready, then let the user know now.
4099 			 */
4100 			if ((ipif->ipif_flags & IPIF_UP) &&
4101 			    !ipif->ipif_addr_ready) {
4102 				ipif_mask_reply(ipif);
4103 				ipif_up_notify(ipif);
4104 			}
4105 			ipif->ipif_addr_ready = 1;
4106 			ipif_refrele(ipif);
4107 		}
4108 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4109 		if (ire != NULL) {
4110 			ire->ire_defense_count = 0;
4111 			ire_refrele(ire);
4112 		}
4113 		break;
4114 	case AR_CN_FAILED:
4115 		/* No external v6 resolver has a contract to use this */
4116 		if (isv6)
4117 			break;
4118 		if (!ill->ill_arp_extend) {
4119 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4120 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4121 			(void) ip_dot_addr(src, sbuf);
4122 
4123 			cmn_err(CE_WARN,
4124 			    "node %s is using our IP address %s on %s",
4125 			    hbuf, sbuf, ill->ill_name);
4126 			break;
4127 		}
4128 		ill_refhold(ill);
4129 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4130 		return;
4131 	}
4132 	freemsg(mp);
4133 }
4134 
4135 /*
4136  * Create a mblk suitable for carrying the interface index and/or source link
4137  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4138  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4139  * application.
4140  */
4141 mblk_t *
4142 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4143     ip_stack_t *ipst)
4144 {
4145 	mblk_t		*mp;
4146 	ip_pktinfo_t	*pinfo;
4147 	ipha_t 		*ipha;
4148 	struct ether_header *pether;
4149 	boolean_t	ipmp_ill_held = B_FALSE;
4150 
4151 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4152 	if (mp == NULL) {
4153 		ip1dbg(("ip_add_info: allocation failure.\n"));
4154 		return (data_mp);
4155 	}
4156 
4157 	ipha = (ipha_t *)data_mp->b_rptr;
4158 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4159 	bzero(pinfo, sizeof (ip_pktinfo_t));
4160 	pinfo->ip_pkt_flags = (uchar_t)flags;
4161 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4162 
4163 	pether = (struct ether_header *)((char *)ipha
4164 	    - sizeof (struct ether_header));
4165 
4166 	/*
4167 	 * Make sure the interface is an ethernet type, since this option
4168 	 * is currently supported only on this type of interface. Also make
4169 	 * sure we are pointing correctly above db_base.
4170 	 */
4171 	if ((flags & IPF_RECVSLLA) &&
4172 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4173 	    (ill->ill_type == IFT_ETHER) &&
4174 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4175 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4176 		bcopy(pether->ether_shost.ether_addr_octet,
4177 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4178 	} else {
4179 		/*
4180 		 * Clear the bit. Indicate to upper layer that IP is not
4181 		 * sending this ancillary info.
4182 		 */
4183 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4184 	}
4185 
4186 	/*
4187 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4188 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4189 	 * IPF_RECVADDR support on test addresses is not needed.)
4190 	 *
4191 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4192 	 * processing a packet looped back to an IPMP data address
4193 	 * (since those IRE_LOCALs are tied to IPMP ills).
4194 	 */
4195 	if (IS_UNDER_IPMP(ill)) {
4196 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4197 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4198 			freemsg(mp);
4199 			return (data_mp);
4200 		}
4201 		ipmp_ill_held = B_TRUE;
4202 	}
4203 
4204 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4205 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4206 	if (flags & IPF_RECVADDR) {
4207 		ipif_t	*ipif;
4208 		ire_t	*ire;
4209 
4210 		/*
4211 		 * Only valid for V4
4212 		 */
4213 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4214 		    (IPV4_VERSION << 4));
4215 
4216 		ipif = ipif_get_next_ipif(NULL, ill);
4217 		if (ipif != NULL) {
4218 			/*
4219 			 * Since a decision has already been made to deliver the
4220 			 * packet, there is no need to test for SECATTR and
4221 			 * ZONEONLY.
4222 			 * When a multicast packet is transmitted
4223 			 * a cache entry is created for the multicast address.
4224 			 * When delivering a copy of the packet or when new
4225 			 * packets are received we do not want to match on the
4226 			 * cached entry so explicitly match on
4227 			 * IRE_LOCAL and IRE_LOOPBACK
4228 			 */
4229 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4230 			    IRE_LOCAL | IRE_LOOPBACK,
4231 			    ipif, zoneid, NULL,
4232 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4233 			if (ire == NULL) {
4234 				/*
4235 				 * packet must have come on a different
4236 				 * interface.
4237 				 * Since a decision has already been made to
4238 				 * deliver the packet, there is no need to test
4239 				 * for SECATTR and ZONEONLY.
4240 				 * Only match on local and broadcast ire's.
4241 				 * See detailed comment above.
4242 				 */
4243 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4244 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4245 				    NULL, MATCH_IRE_TYPE, ipst);
4246 			}
4247 
4248 			if (ire == NULL) {
4249 				/*
4250 				 * This is either a multicast packet or
4251 				 * the address has been removed since
4252 				 * the packet was received.
4253 				 * Return INADDR_ANY so that normal source
4254 				 * selection occurs for the response.
4255 				 */
4256 
4257 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4258 			} else {
4259 				pinfo->ip_pkt_match_addr.s_addr =
4260 				    ire->ire_src_addr;
4261 				ire_refrele(ire);
4262 			}
4263 			ipif_refrele(ipif);
4264 		} else {
4265 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4266 		}
4267 	}
4268 
4269 	if (ipmp_ill_held)
4270 		ill_refrele(ill);
4271 
4272 	mp->b_datap->db_type = M_CTL;
4273 	mp->b_wptr += sizeof (ip_pktinfo_t);
4274 	mp->b_cont = data_mp;
4275 
4276 	return (mp);
4277 }
4278 
4279 /*
4280  * Used to determine the most accurate cred_t to use for TX.
4281  * First priority is SCM_UCRED having set the label in the message,
4282  * which is used for MLP on UDP. Second priority is the open credentials
4283  * with the peer's label (aka conn_effective_cred), which is needed for
4284  * MLP on TCP/SCTP and for MAC-Exempt. Last priority is the open credentials.
4285  */
4286 cred_t *
4287 ip_best_cred(mblk_t *mp, conn_t *connp, pid_t *pidp)
4288 {
4289 	cred_t *cr;
4290 
4291 	cr = msg_getcred(mp, pidp);
4292 	if (cr != NULL && crgetlabel(cr) != NULL)
4293 		return (cr);
4294 	*pidp = NOPID;
4295 	return (CONN_CRED(connp));
4296 }
4297 
4298 /*
4299  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4300  * part of the bind request.
4301  */
4302 
4303 boolean_t
4304 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4305 {
4306 	ipsec_in_t *ii;
4307 
4308 	ASSERT(policy_mp != NULL);
4309 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4310 
4311 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4312 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4313 
4314 	connp->conn_policy = ii->ipsec_in_policy;
4315 	ii->ipsec_in_policy = NULL;
4316 
4317 	if (ii->ipsec_in_action != NULL) {
4318 		if (connp->conn_latch == NULL) {
4319 			connp->conn_latch = iplatch_create();
4320 			if (connp->conn_latch == NULL)
4321 				return (B_FALSE);
4322 		}
4323 		ipsec_latch_inbound(connp->conn_latch, ii);
4324 	}
4325 	return (B_TRUE);
4326 }
4327 
4328 /*
4329  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4330  * and to arrange for power-fanout assist.  The ULP is identified by
4331  * adding a single byte at the end of the original bind message.
4332  * A ULP other than UDP or TCP that wishes to be recognized passes
4333  * down a bind with a zero length address.
4334  *
4335  * The binding works as follows:
4336  * - A zero byte address means just bind to the protocol.
4337  * - A four byte address is treated as a request to validate
4338  *   that the address is a valid local address, appropriate for
4339  *   an application to bind to. This does not affect any fanout
4340  *   information in IP.
4341  * - A sizeof sin_t byte address is used to bind to only the local address
4342  *   and port.
4343  * - A sizeof ipa_conn_t byte address contains complete fanout information
4344  *   consisting of local and remote addresses and ports.  In
4345  *   this case, the addresses are both validated as appropriate
4346  *   for this operation, and, if so, the information is retained
4347  *   for use in the inbound fanout.
4348  *
4349  * The ULP (except in the zero-length bind) can append an
4350  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4351  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4352  * a copy of the source or destination IRE (source for local bind;
4353  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4354  * policy information contained should be copied on to the conn.
4355  *
4356  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4357  */
4358 mblk_t *
4359 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4360 {
4361 	ssize_t		len;
4362 	struct T_bind_req	*tbr;
4363 	sin_t		*sin;
4364 	ipa_conn_t	*ac;
4365 	uchar_t		*ucp;
4366 	int		error = 0;
4367 	int		protocol;
4368 	ipa_conn_x_t	*acx;
4369 	cred_t		*cr;
4370 
4371 	/*
4372 	 * All Solaris components should pass a db_credp
4373 	 * for this TPI message, hence we ASSERT.
4374 	 * But in case there is some other M_PROTO that looks
4375 	 * like a TPI message sent by some other kernel
4376 	 * component, we check and return an error.
4377 	 */
4378 	cr = msg_getcred(mp, NULL);
4379 	ASSERT(cr != NULL);
4380 	if (cr == NULL) {
4381 		error = EINVAL;
4382 		goto bad_addr;
4383 	}
4384 
4385 	ASSERT(!connp->conn_af_isv6);
4386 	connp->conn_pkt_isv6 = B_FALSE;
4387 
4388 	len = MBLKL(mp);
4389 	if (len < (sizeof (*tbr) + 1)) {
4390 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4391 		    "ip_bind: bogus msg, len %ld", len);
4392 		/* XXX: Need to return something better */
4393 		goto bad_addr;
4394 	}
4395 	/* Back up and extract the protocol identifier. */
4396 	mp->b_wptr--;
4397 	protocol = *mp->b_wptr & 0xFF;
4398 	tbr = (struct T_bind_req *)mp->b_rptr;
4399 	/* Reset the message type in preparation for shipping it back. */
4400 	DB_TYPE(mp) = M_PCPROTO;
4401 
4402 	connp->conn_ulp = (uint8_t)protocol;
4403 
4404 	/*
4405 	 * Check for a zero length address.  This is from a protocol that
4406 	 * wants to register to receive all packets of its type.
4407 	 */
4408 	if (tbr->ADDR_length == 0) {
4409 		/*
4410 		 * These protocols are now intercepted in ip_bind_v6().
4411 		 * Reject protocol-level binds here for now.
4412 		 *
4413 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4414 		 * so that the protocol type cannot be SCTP.
4415 		 */
4416 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4417 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4418 			goto bad_addr;
4419 		}
4420 
4421 		/*
4422 		 *
4423 		 * The udp module never sends down a zero-length address,
4424 		 * and allowing this on a labeled system will break MLP
4425 		 * functionality.
4426 		 */
4427 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4428 			goto bad_addr;
4429 
4430 		if (connp->conn_mac_exempt)
4431 			goto bad_addr;
4432 
4433 		/* No hash here really.  The table is big enough. */
4434 		connp->conn_srcv6 = ipv6_all_zeros;
4435 
4436 		ipcl_proto_insert(connp, protocol);
4437 
4438 		tbr->PRIM_type = T_BIND_ACK;
4439 		return (mp);
4440 	}
4441 
4442 	/* Extract the address pointer from the message. */
4443 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4444 	    tbr->ADDR_length);
4445 	if (ucp == NULL) {
4446 		ip1dbg(("ip_bind: no address\n"));
4447 		goto bad_addr;
4448 	}
4449 	if (!OK_32PTR(ucp)) {
4450 		ip1dbg(("ip_bind: unaligned address\n"));
4451 		goto bad_addr;
4452 	}
4453 
4454 	switch (tbr->ADDR_length) {
4455 	default:
4456 		ip1dbg(("ip_bind: bad address length %d\n",
4457 		    (int)tbr->ADDR_length));
4458 		goto bad_addr;
4459 
4460 	case IP_ADDR_LEN:
4461 		/* Verification of local address only */
4462 		error = ip_bind_laddr_v4(connp, &mp->b_cont, protocol,
4463 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4464 		break;
4465 
4466 	case sizeof (sin_t):
4467 		sin = (sin_t *)ucp;
4468 		error = ip_bind_laddr_v4(connp, &mp->b_cont, protocol,
4469 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4470 		break;
4471 
4472 	case sizeof (ipa_conn_t):
4473 		ac = (ipa_conn_t *)ucp;
4474 		/* For raw socket, the local port is not set. */
4475 		if (ac->ac_lport == 0)
4476 			ac->ac_lport = connp->conn_lport;
4477 		/* Always verify destination reachability. */
4478 		error = ip_bind_connected_v4(connp, &mp->b_cont, protocol,
4479 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4480 		    B_TRUE, B_TRUE, cr);
4481 		break;
4482 
4483 	case sizeof (ipa_conn_x_t):
4484 		acx = (ipa_conn_x_t *)ucp;
4485 		/*
4486 		 * Whether or not to verify destination reachability depends
4487 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4488 		 */
4489 		error = ip_bind_connected_v4(connp, &mp->b_cont, protocol,
4490 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4491 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4492 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4493 		break;
4494 	}
4495 	ASSERT(error != EINPROGRESS);
4496 	if (error != 0)
4497 		goto bad_addr;
4498 
4499 	/* Send it home. */
4500 	mp->b_datap->db_type = M_PCPROTO;
4501 	tbr->PRIM_type = T_BIND_ACK;
4502 	return (mp);
4503 
4504 bad_addr:
4505 	/*
4506 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4507 	 * a unix errno.
4508 	 */
4509 	if (error > 0)
4510 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4511 	else
4512 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4513 	return (mp);
4514 }
4515 
4516 /*
4517  * Here address is verified to be a valid local address.
4518  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4519  * address is also considered a valid local address.
4520  * In the case of a broadcast/multicast address, however, the
4521  * upper protocol is expected to reset the src address
4522  * to 0 if it sees a IRE_BROADCAST type returned so that
4523  * no packets are emitted with broadcast/multicast address as
4524  * source address (that violates hosts requirements RFC 1122)
4525  * The addresses valid for bind are:
4526  *	(1) - INADDR_ANY (0)
4527  *	(2) - IP address of an UP interface
4528  *	(3) - IP address of a DOWN interface
4529  *	(4) - valid local IP broadcast addresses. In this case
4530  *	the conn will only receive packets destined to
4531  *	the specified broadcast address.
4532  *	(5) - a multicast address. In this case
4533  *	the conn will only receive packets destined to
4534  *	the specified multicast address. Note: the
4535  *	application still has to issue an
4536  *	IP_ADD_MEMBERSHIP socket option.
4537  *
4538  * On error, return -1 for TBADADDR otherwise pass the
4539  * errno with TSYSERR reply.
4540  *
4541  * In all the above cases, the bound address must be valid in the current zone.
4542  * When the address is loopback, multicast or broadcast, there might be many
4543  * matching IREs so bind has to look up based on the zone.
4544  *
4545  * Note: lport is in network byte order.
4546  *
4547  */
4548 int
4549 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4550     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4551 {
4552 	int		error = 0;
4553 	ire_t		*src_ire;
4554 	zoneid_t	zoneid;
4555 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4556 	mblk_t		*mp = NULL;
4557 	boolean_t	ire_requested = B_FALSE;
4558 	boolean_t	ipsec_policy_set = B_FALSE;
4559 
4560 	if (mpp)
4561 		mp = *mpp;
4562 
4563 	if (mp != NULL) {
4564 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4565 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4566 	}
4567 
4568 	/*
4569 	 * If it was previously connected, conn_fully_bound would have
4570 	 * been set.
4571 	 */
4572 	connp->conn_fully_bound = B_FALSE;
4573 
4574 	src_ire = NULL;
4575 
4576 	zoneid = IPCL_ZONEID(connp);
4577 
4578 	if (src_addr) {
4579 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4580 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4581 		/*
4582 		 * If an address other than 0.0.0.0 is requested,
4583 		 * we verify that it is a valid address for bind
4584 		 * Note: Following code is in if-else-if form for
4585 		 * readability compared to a condition check.
4586 		 */
4587 		/* LINTED - statement has no consequence */
4588 		if (IRE_IS_LOCAL(src_ire)) {
4589 			/*
4590 			 * (2) Bind to address of local UP interface
4591 			 */
4592 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4593 			/*
4594 			 * (4) Bind to broadcast address
4595 			 * Note: permitted only from transports that
4596 			 * request IRE
4597 			 */
4598 			if (!ire_requested)
4599 				error = EADDRNOTAVAIL;
4600 		} else {
4601 			/*
4602 			 * (3) Bind to address of local DOWN interface
4603 			 * (ipif_lookup_addr() looks up all interfaces
4604 			 * but we do not get here for UP interfaces
4605 			 * - case (2) above)
4606 			 */
4607 			/* LINTED - statement has no consequent */
4608 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4609 				/* The address exists */
4610 			} else if (CLASSD(src_addr)) {
4611 				error = 0;
4612 				if (src_ire != NULL)
4613 					ire_refrele(src_ire);
4614 				/*
4615 				 * (5) bind to multicast address.
4616 				 * Fake out the IRE returned to upper
4617 				 * layer to be a broadcast IRE.
4618 				 */
4619 				src_ire = ire_ctable_lookup(
4620 				    INADDR_BROADCAST, INADDR_ANY,
4621 				    IRE_BROADCAST, NULL, zoneid, NULL,
4622 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4623 				    ipst);
4624 				if (src_ire == NULL || !ire_requested)
4625 					error = EADDRNOTAVAIL;
4626 			} else {
4627 				/*
4628 				 * Not a valid address for bind
4629 				 */
4630 				error = EADDRNOTAVAIL;
4631 			}
4632 		}
4633 		if (error) {
4634 			/* Red Alert!  Attempting to be a bogon! */
4635 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4636 			    ntohl(src_addr)));
4637 			goto bad_addr;
4638 		}
4639 	}
4640 
4641 	/*
4642 	 * Allow setting new policies. For example, disconnects come
4643 	 * down as ipa_t bind. As we would have set conn_policy_cached
4644 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4645 	 * can change after the disconnect.
4646 	 */
4647 	connp->conn_policy_cached = B_FALSE;
4648 
4649 	/*
4650 	 * If not fanout_insert this was just an address verification
4651 	 */
4652 	if (fanout_insert) {
4653 		/*
4654 		 * The addresses have been verified. Time to insert in
4655 		 * the correct fanout list.
4656 		 */
4657 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4658 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4659 		connp->conn_lport = lport;
4660 		connp->conn_fport = 0;
4661 		/*
4662 		 * Do we need to add a check to reject Multicast packets
4663 		 */
4664 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4665 	}
4666 
4667 	if (error == 0) {
4668 		if (ire_requested) {
4669 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4670 				error = -1;
4671 				/* Falls through to bad_addr */
4672 			}
4673 		} else if (ipsec_policy_set) {
4674 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4675 				error = -1;
4676 				/* Falls through to bad_addr */
4677 			}
4678 		}
4679 	}
4680 bad_addr:
4681 	if (error != 0) {
4682 		if (connp->conn_anon_port) {
4683 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4684 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4685 			    B_FALSE);
4686 		}
4687 		connp->conn_mlp_type = mlptSingle;
4688 	}
4689 	if (src_ire != NULL)
4690 		IRE_REFRELE(src_ire);
4691 	return (error);
4692 }
4693 
4694 int
4695 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4696     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4697 {
4698 	int error;
4699 
4700 	ASSERT(!connp->conn_af_isv6);
4701 	connp->conn_pkt_isv6 = B_FALSE;
4702 	connp->conn_ulp = protocol;
4703 
4704 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4705 	    fanout_insert);
4706 	if (error < 0)
4707 		error = -TBADADDR;
4708 	return (error);
4709 }
4710 
4711 /*
4712  * Verify that both the source and destination addresses
4713  * are valid.  If verify_dst is false, then the destination address may be
4714  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4715  * destination reachability, while tunnels do not.
4716  * Note that we allow connect to broadcast and multicast
4717  * addresses when ire_requested is set. Thus the ULP
4718  * has to check for IRE_BROADCAST and multicast.
4719  *
4720  * Returns zero if ok.
4721  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4722  * (for use with TSYSERR reply).
4723  *
4724  * Note: lport and fport are in network byte order.
4725  */
4726 int
4727 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4728     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4729     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4730 {
4731 
4732 	ire_t		*src_ire;
4733 	ire_t		*dst_ire;
4734 	int		error = 0;
4735 	ire_t		*sire = NULL;
4736 	ire_t		*md_dst_ire = NULL;
4737 	ire_t		*lso_dst_ire = NULL;
4738 	ill_t		*ill = NULL;
4739 	zoneid_t	zoneid;
4740 	ipaddr_t	src_addr = *src_addrp;
4741 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4742 	mblk_t		*mp = NULL;
4743 	boolean_t	ire_requested = B_FALSE;
4744 	boolean_t	ipsec_policy_set = B_FALSE;
4745 	ts_label_t	*tsl = NULL;
4746 	cred_t		*effective_cred = NULL;
4747 
4748 	if (mpp)
4749 		mp = *mpp;
4750 
4751 	if (mp != NULL) {
4752 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4753 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4754 	}
4755 
4756 	src_ire = dst_ire = NULL;
4757 
4758 	/*
4759 	 * If we never got a disconnect before, clear it now.
4760 	 */
4761 	connp->conn_fully_bound = B_FALSE;
4762 
4763 	zoneid = IPCL_ZONEID(connp);
4764 
4765 	/*
4766 	 * Check whether Trusted Solaris policy allows communication with this
4767 	 * host, and pretend that the destination is unreachable if not.
4768 	 *
4769 	 * This is never a problem for TCP, since that transport is known to
4770 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4771 	 * handling.  If the remote is unreachable, it will be detected at that
4772 	 * point, so there's no reason to check it here.
4773 	 *
4774 	 * Note that for sendto (and other datagram-oriented friends), this
4775 	 * check is done as part of the data path label computation instead.
4776 	 * The check here is just to make non-TCP connect() report the right
4777 	 * error.
4778 	 */
4779 	if (is_system_labeled() && !IPCL_IS_TCP(connp)) {
4780 		if ((error = tsol_check_dest(cr, &dst_addr, IPV4_VERSION,
4781 		    connp->conn_mac_exempt, &effective_cred)) != 0) {
4782 			if (ip_debug > 2) {
4783 				pr_addr_dbg(
4784 				    "ip_bind_connected_v4:"
4785 				    " no label for dst %s\n",
4786 				    AF_INET, &dst_addr);
4787 			}
4788 			goto bad_addr;
4789 		}
4790 
4791 		/*
4792 		 * tsol_check_dest() may have created a new cred with
4793 		 * a modified security label. Use that cred if it exists
4794 		 * for ire lookups.
4795 		 */
4796 		if (effective_cred == NULL) {
4797 			tsl = crgetlabel(cr);
4798 		} else {
4799 			tsl = crgetlabel(effective_cred);
4800 		}
4801 	}
4802 
4803 	if (CLASSD(dst_addr)) {
4804 		/* Pick up an IRE_BROADCAST */
4805 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4806 		    NULL, zoneid, tsl,
4807 		    (MATCH_IRE_RECURSIVE |
4808 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4809 		    MATCH_IRE_SECATTR), ipst);
4810 	} else {
4811 		/*
4812 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4813 		 * and onlink ipif is not found set ENETUNREACH error.
4814 		 */
4815 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4816 			ipif_t *ipif;
4817 
4818 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4819 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4820 			if (ipif == NULL) {
4821 				error = ENETUNREACH;
4822 				goto bad_addr;
4823 			}
4824 			ipif_refrele(ipif);
4825 		}
4826 
4827 		if (connp->conn_nexthop_set) {
4828 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4829 			    0, 0, NULL, NULL, zoneid, tsl,
4830 			    MATCH_IRE_SECATTR, ipst);
4831 		} else {
4832 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4833 			    &sire, zoneid, tsl,
4834 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4835 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4836 			    MATCH_IRE_SECATTR), ipst);
4837 		}
4838 	}
4839 	/*
4840 	 * dst_ire can't be a broadcast when not ire_requested.
4841 	 * We also prevent ire's with src address INADDR_ANY to
4842 	 * be used, which are created temporarily for
4843 	 * sending out packets from endpoints that have
4844 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4845 	 * reachable.  If verify_dst is false, the destination needn't be
4846 	 * reachable.
4847 	 *
4848 	 * If we match on a reject or black hole, then we've got a
4849 	 * local failure.  May as well fail out the connect() attempt,
4850 	 * since it's never going to succeed.
4851 	 */
4852 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4853 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4854 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4855 		/*
4856 		 * If we're verifying destination reachability, we always want
4857 		 * to complain here.
4858 		 *
4859 		 * If we're not verifying destination reachability but the
4860 		 * destination has a route, we still want to fail on the
4861 		 * temporary address and broadcast address tests.
4862 		 */
4863 		if (verify_dst || (dst_ire != NULL)) {
4864 			if (ip_debug > 2) {
4865 				pr_addr_dbg("ip_bind_connected_v4:"
4866 				    "bad connected dst %s\n",
4867 				    AF_INET, &dst_addr);
4868 			}
4869 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4870 				error = ENETUNREACH;
4871 			else
4872 				error = EHOSTUNREACH;
4873 			goto bad_addr;
4874 		}
4875 	}
4876 
4877 	/*
4878 	 * If the app does a connect(), it means that it will most likely
4879 	 * send more than 1 packet to the destination.  It makes sense
4880 	 * to clear the temporary flag.
4881 	 */
4882 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4883 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4884 		irb_t *irb = dst_ire->ire_bucket;
4885 
4886 		rw_enter(&irb->irb_lock, RW_WRITER);
4887 		/*
4888 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4889 		 * the lock to guarantee irb_tmp_ire_cnt.
4890 		 */
4891 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4892 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4893 			irb->irb_tmp_ire_cnt--;
4894 		}
4895 		rw_exit(&irb->irb_lock);
4896 	}
4897 
4898 	/*
4899 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4900 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4901 	 * eligibility tests for passive connects are handled separately
4902 	 * through tcp_adapt_ire().  We do this before the source address
4903 	 * selection, because dst_ire may change after a call to
4904 	 * ipif_select_source().  This is a best-effort check, as the
4905 	 * packet for this connection may not actually go through
4906 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4907 	 * calling ip_newroute().  This is why we further check on the
4908 	 * IRE during LSO/Multidata packet transmission in
4909 	 * tcp_lsosend()/tcp_multisend().
4910 	 */
4911 	if (!ipsec_policy_set && dst_ire != NULL &&
4912 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4913 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4914 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4915 			lso_dst_ire = dst_ire;
4916 			IRE_REFHOLD(lso_dst_ire);
4917 		} else if (ipst->ips_ip_multidata_outbound &&
4918 		    ILL_MDT_CAPABLE(ill)) {
4919 			md_dst_ire = dst_ire;
4920 			IRE_REFHOLD(md_dst_ire);
4921 		}
4922 	}
4923 
4924 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4925 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4926 		/*
4927 		 * If the IRE belongs to a different zone, look for a matching
4928 		 * route in the forwarding table and use the source address from
4929 		 * that route.
4930 		 */
4931 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4932 		    zoneid, 0, NULL,
4933 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4934 		    MATCH_IRE_RJ_BHOLE, ipst);
4935 		if (src_ire == NULL) {
4936 			error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4939 			if (!(src_ire->ire_type & IRE_HOST))
4940 				error = ENETUNREACH;
4941 			else
4942 				error = EHOSTUNREACH;
4943 			goto bad_addr;
4944 		}
4945 		if (src_addr == INADDR_ANY)
4946 			src_addr = src_ire->ire_src_addr;
4947 		ire_refrele(src_ire);
4948 		src_ire = NULL;
4949 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4950 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4951 			src_addr = sire->ire_src_addr;
4952 			ire_refrele(dst_ire);
4953 			dst_ire = sire;
4954 			sire = NULL;
4955 		} else {
4956 			/*
4957 			 * Pick a source address so that a proper inbound
4958 			 * load spreading would happen.
4959 			 */
4960 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
4961 			ipif_t *src_ipif = NULL;
4962 			ire_t *ipif_ire;
4963 
4964 			/*
4965 			 * Supply a local source address such that inbound
4966 			 * load spreading happens.
4967 			 *
4968 			 * Determine the best source address on this ill for
4969 			 * the destination.
4970 			 *
4971 			 * 1) For broadcast, we should return a broadcast ire
4972 			 *    found above so that upper layers know that the
4973 			 *    destination address is a broadcast address.
4974 			 *
4975 			 * 2) If the ipif is DEPRECATED, select a better
4976 			 *    source address.  Similarly, if the ipif is on
4977 			 *    the IPMP meta-interface, pick a source address
4978 			 *    at random to improve inbound load spreading.
4979 			 *
4980 			 * 3) If the outgoing interface is part of a usesrc
4981 			 *    group, then try selecting a source address from
4982 			 *    the usesrc ILL.
4983 			 */
4984 			if ((dst_ire->ire_zoneid != zoneid &&
4985 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4986 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4987 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4988 			    (IS_IPMP(ire_ill) ||
4989 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4990 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
4991 				/*
4992 				 * If the destination is reachable via a
4993 				 * given gateway, the selected source address
4994 				 * should be in the same subnet as the gateway.
4995 				 * Otherwise, the destination is not reachable.
4996 				 *
4997 				 * If there are no interfaces on the same subnet
4998 				 * as the destination, ipif_select_source gives
4999 				 * first non-deprecated interface which might be
5000 				 * on a different subnet than the gateway.
5001 				 * This is not desirable. Hence pass the dst_ire
5002 				 * source address to ipif_select_source.
5003 				 * It is sure that the destination is reachable
5004 				 * with the dst_ire source address subnet.
5005 				 * So passing dst_ire source address to
5006 				 * ipif_select_source will make sure that the
5007 				 * selected source will be on the same subnet
5008 				 * as dst_ire source address.
5009 				 */
5010 				ipaddr_t saddr =
5011 				    dst_ire->ire_ipif->ipif_src_addr;
5012 				src_ipif = ipif_select_source(ire_ill,
5013 				    saddr, zoneid);
5014 				if (src_ipif != NULL) {
5015 					if (IS_VNI(src_ipif->ipif_ill)) {
5016 						/*
5017 						 * For VNI there is no
5018 						 * interface route
5019 						 */
5020 						src_addr =
5021 						    src_ipif->ipif_src_addr;
5022 					} else {
5023 						ipif_ire =
5024 						    ipif_to_ire(src_ipif);
5025 						if (ipif_ire != NULL) {
5026 							IRE_REFRELE(dst_ire);
5027 							dst_ire = ipif_ire;
5028 						}
5029 						src_addr =
5030 						    dst_ire->ire_src_addr;
5031 					}
5032 					ipif_refrele(src_ipif);
5033 				} else {
5034 					src_addr = dst_ire->ire_src_addr;
5035 				}
5036 			} else {
5037 				src_addr = dst_ire->ire_src_addr;
5038 			}
5039 		}
5040 	}
5041 
5042 	/*
5043 	 * We do ire_route_lookup() here (and not
5044 	 * interface lookup as we assert that
5045 	 * src_addr should only come from an
5046 	 * UP interface for hard binding.
5047 	 */
5048 	ASSERT(src_ire == NULL);
5049 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5050 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5051 	/* src_ire must be a local|loopback */
5052 	if (!IRE_IS_LOCAL(src_ire)) {
5053 		if (ip_debug > 2) {
5054 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5055 			    "src %s\n", AF_INET, &src_addr);
5056 		}
5057 		error = EADDRNOTAVAIL;
5058 		goto bad_addr;
5059 	}
5060 
5061 	/*
5062 	 * If the source address is a loopback address, the
5063 	 * destination had best be local or multicast.
5064 	 * The transports that can't handle multicast will reject
5065 	 * those addresses.
5066 	 */
5067 	if (src_ire->ire_type == IRE_LOOPBACK &&
5068 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5069 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5070 		error = -1;
5071 		goto bad_addr;
5072 	}
5073 
5074 	/*
5075 	 * Allow setting new policies. For example, disconnects come
5076 	 * down as ipa_t bind. As we would have set conn_policy_cached
5077 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5078 	 * can change after the disconnect.
5079 	 */
5080 	connp->conn_policy_cached = B_FALSE;
5081 
5082 	/*
5083 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5084 	 * can handle their passed-in conn's.
5085 	 */
5086 
5087 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5088 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5089 	connp->conn_lport = lport;
5090 	connp->conn_fport = fport;
5091 	*src_addrp = src_addr;
5092 
5093 	ASSERT(!(ipsec_policy_set && ire_requested));
5094 	if (ire_requested) {
5095 		iulp_t *ulp_info = NULL;
5096 
5097 		/*
5098 		 * Note that sire will not be NULL if this is an off-link
5099 		 * connection and there is not cache for that dest yet.
5100 		 *
5101 		 * XXX Because of an existing bug, if there are multiple
5102 		 * default routes, the IRE returned now may not be the actual
5103 		 * default route used (default routes are chosen in a
5104 		 * round robin fashion).  So if the metrics for different
5105 		 * default routes are different, we may return the wrong
5106 		 * metrics.  This will not be a problem if the existing
5107 		 * bug is fixed.
5108 		 */
5109 		if (sire != NULL) {
5110 			ulp_info = &(sire->ire_uinfo);
5111 		}
5112 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5113 			error = -1;
5114 			goto bad_addr;
5115 		}
5116 		mp = *mpp;
5117 	} else if (ipsec_policy_set) {
5118 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5119 			error = -1;
5120 			goto bad_addr;
5121 		}
5122 	}
5123 
5124 	/*
5125 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5126 	 * we'll cache that.  If we don't, we'll inherit global policy.
5127 	 *
5128 	 * We can't insert until the conn reflects the policy. Note that
5129 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5130 	 * connections where we don't have a policy. This is to prevent
5131 	 * global policy lookups in the inbound path.
5132 	 *
5133 	 * If we insert before we set conn_policy_cached,
5134 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5135 	 * because global policy cound be non-empty. We normally call
5136 	 * ipsec_check_policy() for conn_policy_cached connections only if
5137 	 * ipc_in_enforce_policy is set. But in this case,
5138 	 * conn_policy_cached can get set anytime since we made the
5139 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5140 	 * called, which will make the above assumption false.  Thus, we
5141 	 * need to insert after we set conn_policy_cached.
5142 	 */
5143 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5144 		goto bad_addr;
5145 
5146 	if (fanout_insert) {
5147 		/*
5148 		 * The addresses have been verified. Time to insert in
5149 		 * the correct fanout list.
5150 		 */
5151 		error = ipcl_conn_insert(connp, protocol, src_addr,
5152 		    dst_addr, connp->conn_ports);
5153 	}
5154 
5155 	if (error == 0) {
5156 		connp->conn_fully_bound = B_TRUE;
5157 		/*
5158 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5159 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5160 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5161 		 * ip_xxinfo_return(), which performs further checks
5162 		 * against them and upon success, returns the LSO/MDT info
5163 		 * mblk which we will attach to the bind acknowledgment.
5164 		 */
5165 		if (lso_dst_ire != NULL) {
5166 			mblk_t *lsoinfo_mp;
5167 
5168 			ASSERT(ill->ill_lso_capab != NULL);
5169 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5170 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5171 				if (mp == NULL) {
5172 					*mpp = lsoinfo_mp;
5173 				} else {
5174 					linkb(mp, lsoinfo_mp);
5175 				}
5176 			}
5177 		} else if (md_dst_ire != NULL) {
5178 			mblk_t *mdinfo_mp;
5179 
5180 			ASSERT(ill->ill_mdt_capab != NULL);
5181 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5182 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5183 				if (mp == NULL) {
5184 					*mpp = mdinfo_mp;
5185 				} else {
5186 					linkb(mp, mdinfo_mp);
5187 				}
5188 			}
5189 		}
5190 	}
5191 bad_addr:
5192 	if (ipsec_policy_set) {
5193 		ASSERT(mp != NULL);
5194 		freeb(mp);
5195 		/*
5196 		 * As of now assume that nothing else accompanies
5197 		 * IPSEC_POLICY_SET.
5198 		 */
5199 		*mpp = NULL;
5200 	}
5201 	if (src_ire != NULL)
5202 		IRE_REFRELE(src_ire);
5203 	if (dst_ire != NULL)
5204 		IRE_REFRELE(dst_ire);
5205 	if (sire != NULL)
5206 		IRE_REFRELE(sire);
5207 	if (md_dst_ire != NULL)
5208 		IRE_REFRELE(md_dst_ire);
5209 	if (lso_dst_ire != NULL)
5210 		IRE_REFRELE(lso_dst_ire);
5211 	if (effective_cred != NULL)
5212 		crfree(effective_cred);
5213 	return (error);
5214 }
5215 
5216 int
5217 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5218     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5219     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5220 {
5221 	int error;
5222 
5223 	ASSERT(!connp->conn_af_isv6);
5224 	connp->conn_pkt_isv6 = B_FALSE;
5225 	connp->conn_ulp = protocol;
5226 
5227 	/* For raw socket, the local port is not set. */
5228 	if (lport == 0)
5229 		lport = connp->conn_lport;
5230 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5231 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5232 	if (error < 0)
5233 		error = -TBADADDR;
5234 	return (error);
5235 }
5236 
5237 /*
5238  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5239  * Prefers dst_ire over src_ire.
5240  */
5241 static boolean_t
5242 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5243 {
5244 	mblk_t	*mp = *mpp;
5245 	ire_t	*ret_ire;
5246 
5247 	ASSERT(mp != NULL);
5248 
5249 	if (ire != NULL) {
5250 		/*
5251 		 * mp initialized above to IRE_DB_REQ_TYPE
5252 		 * appended mblk. Its <upper protocol>'s
5253 		 * job to make sure there is room.
5254 		 */
5255 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5256 			return (B_FALSE);
5257 
5258 		mp->b_datap->db_type = IRE_DB_TYPE;
5259 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5260 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5261 		ret_ire = (ire_t *)mp->b_rptr;
5262 		/*
5263 		 * Pass the latest setting of the ip_path_mtu_discovery and
5264 		 * copy the ulp info if any.
5265 		 */
5266 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5267 		    IPH_DF : 0;
5268 		if (ulp_info != NULL) {
5269 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5270 			    sizeof (iulp_t));
5271 		}
5272 		ret_ire->ire_mp = mp;
5273 	} else {
5274 		/*
5275 		 * No IRE was found. Remove IRE mblk.
5276 		 */
5277 		*mpp = mp->b_cont;
5278 		freeb(mp);
5279 	}
5280 	return (B_TRUE);
5281 }
5282 
5283 /*
5284  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5285  * the final piece where we don't.  Return a pointer to the first mblk in the
5286  * result, and update the pointer to the next mblk to chew on.  If anything
5287  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5288  * NULL pointer.
5289  */
5290 mblk_t *
5291 ip_carve_mp(mblk_t **mpp, ssize_t len)
5292 {
5293 	mblk_t	*mp0;
5294 	mblk_t	*mp1;
5295 	mblk_t	*mp2;
5296 
5297 	if (!len || !mpp || !(mp0 = *mpp))
5298 		return (NULL);
5299 	/* If we aren't going to consume the first mblk, we need a dup. */
5300 	if (mp0->b_wptr - mp0->b_rptr > len) {
5301 		mp1 = dupb(mp0);
5302 		if (mp1) {
5303 			/* Partition the data between the two mblks. */
5304 			mp1->b_wptr = mp1->b_rptr + len;
5305 			mp0->b_rptr = mp1->b_wptr;
5306 			/*
5307 			 * after adjustments if mblk not consumed is now
5308 			 * unaligned, try to align it. If this fails free
5309 			 * all messages and let upper layer recover.
5310 			 */
5311 			if (!OK_32PTR(mp0->b_rptr)) {
5312 				if (!pullupmsg(mp0, -1)) {
5313 					freemsg(mp0);
5314 					freemsg(mp1);
5315 					*mpp = NULL;
5316 					return (NULL);
5317 				}
5318 			}
5319 		}
5320 		return (mp1);
5321 	}
5322 	/* Eat through as many mblks as we need to get len bytes. */
5323 	len -= mp0->b_wptr - mp0->b_rptr;
5324 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5325 		if (mp2->b_wptr - mp2->b_rptr > len) {
5326 			/*
5327 			 * We won't consume the entire last mblk.  Like
5328 			 * above, dup and partition it.
5329 			 */
5330 			mp1->b_cont = dupb(mp2);
5331 			mp1 = mp1->b_cont;
5332 			if (!mp1) {
5333 				/*
5334 				 * Trouble.  Rather than go to a lot of
5335 				 * trouble to clean up, we free the messages.
5336 				 * This won't be any worse than losing it on
5337 				 * the wire.
5338 				 */
5339 				freemsg(mp0);
5340 				freemsg(mp2);
5341 				*mpp = NULL;
5342 				return (NULL);
5343 			}
5344 			mp1->b_wptr = mp1->b_rptr + len;
5345 			mp2->b_rptr = mp1->b_wptr;
5346 			/*
5347 			 * after adjustments if mblk not consumed is now
5348 			 * unaligned, try to align it. If this fails free
5349 			 * all messages and let upper layer recover.
5350 			 */
5351 			if (!OK_32PTR(mp2->b_rptr)) {
5352 				if (!pullupmsg(mp2, -1)) {
5353 					freemsg(mp0);
5354 					freemsg(mp2);
5355 					*mpp = NULL;
5356 					return (NULL);
5357 				}
5358 			}
5359 			*mpp = mp2;
5360 			return (mp0);
5361 		}
5362 		/* Decrement len by the amount we just got. */
5363 		len -= mp2->b_wptr - mp2->b_rptr;
5364 	}
5365 	/*
5366 	 * len should be reduced to zero now.  If not our caller has
5367 	 * screwed up.
5368 	 */
5369 	if (len) {
5370 		/* Shouldn't happen! */
5371 		freemsg(mp0);
5372 		*mpp = NULL;
5373 		return (NULL);
5374 	}
5375 	/*
5376 	 * We consumed up to exactly the end of an mblk.  Detach the part
5377 	 * we are returning from the rest of the chain.
5378 	 */
5379 	mp1->b_cont = NULL;
5380 	*mpp = mp2;
5381 	return (mp0);
5382 }
5383 
5384 /* The ill stream is being unplumbed. Called from ip_close */
5385 int
5386 ip_modclose(ill_t *ill)
5387 {
5388 	boolean_t success;
5389 	ipsq_t	*ipsq;
5390 	ipif_t	*ipif;
5391 	queue_t	*q = ill->ill_rq;
5392 	ip_stack_t	*ipst = ill->ill_ipst;
5393 	int	i;
5394 
5395 	/*
5396 	 * The punlink prior to this may have initiated a capability
5397 	 * negotiation. But ipsq_enter will block until that finishes or
5398 	 * times out.
5399 	 */
5400 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5401 
5402 	/*
5403 	 * Open/close/push/pop is guaranteed to be single threaded
5404 	 * per stream by STREAMS. FS guarantees that all references
5405 	 * from top are gone before close is called. So there can't
5406 	 * be another close thread that has set CONDEMNED on this ill.
5407 	 * and cause ipsq_enter to return failure.
5408 	 */
5409 	ASSERT(success);
5410 	ipsq = ill->ill_phyint->phyint_ipsq;
5411 
5412 	/*
5413 	 * Mark it condemned. No new reference will be made to this ill.
5414 	 * Lookup functions will return an error. Threads that try to
5415 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5416 	 * that the refcnt will drop down to zero.
5417 	 */
5418 	mutex_enter(&ill->ill_lock);
5419 	ill->ill_state_flags |= ILL_CONDEMNED;
5420 	for (ipif = ill->ill_ipif; ipif != NULL;
5421 	    ipif = ipif->ipif_next) {
5422 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5423 	}
5424 	/*
5425 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5426 	 * returns  error if ILL_CONDEMNED is set
5427 	 */
5428 	cv_broadcast(&ill->ill_cv);
5429 	mutex_exit(&ill->ill_lock);
5430 
5431 	/*
5432 	 * Send all the deferred DLPI messages downstream which came in
5433 	 * during the small window right before ipsq_enter(). We do this
5434 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5435 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5436 	 */
5437 	ill_dlpi_send_deferred(ill);
5438 
5439 	/*
5440 	 * Shut down fragmentation reassembly.
5441 	 * ill_frag_timer won't start a timer again.
5442 	 * Now cancel any existing timer
5443 	 */
5444 	(void) untimeout(ill->ill_frag_timer_id);
5445 	(void) ill_frag_timeout(ill, 0);
5446 
5447 	/*
5448 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5449 	 * this ill. Then wait for the refcnts to drop to zero.
5450 	 * ill_is_freeable checks whether the ill is really quiescent.
5451 	 * Then make sure that threads that are waiting to enter the
5452 	 * ipsq have seen the error returned by ipsq_enter and have
5453 	 * gone away. Then we call ill_delete_tail which does the
5454 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5455 	 */
5456 	ill_delete(ill);
5457 	mutex_enter(&ill->ill_lock);
5458 	while (!ill_is_freeable(ill))
5459 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5460 	while (ill->ill_waiters)
5461 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5462 
5463 	mutex_exit(&ill->ill_lock);
5464 
5465 	/*
5466 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5467 	 * it held until the end of the function since the cleanup
5468 	 * below needs to be able to use the ip_stack_t.
5469 	 */
5470 	netstack_hold(ipst->ips_netstack);
5471 
5472 	/* qprocsoff is done via ill_delete_tail */
5473 	ill_delete_tail(ill);
5474 	ASSERT(ill->ill_ipst == NULL);
5475 
5476 	/*
5477 	 * Walk through all upper (conn) streams and qenable
5478 	 * those that have queued data.
5479 	 * close synchronization needs this to
5480 	 * be done to ensure that all upper layers blocked
5481 	 * due to flow control to the closing device
5482 	 * get unblocked.
5483 	 */
5484 	ip1dbg(("ip_wsrv: walking\n"));
5485 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5486 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5487 	}
5488 
5489 	mutex_enter(&ipst->ips_ip_mi_lock);
5490 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5491 	mutex_exit(&ipst->ips_ip_mi_lock);
5492 
5493 	/*
5494 	 * credp could be null if the open didn't succeed and ip_modopen
5495 	 * itself calls ip_close.
5496 	 */
5497 	if (ill->ill_credp != NULL)
5498 		crfree(ill->ill_credp);
5499 
5500 	/*
5501 	 * Now we are done with the module close pieces that
5502 	 * need the netstack_t.
5503 	 */
5504 	netstack_rele(ipst->ips_netstack);
5505 
5506 	mi_close_free((IDP)ill);
5507 	q->q_ptr = WR(q)->q_ptr = NULL;
5508 
5509 	ipsq_exit(ipsq);
5510 
5511 	return (0);
5512 }
5513 
5514 /*
5515  * This is called as part of close() for IP, UDP, ICMP, and RTS
5516  * in order to quiesce the conn.
5517  */
5518 void
5519 ip_quiesce_conn(conn_t *connp)
5520 {
5521 	boolean_t	drain_cleanup_reqd = B_FALSE;
5522 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5523 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5524 	ip_stack_t	*ipst;
5525 
5526 	ASSERT(!IPCL_IS_TCP(connp));
5527 	ipst = connp->conn_netstack->netstack_ip;
5528 
5529 	/*
5530 	 * Mark the conn as closing, and this conn must not be
5531 	 * inserted in future into any list. Eg. conn_drain_insert(),
5532 	 * won't insert this conn into the conn_drain_list.
5533 	 * Similarly ill_pending_mp_add() will not add any mp to
5534 	 * the pending mp list, after this conn has started closing.
5535 	 *
5536 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5537 	 * cannot get set henceforth.
5538 	 */
5539 	mutex_enter(&connp->conn_lock);
5540 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5541 	connp->conn_state_flags |= CONN_CLOSING;
5542 	if (connp->conn_idl != NULL)
5543 		drain_cleanup_reqd = B_TRUE;
5544 	if (connp->conn_oper_pending_ill != NULL)
5545 		conn_ioctl_cleanup_reqd = B_TRUE;
5546 	if (connp->conn_dhcpinit_ill != NULL) {
5547 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5548 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5549 		connp->conn_dhcpinit_ill = NULL;
5550 	}
5551 	if (connp->conn_ilg_inuse != 0)
5552 		ilg_cleanup_reqd = B_TRUE;
5553 	mutex_exit(&connp->conn_lock);
5554 
5555 	if (conn_ioctl_cleanup_reqd)
5556 		conn_ioctl_cleanup(connp);
5557 
5558 	if (is_system_labeled() && connp->conn_anon_port) {
5559 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5560 		    connp->conn_mlp_type, connp->conn_ulp,
5561 		    ntohs(connp->conn_lport), B_FALSE);
5562 		connp->conn_anon_port = 0;
5563 	}
5564 	connp->conn_mlp_type = mlptSingle;
5565 
5566 	/*
5567 	 * Remove this conn from any fanout list it is on.
5568 	 * and then wait for any threads currently operating
5569 	 * on this endpoint to finish
5570 	 */
5571 	ipcl_hash_remove(connp);
5572 
5573 	/*
5574 	 * Remove this conn from the drain list, and do
5575 	 * any other cleanup that may be required.
5576 	 * (Only non-tcp streams may have a non-null conn_idl.
5577 	 * TCP streams are never flow controlled, and
5578 	 * conn_idl will be null)
5579 	 */
5580 	if (drain_cleanup_reqd)
5581 		conn_drain_tail(connp, B_TRUE);
5582 
5583 	if (connp == ipst->ips_ip_g_mrouter)
5584 		(void) ip_mrouter_done(NULL, ipst);
5585 
5586 	if (ilg_cleanup_reqd)
5587 		ilg_delete_all(connp);
5588 
5589 	conn_delete_ire(connp, NULL);
5590 
5591 	/*
5592 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5593 	 * callers from write side can't be there now because close
5594 	 * is in progress. The only other caller is ipcl_walk
5595 	 * which checks for the condemned flag.
5596 	 */
5597 	mutex_enter(&connp->conn_lock);
5598 	connp->conn_state_flags |= CONN_CONDEMNED;
5599 	while (connp->conn_ref != 1)
5600 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5601 	connp->conn_state_flags |= CONN_QUIESCED;
5602 	mutex_exit(&connp->conn_lock);
5603 }
5604 
5605 /* ARGSUSED */
5606 int
5607 ip_close(queue_t *q, int flags)
5608 {
5609 	conn_t		*connp;
5610 
5611 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5612 
5613 	/*
5614 	 * Call the appropriate delete routine depending on whether this is
5615 	 * a module or device.
5616 	 */
5617 	if (WR(q)->q_next != NULL) {
5618 		/* This is a module close */
5619 		return (ip_modclose((ill_t *)q->q_ptr));
5620 	}
5621 
5622 	connp = q->q_ptr;
5623 	ip_quiesce_conn(connp);
5624 
5625 	qprocsoff(q);
5626 
5627 	/*
5628 	 * Now we are truly single threaded on this stream, and can
5629 	 * delete the things hanging off the connp, and finally the connp.
5630 	 * We removed this connp from the fanout list, it cannot be
5631 	 * accessed thru the fanouts, and we already waited for the
5632 	 * conn_ref to drop to 0. We are already in close, so
5633 	 * there cannot be any other thread from the top. qprocsoff
5634 	 * has completed, and service has completed or won't run in
5635 	 * future.
5636 	 */
5637 	ASSERT(connp->conn_ref == 1);
5638 
5639 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5640 
5641 	connp->conn_ref--;
5642 	ipcl_conn_destroy(connp);
5643 
5644 	q->q_ptr = WR(q)->q_ptr = NULL;
5645 	return (0);
5646 }
5647 
5648 /*
5649  * Wapper around putnext() so that ip_rts_request can merely use
5650  * conn_recv.
5651  */
5652 /*ARGSUSED2*/
5653 static void
5654 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5655 {
5656 	conn_t *connp = (conn_t *)arg1;
5657 
5658 	putnext(connp->conn_rq, mp);
5659 }
5660 
5661 /*
5662  * Called when the module is about to be unloaded
5663  */
5664 void
5665 ip_ddi_destroy(void)
5666 {
5667 	tnet_fini();
5668 
5669 	icmp_ddi_g_destroy();
5670 	rts_ddi_g_destroy();
5671 	udp_ddi_g_destroy();
5672 	sctp_ddi_g_destroy();
5673 	tcp_ddi_g_destroy();
5674 	ipsec_policy_g_destroy();
5675 	ipcl_g_destroy();
5676 	ip_net_g_destroy();
5677 	ip_ire_g_fini();
5678 	inet_minor_destroy(ip_minor_arena_sa);
5679 #if defined(_LP64)
5680 	inet_minor_destroy(ip_minor_arena_la);
5681 #endif
5682 
5683 #ifdef DEBUG
5684 	list_destroy(&ip_thread_list);
5685 	rw_destroy(&ip_thread_rwlock);
5686 	tsd_destroy(&ip_thread_data);
5687 #endif
5688 
5689 	netstack_unregister(NS_IP);
5690 }
5691 
5692 /*
5693  * First step in cleanup.
5694  */
5695 /* ARGSUSED */
5696 static void
5697 ip_stack_shutdown(netstackid_t stackid, void *arg)
5698 {
5699 	ip_stack_t *ipst = (ip_stack_t *)arg;
5700 
5701 #ifdef NS_DEBUG
5702 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5703 #endif
5704 
5705 	/*
5706 	 * Perform cleanup for special interfaces (loopback and IPMP).
5707 	 */
5708 	ip_interface_cleanup(ipst);
5709 
5710 	/*
5711 	 * The *_hook_shutdown()s start the process of notifying any
5712 	 * consumers that things are going away.... nothing is destroyed.
5713 	 */
5714 	ipv4_hook_shutdown(ipst);
5715 	ipv6_hook_shutdown(ipst);
5716 
5717 	mutex_enter(&ipst->ips_capab_taskq_lock);
5718 	ipst->ips_capab_taskq_quit = B_TRUE;
5719 	cv_signal(&ipst->ips_capab_taskq_cv);
5720 	mutex_exit(&ipst->ips_capab_taskq_lock);
5721 
5722 	mutex_enter(&ipst->ips_mrt_lock);
5723 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5724 	cv_signal(&ipst->ips_mrt_cv);
5725 	mutex_exit(&ipst->ips_mrt_lock);
5726 }
5727 
5728 /*
5729  * Free the IP stack instance.
5730  */
5731 static void
5732 ip_stack_fini(netstackid_t stackid, void *arg)
5733 {
5734 	ip_stack_t *ipst = (ip_stack_t *)arg;
5735 	int ret;
5736 
5737 #ifdef NS_DEBUG
5738 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5739 #endif
5740 	/*
5741 	 * At this point, all of the notifications that the events and
5742 	 * protocols are going away have been run, meaning that we can
5743 	 * now set about starting to clean things up.
5744 	 */
5745 	ipobs_fini(ipst);
5746 	ipv4_hook_destroy(ipst);
5747 	ipv6_hook_destroy(ipst);
5748 	ip_net_destroy(ipst);
5749 
5750 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5751 	cv_destroy(&ipst->ips_capab_taskq_cv);
5752 
5753 	mutex_enter(&ipst->ips_mrt_lock);
5754 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5755 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5756 	mutex_destroy(&ipst->ips_mrt_lock);
5757 	cv_destroy(&ipst->ips_mrt_cv);
5758 	cv_destroy(&ipst->ips_mrt_done_cv);
5759 
5760 	ipmp_destroy(ipst);
5761 	rw_destroy(&ipst->ips_srcid_lock);
5762 
5763 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5764 	ipst->ips_ip_mibkp = NULL;
5765 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5766 	ipst->ips_icmp_mibkp = NULL;
5767 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5768 	ipst->ips_ip_kstat = NULL;
5769 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5770 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5771 	ipst->ips_ip6_kstat = NULL;
5772 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5773 
5774 	nd_free(&ipst->ips_ip_g_nd);
5775 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5776 	ipst->ips_param_arr = NULL;
5777 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5778 	ipst->ips_ndp_arr = NULL;
5779 
5780 	ip_mrouter_stack_destroy(ipst);
5781 
5782 	mutex_destroy(&ipst->ips_ip_mi_lock);
5783 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5784 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5785 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5786 
5787 	ret = untimeout(ipst->ips_igmp_timeout_id);
5788 	if (ret == -1) {
5789 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5790 	} else {
5791 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5792 		ipst->ips_igmp_timeout_id = 0;
5793 	}
5794 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5795 	if (ret == -1) {
5796 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5797 	} else {
5798 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5799 		ipst->ips_igmp_slowtimeout_id = 0;
5800 	}
5801 	ret = untimeout(ipst->ips_mld_timeout_id);
5802 	if (ret == -1) {
5803 		ASSERT(ipst->ips_mld_timeout_id == 0);
5804 	} else {
5805 		ASSERT(ipst->ips_mld_timeout_id != 0);
5806 		ipst->ips_mld_timeout_id = 0;
5807 	}
5808 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5809 	if (ret == -1) {
5810 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5811 	} else {
5812 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5813 		ipst->ips_mld_slowtimeout_id = 0;
5814 	}
5815 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5816 	if (ret == -1) {
5817 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5818 	} else {
5819 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5820 		ipst->ips_ip_ire_expire_id = 0;
5821 	}
5822 
5823 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5824 	mutex_destroy(&ipst->ips_mld_timer_lock);
5825 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5826 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5827 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5828 	rw_destroy(&ipst->ips_ill_g_lock);
5829 
5830 	ip_ire_fini(ipst);
5831 	ip6_asp_free(ipst);
5832 	conn_drain_fini(ipst);
5833 	ipcl_destroy(ipst);
5834 
5835 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5836 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5837 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5838 	ipst->ips_ndp4 = NULL;
5839 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5840 	ipst->ips_ndp6 = NULL;
5841 
5842 	if (ipst->ips_loopback_ksp != NULL) {
5843 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5844 		ipst->ips_loopback_ksp = NULL;
5845 	}
5846 
5847 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5848 	ipst->ips_phyint_g_list = NULL;
5849 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5850 	ipst->ips_ill_g_heads = NULL;
5851 
5852 	ldi_ident_release(ipst->ips_ldi_ident);
5853 	kmem_free(ipst, sizeof (*ipst));
5854 }
5855 
5856 /*
5857  * This function is called from the TSD destructor, and is used to debug
5858  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5859  * details.
5860  */
5861 static void
5862 ip_thread_exit(void *phash)
5863 {
5864 	th_hash_t *thh = phash;
5865 
5866 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5867 	list_remove(&ip_thread_list, thh);
5868 	rw_exit(&ip_thread_rwlock);
5869 	mod_hash_destroy_hash(thh->thh_hash);
5870 	kmem_free(thh, sizeof (*thh));
5871 }
5872 
5873 /*
5874  * Called when the IP kernel module is loaded into the kernel
5875  */
5876 void
5877 ip_ddi_init(void)
5878 {
5879 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5880 
5881 	/*
5882 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5883 	 * initial devices: ip, ip6, tcp, tcp6.
5884 	 */
5885 	/*
5886 	 * If this is a 64-bit kernel, then create two separate arenas -
5887 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5888 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5889 	 */
5890 	ip_minor_arena_la = NULL;
5891 	ip_minor_arena_sa = NULL;
5892 #if defined(_LP64)
5893 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5894 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5895 		cmn_err(CE_PANIC,
5896 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5897 	}
5898 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5899 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5900 		cmn_err(CE_PANIC,
5901 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5902 	}
5903 #else
5904 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5905 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5906 		cmn_err(CE_PANIC,
5907 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5908 	}
5909 #endif
5910 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5911 
5912 	ipcl_g_init();
5913 	ip_ire_g_init();
5914 	ip_net_g_init();
5915 
5916 #ifdef DEBUG
5917 	tsd_create(&ip_thread_data, ip_thread_exit);
5918 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5919 	list_create(&ip_thread_list, sizeof (th_hash_t),
5920 	    offsetof(th_hash_t, thh_link));
5921 #endif
5922 
5923 	/*
5924 	 * We want to be informed each time a stack is created or
5925 	 * destroyed in the kernel, so we can maintain the
5926 	 * set of udp_stack_t's.
5927 	 */
5928 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5929 	    ip_stack_fini);
5930 
5931 	ipsec_policy_g_init();
5932 	tcp_ddi_g_init();
5933 	sctp_ddi_g_init();
5934 
5935 	tnet_init();
5936 
5937 	udp_ddi_g_init();
5938 	rts_ddi_g_init();
5939 	icmp_ddi_g_init();
5940 }
5941 
5942 /*
5943  * Initialize the IP stack instance.
5944  */
5945 static void *
5946 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5947 {
5948 	ip_stack_t	*ipst;
5949 	ipparam_t	*pa;
5950 	ipndp_t		*na;
5951 	major_t		major;
5952 
5953 #ifdef NS_DEBUG
5954 	printf("ip_stack_init(stack %d)\n", stackid);
5955 #endif
5956 
5957 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5958 	ipst->ips_netstack = ns;
5959 
5960 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5961 	    KM_SLEEP);
5962 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5963 	    KM_SLEEP);
5964 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5965 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5966 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5967 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5968 
5969 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5970 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5971 	ipst->ips_igmp_deferred_next = INFINITY;
5972 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5973 	ipst->ips_mld_deferred_next = INFINITY;
5974 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5975 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5976 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5977 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5978 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5979 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5980 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5981 
5982 	ipcl_init(ipst);
5983 	ip_ire_init(ipst);
5984 	ip6_asp_init(ipst);
5985 	ipif_init(ipst);
5986 	conn_drain_init(ipst);
5987 	ip_mrouter_stack_init(ipst);
5988 
5989 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5990 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5991 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
5992 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
5993 
5994 	ipst->ips_ip_multirt_log_interval = 1000;
5995 
5996 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5997 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5998 	ipst->ips_ill_index = 1;
5999 
6000 	ipst->ips_saved_ip_g_forward = -1;
6001 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6002 
6003 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6004 	ipst->ips_param_arr = pa;
6005 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6006 
6007 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6008 	ipst->ips_ndp_arr = na;
6009 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6010 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6011 	    (caddr_t)&ipst->ips_ip_g_forward;
6012 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6013 	    (caddr_t)&ipst->ips_ipv6_forward;
6014 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6015 	    "ip_cgtp_filter") == 0);
6016 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6017 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6018 
6019 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6020 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6021 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6022 
6023 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6024 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6025 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6026 	ipst->ips_ip6_kstat =
6027 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6028 
6029 	ipst->ips_ip_src_id = 1;
6030 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6031 
6032 	ip_net_init(ipst, ns);
6033 	ipv4_hook_init(ipst);
6034 	ipv6_hook_init(ipst);
6035 	ipmp_init(ipst);
6036 	ipobs_init(ipst);
6037 
6038 	/*
6039 	 * Create the taskq dispatcher thread and initialize related stuff.
6040 	 */
6041 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6042 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6043 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6044 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6045 
6046 	/*
6047 	 * Create the mcast_restart_timers_thread() worker thread.
6048 	 */
6049 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6050 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6051 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6052 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6053 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6054 
6055 	major = mod_name_to_major(INET_NAME);
6056 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6057 	return (ipst);
6058 }
6059 
6060 /*
6061  * Allocate and initialize a DLPI template of the specified length.  (May be
6062  * called as writer.)
6063  */
6064 mblk_t *
6065 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6066 {
6067 	mblk_t	*mp;
6068 
6069 	mp = allocb(len, BPRI_MED);
6070 	if (!mp)
6071 		return (NULL);
6072 
6073 	/*
6074 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6075 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6076 	 * that other DLPI are M_PROTO.
6077 	 */
6078 	if (prim == DL_INFO_REQ) {
6079 		mp->b_datap->db_type = M_PCPROTO;
6080 	} else {
6081 		mp->b_datap->db_type = M_PROTO;
6082 	}
6083 
6084 	mp->b_wptr = mp->b_rptr + len;
6085 	bzero(mp->b_rptr, len);
6086 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6087 	return (mp);
6088 }
6089 
6090 /*
6091  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6092  */
6093 mblk_t *
6094 ip_dlnotify_alloc(uint_t notification, uint_t data)
6095 {
6096 	dl_notify_ind_t	*notifyp;
6097 	mblk_t		*mp;
6098 
6099 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6100 		return (NULL);
6101 
6102 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6103 	notifyp->dl_notification = notification;
6104 	notifyp->dl_data = data;
6105 	return (mp);
6106 }
6107 
6108 /*
6109  * Debug formatting routine.  Returns a character string representation of the
6110  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6111  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6112  *
6113  * Once the ndd table-printing interfaces are removed, this can be changed to
6114  * standard dotted-decimal form.
6115  */
6116 char *
6117 ip_dot_addr(ipaddr_t addr, char *buf)
6118 {
6119 	uint8_t *ap = (uint8_t *)&addr;
6120 
6121 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6122 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6123 	return (buf);
6124 }
6125 
6126 /*
6127  * Write the given MAC address as a printable string in the usual colon-
6128  * separated format.
6129  */
6130 const char *
6131 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6132 {
6133 	char *bp;
6134 
6135 	if (alen == 0 || buflen < 4)
6136 		return ("?");
6137 	bp = buf;
6138 	for (;;) {
6139 		/*
6140 		 * If there are more MAC address bytes available, but we won't
6141 		 * have any room to print them, then add "..." to the string
6142 		 * instead.  See below for the 'magic number' explanation.
6143 		 */
6144 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6145 			(void) strcpy(bp, "...");
6146 			break;
6147 		}
6148 		(void) sprintf(bp, "%02x", *addr++);
6149 		bp += 2;
6150 		if (--alen == 0)
6151 			break;
6152 		*bp++ = ':';
6153 		buflen -= 3;
6154 		/*
6155 		 * At this point, based on the first 'if' statement above,
6156 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6157 		 * buflen >= 4.  The first case leaves room for the final "xx"
6158 		 * number and trailing NUL byte.  The second leaves room for at
6159 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6160 		 * that statement.
6161 		 */
6162 	}
6163 	return (buf);
6164 }
6165 
6166 /*
6167  * Send an ICMP error after patching up the packet appropriately.  Returns
6168  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6169  */
6170 static boolean_t
6171 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6172     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6173     zoneid_t zoneid, ip_stack_t *ipst)
6174 {
6175 	ipha_t *ipha;
6176 	mblk_t *first_mp;
6177 	boolean_t secure;
6178 	unsigned char db_type;
6179 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6180 
6181 	first_mp = mp;
6182 	if (mctl_present) {
6183 		mp = mp->b_cont;
6184 		secure = ipsec_in_is_secure(first_mp);
6185 		ASSERT(mp != NULL);
6186 	} else {
6187 		/*
6188 		 * If this is an ICMP error being reported - which goes
6189 		 * up as M_CTLs, we need to convert them to M_DATA till
6190 		 * we finish checking with global policy because
6191 		 * ipsec_check_global_policy() assumes M_DATA as clear
6192 		 * and M_CTL as secure.
6193 		 */
6194 		db_type = DB_TYPE(mp);
6195 		DB_TYPE(mp) = M_DATA;
6196 		secure = B_FALSE;
6197 	}
6198 	/*
6199 	 * We are generating an icmp error for some inbound packet.
6200 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6201 	 * Before we generate an error, check with global policy
6202 	 * to see whether this is allowed to enter the system. As
6203 	 * there is no "conn", we are checking with global policy.
6204 	 */
6205 	ipha = (ipha_t *)mp->b_rptr;
6206 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6207 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6208 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6209 		if (first_mp == NULL)
6210 			return (B_FALSE);
6211 	}
6212 
6213 	if (!mctl_present)
6214 		DB_TYPE(mp) = db_type;
6215 
6216 	if (flags & IP_FF_SEND_ICMP) {
6217 		if (flags & IP_FF_HDR_COMPLETE) {
6218 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6219 				freemsg(first_mp);
6220 				return (B_TRUE);
6221 			}
6222 		}
6223 		if (flags & IP_FF_CKSUM) {
6224 			/*
6225 			 * Have to correct checksum since
6226 			 * the packet might have been
6227 			 * fragmented and the reassembly code in ip_rput
6228 			 * does not restore the IP checksum.
6229 			 */
6230 			ipha->ipha_hdr_checksum = 0;
6231 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6232 		}
6233 		switch (icmp_type) {
6234 		case ICMP_DEST_UNREACHABLE:
6235 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6236 			    ipst);
6237 			break;
6238 		default:
6239 			freemsg(first_mp);
6240 			break;
6241 		}
6242 	} else {
6243 		freemsg(first_mp);
6244 		return (B_FALSE);
6245 	}
6246 
6247 	return (B_TRUE);
6248 }
6249 
6250 /*
6251  * Used to send an ICMP error message when a packet is received for
6252  * a protocol that is not supported. The mblk passed as argument
6253  * is consumed by this function.
6254  */
6255 void
6256 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6257     ip_stack_t *ipst)
6258 {
6259 	mblk_t *mp;
6260 	ipha_t *ipha;
6261 	ill_t *ill;
6262 	ipsec_in_t *ii;
6263 
6264 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6265 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6266 
6267 	mp = ipsec_mp->b_cont;
6268 	ipsec_mp->b_cont = NULL;
6269 	ipha = (ipha_t *)mp->b_rptr;
6270 	/* Get ill from index in ipsec_in_t. */
6271 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6272 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6273 	    ipst);
6274 	if (ill != NULL) {
6275 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6276 			if (ip_fanout_send_icmp(q, mp, flags,
6277 			    ICMP_DEST_UNREACHABLE,
6278 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6279 				BUMP_MIB(ill->ill_ip_mib,
6280 				    ipIfStatsInUnknownProtos);
6281 			}
6282 		} else {
6283 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6284 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6285 			    0, B_FALSE, zoneid, ipst)) {
6286 				BUMP_MIB(ill->ill_ip_mib,
6287 				    ipIfStatsInUnknownProtos);
6288 			}
6289 		}
6290 		ill_refrele(ill);
6291 	} else { /* re-link for the freemsg() below. */
6292 		ipsec_mp->b_cont = mp;
6293 	}
6294 
6295 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6296 	freemsg(ipsec_mp);
6297 }
6298 
6299 /*
6300  * See if the inbound datagram has had IPsec processing applied to it.
6301  */
6302 boolean_t
6303 ipsec_in_is_secure(mblk_t *ipsec_mp)
6304 {
6305 	ipsec_in_t *ii;
6306 
6307 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6308 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6309 
6310 	if (ii->ipsec_in_loopback) {
6311 		return (ii->ipsec_in_secure);
6312 	} else {
6313 		return (ii->ipsec_in_ah_sa != NULL ||
6314 		    ii->ipsec_in_esp_sa != NULL ||
6315 		    ii->ipsec_in_decaps);
6316 	}
6317 }
6318 
6319 /*
6320  * Handle protocols with which IP is less intimate.  There
6321  * can be more than one stream bound to a particular
6322  * protocol.  When this is the case, normally each one gets a copy
6323  * of any incoming packets.
6324  *
6325  * IPsec NOTE :
6326  *
6327  * Don't allow a secure packet going up a non-secure connection.
6328  * We don't allow this because
6329  *
6330  * 1) Reply might go out in clear which will be dropped at
6331  *    the sending side.
6332  * 2) If the reply goes out in clear it will give the
6333  *    adversary enough information for getting the key in
6334  *    most of the cases.
6335  *
6336  * Moreover getting a secure packet when we expect clear
6337  * implies that SA's were added without checking for
6338  * policy on both ends. This should not happen once ISAKMP
6339  * is used to negotiate SAs as SAs will be added only after
6340  * verifying the policy.
6341  *
6342  * IPQoS Notes:
6343  * Once we have determined the client, invoke IPPF processing.
6344  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6345  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6346  * ip_policy will be false.
6347  *
6348  * Zones notes:
6349  * Currently only applications in the global zone can create raw sockets for
6350  * protocols other than ICMP. So unlike the broadcast / multicast case of
6351  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6352  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6353  */
6354 static void
6355 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6356     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6357     zoneid_t zoneid)
6358 {
6359 	queue_t	*rq;
6360 	mblk_t	*mp1, *first_mp1;
6361 	uint_t	protocol = ipha->ipha_protocol;
6362 	ipaddr_t dst;
6363 	mblk_t *first_mp = mp;
6364 	boolean_t secure;
6365 	uint32_t ill_index;
6366 	conn_t	*connp, *first_connp, *next_connp;
6367 	connf_t	*connfp;
6368 	boolean_t shared_addr;
6369 	mib2_ipIfStatsEntry_t *mibptr;
6370 	ip_stack_t *ipst = recv_ill->ill_ipst;
6371 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6372 
6373 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6374 	if (mctl_present) {
6375 		mp = first_mp->b_cont;
6376 		secure = ipsec_in_is_secure(first_mp);
6377 		ASSERT(mp != NULL);
6378 	} else {
6379 		secure = B_FALSE;
6380 	}
6381 	dst = ipha->ipha_dst;
6382 	shared_addr = (zoneid == ALL_ZONES);
6383 	if (shared_addr) {
6384 		/*
6385 		 * We don't allow multilevel ports for raw IP, so no need to
6386 		 * check for that here.
6387 		 */
6388 		zoneid = tsol_packet_to_zoneid(mp);
6389 	}
6390 
6391 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6392 	mutex_enter(&connfp->connf_lock);
6393 	connp = connfp->connf_head;
6394 	for (connp = connfp->connf_head; connp != NULL;
6395 	    connp = connp->conn_next) {
6396 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6397 		    zoneid) &&
6398 		    (!is_system_labeled() ||
6399 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6400 		    connp))) {
6401 			break;
6402 		}
6403 	}
6404 
6405 	if (connp == NULL) {
6406 		/*
6407 		 * No one bound to these addresses.  Is
6408 		 * there a client that wants all
6409 		 * unclaimed datagrams?
6410 		 */
6411 		mutex_exit(&connfp->connf_lock);
6412 		/*
6413 		 * Check for IPPROTO_ENCAP...
6414 		 */
6415 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6416 			/*
6417 			 * If an IPsec mblk is here on a multicast
6418 			 * tunnel (using ip_mroute stuff), check policy here,
6419 			 * THEN ship off to ip_mroute_decap().
6420 			 *
6421 			 * BTW,  If I match a configured IP-in-IP
6422 			 * tunnel, this path will not be reached, and
6423 			 * ip_mroute_decap will never be called.
6424 			 */
6425 			first_mp = ipsec_check_global_policy(first_mp, connp,
6426 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6427 			if (first_mp != NULL) {
6428 				if (mctl_present)
6429 					freeb(first_mp);
6430 				ip_mroute_decap(q, mp, ill);
6431 			} /* Else we already freed everything! */
6432 		} else {
6433 			/*
6434 			 * Otherwise send an ICMP protocol unreachable.
6435 			 */
6436 			if (ip_fanout_send_icmp(q, first_mp, flags,
6437 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6438 			    mctl_present, zoneid, ipst)) {
6439 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6440 			}
6441 		}
6442 		return;
6443 	}
6444 
6445 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6446 
6447 	CONN_INC_REF(connp);
6448 	first_connp = connp;
6449 	connp = connp->conn_next;
6450 
6451 	for (;;) {
6452 		while (connp != NULL) {
6453 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6454 			    flags, zoneid) &&
6455 			    (!is_system_labeled() ||
6456 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6457 			    shared_addr, connp)))
6458 				break;
6459 			connp = connp->conn_next;
6460 		}
6461 
6462 		/*
6463 		 * Copy the packet.
6464 		 */
6465 		if (connp == NULL ||
6466 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6467 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6468 			/*
6469 			 * No more interested clients or memory
6470 			 * allocation failed
6471 			 */
6472 			connp = first_connp;
6473 			break;
6474 		}
6475 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6476 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6477 		CONN_INC_REF(connp);
6478 		mutex_exit(&connfp->connf_lock);
6479 		rq = connp->conn_rq;
6480 
6481 		/*
6482 		 * Check flow control
6483 		 */
6484 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6485 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6486 			if (flags & IP_FF_RAWIP) {
6487 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6488 			} else {
6489 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6490 			}
6491 
6492 			freemsg(first_mp1);
6493 		} else {
6494 			/*
6495 			 * Enforce policy like any other conn_t.  Note that
6496 			 * IP-in-IP packets don't come through here, but
6497 			 * through ip_iptun_input() or
6498 			 * icmp_inbound_iptun_fanout().  IPsec policy for such
6499 			 * packets is enforced in the iptun module.
6500 			 */
6501 			if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6502 			    secure) {
6503 				first_mp1 = ipsec_check_inbound_policy
6504 				    (first_mp1, connp, ipha, NULL,
6505 				    mctl_present);
6506 			}
6507 			if (first_mp1 != NULL) {
6508 				int in_flags = 0;
6509 				/*
6510 				 * ip_fanout_proto also gets called from
6511 				 * icmp_inbound_error_fanout, in which case
6512 				 * the msg type is M_CTL.  Don't add info
6513 				 * in this case for the time being. In future
6514 				 * when there is a need for knowing the
6515 				 * inbound iface index for ICMP error msgs,
6516 				 * then this can be changed.
6517 				 */
6518 				if (connp->conn_recvif)
6519 					in_flags = IPF_RECVIF;
6520 				/*
6521 				 * The ULP may support IP_RECVPKTINFO for both
6522 				 * IP v4 and v6 so pass the appropriate argument
6523 				 * based on conn IP version.
6524 				 */
6525 				if (connp->conn_ip_recvpktinfo) {
6526 					if (connp->conn_af_isv6) {
6527 						/*
6528 						 * V6 only needs index
6529 						 */
6530 						in_flags |= IPF_RECVIF;
6531 					} else {
6532 						/*
6533 						 * V4 needs index +
6534 						 * matching address.
6535 						 */
6536 						in_flags |= IPF_RECVADDR;
6537 					}
6538 				}
6539 				if ((in_flags != 0) &&
6540 				    (mp->b_datap->db_type != M_CTL)) {
6541 					/*
6542 					 * the actual data will be
6543 					 * contained in b_cont upon
6544 					 * successful return of the
6545 					 * following call else
6546 					 * original mblk is returned
6547 					 */
6548 					ASSERT(recv_ill != NULL);
6549 					mp1 = ip_add_info(mp1, recv_ill,
6550 					    in_flags, IPCL_ZONEID(connp), ipst);
6551 				}
6552 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6553 				if (mctl_present)
6554 					freeb(first_mp1);
6555 				(connp->conn_recv)(connp, mp1, NULL);
6556 			}
6557 		}
6558 		mutex_enter(&connfp->connf_lock);
6559 		/* Follow the next pointer before releasing the conn. */
6560 		next_connp = connp->conn_next;
6561 		CONN_DEC_REF(connp);
6562 		connp = next_connp;
6563 	}
6564 
6565 	/* Last one.  Send it upstream. */
6566 	mutex_exit(&connfp->connf_lock);
6567 
6568 	/*
6569 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6570 	 * will be set to false.
6571 	 */
6572 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6573 		ill_index = ill->ill_phyint->phyint_ifindex;
6574 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6575 		if (mp == NULL) {
6576 			CONN_DEC_REF(connp);
6577 			if (mctl_present) {
6578 				freeb(first_mp);
6579 			}
6580 			return;
6581 		}
6582 	}
6583 
6584 	rq = connp->conn_rq;
6585 	/*
6586 	 * Check flow control
6587 	 */
6588 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6589 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6590 		if (flags & IP_FF_RAWIP) {
6591 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6592 		} else {
6593 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6594 		}
6595 
6596 		freemsg(first_mp);
6597 	} else {
6598 		ASSERT(!IPCL_IS_IPTUN(connp));
6599 
6600 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6601 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6602 			    ipha, NULL, mctl_present);
6603 		}
6604 
6605 		if (first_mp != NULL) {
6606 			int in_flags = 0;
6607 
6608 			/*
6609 			 * ip_fanout_proto also gets called
6610 			 * from icmp_inbound_error_fanout, in
6611 			 * which case the msg type is M_CTL.
6612 			 * Don't add info in this case for time
6613 			 * being. In future when there is a
6614 			 * need for knowing the inbound iface
6615 			 * index for ICMP error msgs, then this
6616 			 * can be changed
6617 			 */
6618 			if (connp->conn_recvif)
6619 				in_flags = IPF_RECVIF;
6620 			if (connp->conn_ip_recvpktinfo) {
6621 				if (connp->conn_af_isv6) {
6622 					/*
6623 					 * V6 only needs index
6624 					 */
6625 					in_flags |= IPF_RECVIF;
6626 				} else {
6627 					/*
6628 					 * V4 needs index +
6629 					 * matching address.
6630 					 */
6631 					in_flags |= IPF_RECVADDR;
6632 				}
6633 			}
6634 			if ((in_flags != 0) &&
6635 			    (mp->b_datap->db_type != M_CTL)) {
6636 
6637 				/*
6638 				 * the actual data will be contained in
6639 				 * b_cont upon successful return
6640 				 * of the following call else original
6641 				 * mblk is returned
6642 				 */
6643 				ASSERT(recv_ill != NULL);
6644 				mp = ip_add_info(mp, recv_ill,
6645 				    in_flags, IPCL_ZONEID(connp), ipst);
6646 			}
6647 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6648 			(connp->conn_recv)(connp, mp, NULL);
6649 			if (mctl_present)
6650 				freeb(first_mp);
6651 		}
6652 	}
6653 	CONN_DEC_REF(connp);
6654 }
6655 
6656 /*
6657  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6658  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6659  * the correct squeue, in this case the same squeue as a valid listener with
6660  * no current connection state for the packet we are processing. The function
6661  * is called for synchronizing both IPv4 and IPv6.
6662  */
6663 void
6664 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6665     tcp_stack_t *tcps, conn_t *connp)
6666 {
6667 	mblk_t *rst_mp;
6668 	tcp_xmit_reset_event_t *eventp;
6669 
6670 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6671 
6672 	if (rst_mp == NULL) {
6673 		freemsg(mp);
6674 		return;
6675 	}
6676 
6677 	rst_mp->b_datap->db_type = M_PROTO;
6678 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6679 
6680 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6681 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6682 	eventp->tcp_xre_iphdrlen = hdrlen;
6683 	eventp->tcp_xre_zoneid = zoneid;
6684 	eventp->tcp_xre_tcps = tcps;
6685 
6686 	rst_mp->b_cont = mp;
6687 	mp = rst_mp;
6688 
6689 	/*
6690 	 * Increment the connref, this ref will be released by the squeue
6691 	 * framework.
6692 	 */
6693 	CONN_INC_REF(connp);
6694 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6695 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6696 }
6697 
6698 /*
6699  * Fanout for TCP packets
6700  * The caller puts <fport, lport> in the ports parameter.
6701  *
6702  * IPQoS Notes
6703  * Before sending it to the client, invoke IPPF processing.
6704  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6705  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6706  * ip_policy is false.
6707  */
6708 static void
6709 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6710     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6711 {
6712 	mblk_t  *first_mp;
6713 	boolean_t secure;
6714 	uint32_t ill_index;
6715 	int	ip_hdr_len;
6716 	tcph_t	*tcph;
6717 	boolean_t syn_present = B_FALSE;
6718 	conn_t	*connp;
6719 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6720 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6721 
6722 	ASSERT(recv_ill != NULL);
6723 
6724 	first_mp = mp;
6725 	if (mctl_present) {
6726 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6727 		mp = first_mp->b_cont;
6728 		secure = ipsec_in_is_secure(first_mp);
6729 		ASSERT(mp != NULL);
6730 	} else {
6731 		secure = B_FALSE;
6732 	}
6733 
6734 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6735 
6736 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6737 	    zoneid, ipst)) == NULL) {
6738 		/*
6739 		 * No connected connection or listener. Send a
6740 		 * TH_RST via tcp_xmit_listeners_reset.
6741 		 */
6742 
6743 		/* Initiate IPPf processing, if needed. */
6744 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6745 			uint32_t ill_index;
6746 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6747 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6748 			if (first_mp == NULL)
6749 				return;
6750 		}
6751 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6752 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6753 		    zoneid));
6754 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6755 		    ipst->ips_netstack->netstack_tcp, NULL);
6756 		return;
6757 	}
6758 
6759 	/*
6760 	 * Allocate the SYN for the TCP connection here itself
6761 	 */
6762 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6763 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6764 		if (IPCL_IS_TCP(connp)) {
6765 			squeue_t *sqp;
6766 
6767 			/*
6768 			 * If the queue belongs to a conn, and fused tcp
6769 			 * loopback is enabled, assign the eager's squeue
6770 			 * to be that of the active connect's. Note that
6771 			 * we don't check for IP_FF_LOOPBACK here since this
6772 			 * routine gets called only for loopback (unlike the
6773 			 * IPv6 counterpart).
6774 			 */
6775 			if (do_tcp_fusion &&
6776 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6777 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6778 			    !secure &&
6779 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6780 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6781 				sqp = Q_TO_CONN(q)->conn_sqp;
6782 			} else {
6783 				sqp = IP_SQUEUE_GET(lbolt);
6784 			}
6785 
6786 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6787 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6788 			syn_present = B_TRUE;
6789 		}
6790 	}
6791 
6792 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6793 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6794 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6795 		if ((flags & TH_RST) || (flags & TH_URG)) {
6796 			CONN_DEC_REF(connp);
6797 			freemsg(first_mp);
6798 			return;
6799 		}
6800 		if (flags & TH_ACK) {
6801 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6802 			    ipst->ips_netstack->netstack_tcp, connp);
6803 			CONN_DEC_REF(connp);
6804 			return;
6805 		}
6806 
6807 		CONN_DEC_REF(connp);
6808 		freemsg(first_mp);
6809 		return;
6810 	}
6811 
6812 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6813 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6814 		    NULL, mctl_present);
6815 		if (first_mp == NULL) {
6816 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6817 			CONN_DEC_REF(connp);
6818 			return;
6819 		}
6820 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6821 			ASSERT(syn_present);
6822 			if (mctl_present) {
6823 				ASSERT(first_mp != mp);
6824 				first_mp->b_datap->db_struioflag |=
6825 				    STRUIO_POLICY;
6826 			} else {
6827 				ASSERT(first_mp == mp);
6828 				mp->b_datap->db_struioflag &=
6829 				    ~STRUIO_EAGER;
6830 				mp->b_datap->db_struioflag |=
6831 				    STRUIO_POLICY;
6832 			}
6833 		} else {
6834 			/*
6835 			 * Discard first_mp early since we're dealing with a
6836 			 * fully-connected conn_t and tcp doesn't do policy in
6837 			 * this case.
6838 			 */
6839 			if (mctl_present) {
6840 				freeb(first_mp);
6841 				mctl_present = B_FALSE;
6842 			}
6843 			first_mp = mp;
6844 		}
6845 	}
6846 
6847 	/*
6848 	 * Initiate policy processing here if needed. If we get here from
6849 	 * icmp_inbound_error_fanout, ip_policy is false.
6850 	 */
6851 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6852 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6853 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6854 		if (mp == NULL) {
6855 			CONN_DEC_REF(connp);
6856 			if (mctl_present)
6857 				freeb(first_mp);
6858 			return;
6859 		} else if (mctl_present) {
6860 			ASSERT(first_mp != mp);
6861 			first_mp->b_cont = mp;
6862 		} else {
6863 			first_mp = mp;
6864 		}
6865 	}
6866 
6867 	/* Handle socket options. */
6868 	if (!syn_present &&
6869 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6870 		/* Add header */
6871 		ASSERT(recv_ill != NULL);
6872 		/*
6873 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6874 		 * IPF_RECVIF.
6875 		 */
6876 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6877 		    ipst);
6878 		if (mp == NULL) {
6879 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6880 			CONN_DEC_REF(connp);
6881 			if (mctl_present)
6882 				freeb(first_mp);
6883 			return;
6884 		} else if (mctl_present) {
6885 			/*
6886 			 * ip_add_info might return a new mp.
6887 			 */
6888 			ASSERT(first_mp != mp);
6889 			first_mp->b_cont = mp;
6890 		} else {
6891 			first_mp = mp;
6892 		}
6893 	}
6894 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6895 	if (IPCL_IS_TCP(connp)) {
6896 		/* do not drain, certain use cases can blow the stack */
6897 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6898 		    connp, SQ_NODRAIN, SQTAG_IP_FANOUT_TCP);
6899 	} else {
6900 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6901 		(connp->conn_recv)(connp, first_mp, NULL);
6902 		CONN_DEC_REF(connp);
6903 	}
6904 }
6905 
6906 /*
6907  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6908  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6909  * is not consumed.
6910  *
6911  * One of four things can happen, all of which affect the passed-in mblk:
6912  *
6913  * 1.) ICMP messages that go through here just get returned TRUE.
6914  *
6915  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6916  *
6917  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6918  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6919  *
6920  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6921  */
6922 static boolean_t
6923 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6924     ipsec_stack_t *ipss)
6925 {
6926 	int shift, plen, iph_len;
6927 	ipha_t *ipha;
6928 	udpha_t *udpha;
6929 	uint32_t *spi;
6930 	uint32_t esp_ports;
6931 	uint8_t *orptr;
6932 	boolean_t free_ire;
6933 
6934 	if (DB_TYPE(mp) == M_CTL) {
6935 		/*
6936 		 * ICMP message with UDP inside.  Don't bother stripping, just
6937 		 * send it up.
6938 		 *
6939 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6940 		 * to ignore errors set by ICMP anyway ('cause they might be
6941 		 * forged), but that's the app's decision, not ours.
6942 		 */
6943 
6944 		/* Bunch of reality checks for DEBUG kernels... */
6945 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6946 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6947 
6948 		return (B_TRUE);
6949 	}
6950 
6951 	ipha = (ipha_t *)mp->b_rptr;
6952 	iph_len = IPH_HDR_LENGTH(ipha);
6953 	plen = ntohs(ipha->ipha_length);
6954 
6955 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6956 		/*
6957 		 * Most likely a keepalive for the benefit of an intervening
6958 		 * NAT.  These aren't for us, per se, so drop it.
6959 		 *
6960 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6961 		 * byte packets (keepalives are 1-byte), but we'll drop them
6962 		 * also.
6963 		 */
6964 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6965 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6966 		return (B_FALSE);
6967 	}
6968 
6969 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6970 		/* might as well pull it all up - it might be ESP. */
6971 		if (!pullupmsg(mp, -1)) {
6972 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6973 			    DROPPER(ipss, ipds_esp_nomem),
6974 			    &ipss->ipsec_dropper);
6975 			return (B_FALSE);
6976 		}
6977 
6978 		ipha = (ipha_t *)mp->b_rptr;
6979 	}
6980 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6981 	if (*spi == 0) {
6982 		/* UDP packet - remove 0-spi. */
6983 		shift = sizeof (uint32_t);
6984 	} else {
6985 		/* ESP-in-UDP packet - reduce to ESP. */
6986 		ipha->ipha_protocol = IPPROTO_ESP;
6987 		shift = sizeof (udpha_t);
6988 	}
6989 
6990 	/* Fix IP header */
6991 	ipha->ipha_length = htons(plen - shift);
6992 	ipha->ipha_hdr_checksum = 0;
6993 
6994 	orptr = mp->b_rptr;
6995 	mp->b_rptr += shift;
6996 
6997 	udpha = (udpha_t *)(orptr + iph_len);
6998 	if (*spi == 0) {
6999 		ASSERT((uint8_t *)ipha == orptr);
7000 		udpha->uha_length = htons(plen - shift - iph_len);
7001 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7002 		esp_ports = 0;
7003 	} else {
7004 		esp_ports = *((uint32_t *)udpha);
7005 		ASSERT(esp_ports != 0);
7006 	}
7007 	ovbcopy(orptr, orptr + shift, iph_len);
7008 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7009 		ipha = (ipha_t *)(orptr + shift);
7010 
7011 		free_ire = (ire == NULL);
7012 		if (free_ire) {
7013 			/* Re-acquire ire. */
7014 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7015 			    ipss->ipsec_netstack->netstack_ip);
7016 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7017 				if (ire != NULL)
7018 					ire_refrele(ire);
7019 				/*
7020 				 * Do a regular freemsg(), as this is an IP
7021 				 * error (no local route) not an IPsec one.
7022 				 */
7023 				freemsg(mp);
7024 			}
7025 		}
7026 
7027 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7028 		if (free_ire)
7029 			ire_refrele(ire);
7030 	}
7031 
7032 	return (esp_ports == 0);
7033 }
7034 
7035 /*
7036  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7037  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7038  * Caller is responsible for dropping references to the conn, and freeing
7039  * first_mp.
7040  *
7041  * IPQoS Notes
7042  * Before sending it to the client, invoke IPPF processing. Policy processing
7043  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7044  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7045  * ip_wput_local, ip_policy is false.
7046  */
7047 static void
7048 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7049     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7050     boolean_t ip_policy)
7051 {
7052 	boolean_t	mctl_present = (first_mp != NULL);
7053 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7054 	uint32_t	ill_index;
7055 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7056 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7057 
7058 	ASSERT(ill != NULL);
7059 
7060 	if (mctl_present)
7061 		first_mp->b_cont = mp;
7062 	else
7063 		first_mp = mp;
7064 
7065 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7066 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7067 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7068 		freemsg(first_mp);
7069 		return;
7070 	}
7071 
7072 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7073 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7074 		    NULL, mctl_present);
7075 		/* Freed by ipsec_check_inbound_policy(). */
7076 		if (first_mp == NULL) {
7077 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7078 			return;
7079 		}
7080 	}
7081 	if (mctl_present)
7082 		freeb(first_mp);
7083 
7084 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7085 	if (connp->conn_udp->udp_nat_t_endpoint) {
7086 		if (mctl_present) {
7087 			/* mctl_present *shouldn't* happen. */
7088 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7089 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7090 			    &ipss->ipsec_dropper);
7091 			return;
7092 		}
7093 
7094 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7095 			return;
7096 	}
7097 
7098 	/* Handle options. */
7099 	if (connp->conn_recvif)
7100 		in_flags = IPF_RECVIF;
7101 	/*
7102 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7103 	 * passed to ip_add_info is based on IP version of connp.
7104 	 */
7105 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7106 		if (connp->conn_af_isv6) {
7107 			/*
7108 			 * V6 only needs index
7109 			 */
7110 			in_flags |= IPF_RECVIF;
7111 		} else {
7112 			/*
7113 			 * V4 needs index + matching address.
7114 			 */
7115 			in_flags |= IPF_RECVADDR;
7116 		}
7117 	}
7118 
7119 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7120 		in_flags |= IPF_RECVSLLA;
7121 
7122 	/*
7123 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7124 	 * freed if the packet is dropped. The caller will do so.
7125 	 */
7126 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7127 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7128 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7129 		if (mp == NULL) {
7130 			return;
7131 		}
7132 	}
7133 	if ((in_flags != 0) &&
7134 	    (mp->b_datap->db_type != M_CTL)) {
7135 		/*
7136 		 * The actual data will be contained in b_cont
7137 		 * upon successful return of the following call
7138 		 * else original mblk is returned
7139 		 */
7140 		ASSERT(recv_ill != NULL);
7141 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7142 		    ipst);
7143 	}
7144 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7145 	/* Send it upstream */
7146 	(connp->conn_recv)(connp, mp, NULL);
7147 }
7148 
7149 /*
7150  * Fanout for UDP packets.
7151  * The caller puts <fport, lport> in the ports parameter.
7152  *
7153  * If SO_REUSEADDR is set all multicast and broadcast packets
7154  * will be delivered to all streams bound to the same port.
7155  *
7156  * Zones notes:
7157  * Multicast and broadcast packets will be distributed to streams in all zones.
7158  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7159  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7160  * packets. To maintain this behavior with multiple zones, the conns are grouped
7161  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7162  * each zone. If unset, all the following conns in the same zone are skipped.
7163  */
7164 static void
7165 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7166     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7167     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7168 {
7169 	uint32_t	dstport, srcport;
7170 	ipaddr_t	dst;
7171 	mblk_t		*first_mp;
7172 	boolean_t	secure;
7173 	in6_addr_t	v6src;
7174 	conn_t		*connp;
7175 	connf_t		*connfp;
7176 	conn_t		*first_connp;
7177 	conn_t		*next_connp;
7178 	mblk_t		*mp1, *first_mp1;
7179 	ipaddr_t	src;
7180 	zoneid_t	last_zoneid;
7181 	boolean_t	reuseaddr;
7182 	boolean_t	shared_addr;
7183 	boolean_t	unlabeled;
7184 	ip_stack_t	*ipst;
7185 
7186 	ASSERT(recv_ill != NULL);
7187 	ipst = recv_ill->ill_ipst;
7188 
7189 	first_mp = mp;
7190 	if (mctl_present) {
7191 		mp = first_mp->b_cont;
7192 		first_mp->b_cont = NULL;
7193 		secure = ipsec_in_is_secure(first_mp);
7194 		ASSERT(mp != NULL);
7195 	} else {
7196 		first_mp = NULL;
7197 		secure = B_FALSE;
7198 	}
7199 
7200 	/* Extract ports in net byte order */
7201 	dstport = htons(ntohl(ports) & 0xFFFF);
7202 	srcport = htons(ntohl(ports) >> 16);
7203 	dst = ipha->ipha_dst;
7204 	src = ipha->ipha_src;
7205 
7206 	unlabeled = B_FALSE;
7207 	if (is_system_labeled())
7208 		/* Cred cannot be null on IPv4 */
7209 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7210 		    TSLF_UNLABELED) != 0;
7211 	shared_addr = (zoneid == ALL_ZONES);
7212 	if (shared_addr) {
7213 		/*
7214 		 * No need to handle exclusive-stack zones since ALL_ZONES
7215 		 * only applies to the shared stack.
7216 		 */
7217 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7218 		/*
7219 		 * If no shared MLP is found, tsol_mlp_findzone returns
7220 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7221 		 * search for the zone based on the packet label.
7222 		 *
7223 		 * If there is such a zone, we prefer to find a
7224 		 * connection in it.  Otherwise, we look for a
7225 		 * MAC-exempt connection in any zone whose label
7226 		 * dominates the default label on the packet.
7227 		 */
7228 		if (zoneid == ALL_ZONES)
7229 			zoneid = tsol_packet_to_zoneid(mp);
7230 		else
7231 			unlabeled = B_FALSE;
7232 	}
7233 
7234 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7235 	mutex_enter(&connfp->connf_lock);
7236 	connp = connfp->connf_head;
7237 	if (!broadcast && !CLASSD(dst)) {
7238 		/*
7239 		 * Not broadcast or multicast. Send to the one (first)
7240 		 * client we find. No need to check conn_wantpacket()
7241 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7242 		 * IPv4 unicast packets.
7243 		 */
7244 		while ((connp != NULL) &&
7245 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7246 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7247 		    !(unlabeled && connp->conn_mac_exempt && shared_addr)))) {
7248 			/*
7249 			 * We keep searching since the conn did not match,
7250 			 * or its zone did not match and it is not either
7251 			 * an allzones conn or a mac exempt conn (if the
7252 			 * sender is unlabeled.)
7253 			 */
7254 			connp = connp->conn_next;
7255 		}
7256 
7257 		if (connp == NULL ||
7258 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7259 			goto notfound;
7260 
7261 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7262 
7263 		if (is_system_labeled() &&
7264 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7265 		    connp))
7266 			goto notfound;
7267 
7268 		CONN_INC_REF(connp);
7269 		mutex_exit(&connfp->connf_lock);
7270 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7271 		    flags, recv_ill, ip_policy);
7272 		IP_STAT(ipst, ip_udp_fannorm);
7273 		CONN_DEC_REF(connp);
7274 		return;
7275 	}
7276 
7277 	/*
7278 	 * Broadcast and multicast case
7279 	 *
7280 	 * Need to check conn_wantpacket().
7281 	 * If SO_REUSEADDR has been set on the first we send the
7282 	 * packet to all clients that have joined the group and
7283 	 * match the port.
7284 	 */
7285 
7286 	while (connp != NULL) {
7287 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7288 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7289 		    (!is_system_labeled() ||
7290 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7291 		    connp)))
7292 			break;
7293 		connp = connp->conn_next;
7294 	}
7295 
7296 	if (connp == NULL ||
7297 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7298 		goto notfound;
7299 
7300 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7301 
7302 	first_connp = connp;
7303 	/*
7304 	 * When SO_REUSEADDR is not set, send the packet only to the first
7305 	 * matching connection in its zone by keeping track of the zoneid.
7306 	 */
7307 	reuseaddr = first_connp->conn_reuseaddr;
7308 	last_zoneid = first_connp->conn_zoneid;
7309 
7310 	CONN_INC_REF(connp);
7311 	connp = connp->conn_next;
7312 	for (;;) {
7313 		while (connp != NULL) {
7314 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7315 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7316 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7317 			    (!is_system_labeled() ||
7318 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7319 			    shared_addr, connp)))
7320 				break;
7321 			connp = connp->conn_next;
7322 		}
7323 		/*
7324 		 * Just copy the data part alone. The mctl part is
7325 		 * needed just for verifying policy and it is never
7326 		 * sent up.
7327 		 */
7328 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7329 		    ((mp1 = copymsg(mp)) == NULL))) {
7330 			/*
7331 			 * No more interested clients or memory
7332 			 * allocation failed
7333 			 */
7334 			connp = first_connp;
7335 			break;
7336 		}
7337 		if (connp->conn_zoneid != last_zoneid) {
7338 			/*
7339 			 * Update the zoneid so that the packet isn't sent to
7340 			 * any more conns in the same zone unless SO_REUSEADDR
7341 			 * is set.
7342 			 */
7343 			reuseaddr = connp->conn_reuseaddr;
7344 			last_zoneid = connp->conn_zoneid;
7345 		}
7346 		if (first_mp != NULL) {
7347 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7348 			    ipsec_info_type == IPSEC_IN);
7349 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7350 			    ipst->ips_netstack);
7351 			if (first_mp1 == NULL) {
7352 				freemsg(mp1);
7353 				connp = first_connp;
7354 				break;
7355 			}
7356 		} else {
7357 			first_mp1 = NULL;
7358 		}
7359 		CONN_INC_REF(connp);
7360 		mutex_exit(&connfp->connf_lock);
7361 		/*
7362 		 * IPQoS notes: We don't send the packet for policy
7363 		 * processing here, will do it for the last one (below).
7364 		 * i.e. we do it per-packet now, but if we do policy
7365 		 * processing per-conn, then we would need to do it
7366 		 * here too.
7367 		 */
7368 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7369 		    ipha, flags, recv_ill, B_FALSE);
7370 		mutex_enter(&connfp->connf_lock);
7371 		/* Follow the next pointer before releasing the conn. */
7372 		next_connp = connp->conn_next;
7373 		IP_STAT(ipst, ip_udp_fanmb);
7374 		CONN_DEC_REF(connp);
7375 		connp = next_connp;
7376 	}
7377 
7378 	/* Last one.  Send it upstream. */
7379 	mutex_exit(&connfp->connf_lock);
7380 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7381 	    recv_ill, ip_policy);
7382 	IP_STAT(ipst, ip_udp_fanmb);
7383 	CONN_DEC_REF(connp);
7384 	return;
7385 
7386 notfound:
7387 
7388 	mutex_exit(&connfp->connf_lock);
7389 	IP_STAT(ipst, ip_udp_fanothers);
7390 	/*
7391 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7392 	 * have already been matched above, since they live in the IPv4
7393 	 * fanout tables. This implies we only need to
7394 	 * check for IPv6 in6addr_any endpoints here.
7395 	 * Thus we compare using ipv6_all_zeros instead of the destination
7396 	 * address, except for the multicast group membership lookup which
7397 	 * uses the IPv4 destination.
7398 	 */
7399 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7400 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7401 	mutex_enter(&connfp->connf_lock);
7402 	connp = connfp->connf_head;
7403 	if (!broadcast && !CLASSD(dst)) {
7404 		while (connp != NULL) {
7405 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7406 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7407 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7408 			    !connp->conn_ipv6_v6only)
7409 				break;
7410 			connp = connp->conn_next;
7411 		}
7412 
7413 		if (connp != NULL && is_system_labeled() &&
7414 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7415 		    connp))
7416 			connp = NULL;
7417 
7418 		if (connp == NULL ||
7419 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7420 			/*
7421 			 * No one bound to this port.  Is
7422 			 * there a client that wants all
7423 			 * unclaimed datagrams?
7424 			 */
7425 			mutex_exit(&connfp->connf_lock);
7426 
7427 			if (mctl_present)
7428 				first_mp->b_cont = mp;
7429 			else
7430 				first_mp = mp;
7431 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7432 			    connf_head != NULL) {
7433 				ip_fanout_proto(q, first_mp, ill, ipha,
7434 				    flags | IP_FF_RAWIP, mctl_present,
7435 				    ip_policy, recv_ill, zoneid);
7436 			} else {
7437 				if (ip_fanout_send_icmp(q, first_mp, flags,
7438 				    ICMP_DEST_UNREACHABLE,
7439 				    ICMP_PORT_UNREACHABLE,
7440 				    mctl_present, zoneid, ipst)) {
7441 					BUMP_MIB(ill->ill_ip_mib,
7442 					    udpIfStatsNoPorts);
7443 				}
7444 			}
7445 			return;
7446 		}
7447 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7448 
7449 		CONN_INC_REF(connp);
7450 		mutex_exit(&connfp->connf_lock);
7451 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7452 		    flags, recv_ill, ip_policy);
7453 		CONN_DEC_REF(connp);
7454 		return;
7455 	}
7456 	/*
7457 	 * IPv4 multicast packet being delivered to an AF_INET6
7458 	 * in6addr_any endpoint.
7459 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7460 	 * and not conn_wantpacket_v6() since any multicast membership is
7461 	 * for an IPv4-mapped multicast address.
7462 	 * The packet is sent to all clients in all zones that have joined the
7463 	 * group and match the port.
7464 	 */
7465 	while (connp != NULL) {
7466 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7467 		    srcport, v6src) &&
7468 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7469 		    (!is_system_labeled() ||
7470 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7471 		    connp)))
7472 			break;
7473 		connp = connp->conn_next;
7474 	}
7475 
7476 	if (connp == NULL ||
7477 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7478 		/*
7479 		 * No one bound to this port.  Is
7480 		 * there a client that wants all
7481 		 * unclaimed datagrams?
7482 		 */
7483 		mutex_exit(&connfp->connf_lock);
7484 
7485 		if (mctl_present)
7486 			first_mp->b_cont = mp;
7487 		else
7488 			first_mp = mp;
7489 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7490 		    NULL) {
7491 			ip_fanout_proto(q, first_mp, ill, ipha,
7492 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7493 			    recv_ill, zoneid);
7494 		} else {
7495 			/*
7496 			 * We used to attempt to send an icmp error here, but
7497 			 * since this is known to be a multicast packet
7498 			 * and we don't send icmp errors in response to
7499 			 * multicast, just drop the packet and give up sooner.
7500 			 */
7501 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7502 			freemsg(first_mp);
7503 		}
7504 		return;
7505 	}
7506 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7507 
7508 	first_connp = connp;
7509 
7510 	CONN_INC_REF(connp);
7511 	connp = connp->conn_next;
7512 	for (;;) {
7513 		while (connp != NULL) {
7514 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7515 			    ipv6_all_zeros, srcport, v6src) &&
7516 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7517 			    (!is_system_labeled() ||
7518 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7519 			    shared_addr, connp)))
7520 				break;
7521 			connp = connp->conn_next;
7522 		}
7523 		/*
7524 		 * Just copy the data part alone. The mctl part is
7525 		 * needed just for verifying policy and it is never
7526 		 * sent up.
7527 		 */
7528 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7529 		    ((mp1 = copymsg(mp)) == NULL))) {
7530 			/*
7531 			 * No more intested clients or memory
7532 			 * allocation failed
7533 			 */
7534 			connp = first_connp;
7535 			break;
7536 		}
7537 		if (first_mp != NULL) {
7538 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7539 			    ipsec_info_type == IPSEC_IN);
7540 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7541 			    ipst->ips_netstack);
7542 			if (first_mp1 == NULL) {
7543 				freemsg(mp1);
7544 				connp = first_connp;
7545 				break;
7546 			}
7547 		} else {
7548 			first_mp1 = NULL;
7549 		}
7550 		CONN_INC_REF(connp);
7551 		mutex_exit(&connfp->connf_lock);
7552 		/*
7553 		 * IPQoS notes: We don't send the packet for policy
7554 		 * processing here, will do it for the last one (below).
7555 		 * i.e. we do it per-packet now, but if we do policy
7556 		 * processing per-conn, then we would need to do it
7557 		 * here too.
7558 		 */
7559 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7560 		    ipha, flags, recv_ill, B_FALSE);
7561 		mutex_enter(&connfp->connf_lock);
7562 		/* Follow the next pointer before releasing the conn. */
7563 		next_connp = connp->conn_next;
7564 		CONN_DEC_REF(connp);
7565 		connp = next_connp;
7566 	}
7567 
7568 	/* Last one.  Send it upstream. */
7569 	mutex_exit(&connfp->connf_lock);
7570 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7571 	    recv_ill, ip_policy);
7572 	CONN_DEC_REF(connp);
7573 }
7574 
7575 /*
7576  * Complete the ip_wput header so that it
7577  * is possible to generate ICMP
7578  * errors.
7579  */
7580 int
7581 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7582 {
7583 	ire_t *ire;
7584 
7585 	if (ipha->ipha_src == INADDR_ANY) {
7586 		ire = ire_lookup_local(zoneid, ipst);
7587 		if (ire == NULL) {
7588 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7589 			return (1);
7590 		}
7591 		ipha->ipha_src = ire->ire_addr;
7592 		ire_refrele(ire);
7593 	}
7594 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7595 	ipha->ipha_hdr_checksum = 0;
7596 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7597 	return (0);
7598 }
7599 
7600 /*
7601  * Nobody should be sending
7602  * packets up this stream
7603  */
7604 static void
7605 ip_lrput(queue_t *q, mblk_t *mp)
7606 {
7607 	mblk_t *mp1;
7608 
7609 	switch (mp->b_datap->db_type) {
7610 	case M_FLUSH:
7611 		/* Turn around */
7612 		if (*mp->b_rptr & FLUSHW) {
7613 			*mp->b_rptr &= ~FLUSHR;
7614 			qreply(q, mp);
7615 			return;
7616 		}
7617 		break;
7618 	}
7619 	/* Could receive messages that passed through ar_rput */
7620 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7621 		mp1->b_prev = mp1->b_next = NULL;
7622 	freemsg(mp);
7623 }
7624 
7625 /* Nobody should be sending packets down this stream */
7626 /* ARGSUSED */
7627 void
7628 ip_lwput(queue_t *q, mblk_t *mp)
7629 {
7630 	freemsg(mp);
7631 }
7632 
7633 /*
7634  * Move the first hop in any source route to ipha_dst and remove that part of
7635  * the source route.  Called by other protocols.  Errors in option formatting
7636  * are ignored - will be handled by ip_wput_options Return the final
7637  * destination (either ipha_dst or the last entry in a source route.)
7638  */
7639 ipaddr_t
7640 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7641 {
7642 	ipoptp_t	opts;
7643 	uchar_t		*opt;
7644 	uint8_t		optval;
7645 	uint8_t		optlen;
7646 	ipaddr_t	dst;
7647 	int		i;
7648 	ire_t		*ire;
7649 	ip_stack_t	*ipst = ns->netstack_ip;
7650 
7651 	ip2dbg(("ip_massage_options\n"));
7652 	dst = ipha->ipha_dst;
7653 	for (optval = ipoptp_first(&opts, ipha);
7654 	    optval != IPOPT_EOL;
7655 	    optval = ipoptp_next(&opts)) {
7656 		opt = opts.ipoptp_cur;
7657 		switch (optval) {
7658 			uint8_t off;
7659 		case IPOPT_SSRR:
7660 		case IPOPT_LSRR:
7661 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7662 				ip1dbg(("ip_massage_options: bad src route\n"));
7663 				break;
7664 			}
7665 			optlen = opts.ipoptp_len;
7666 			off = opt[IPOPT_OFFSET];
7667 			off--;
7668 		redo_srr:
7669 			if (optlen < IP_ADDR_LEN ||
7670 			    off > optlen - IP_ADDR_LEN) {
7671 				/* End of source route */
7672 				ip1dbg(("ip_massage_options: end of SR\n"));
7673 				break;
7674 			}
7675 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7676 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7677 			    ntohl(dst)));
7678 			/*
7679 			 * Check if our address is present more than
7680 			 * once as consecutive hops in source route.
7681 			 * XXX verify per-interface ip_forwarding
7682 			 * for source route?
7683 			 */
7684 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7685 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7686 			if (ire != NULL) {
7687 				ire_refrele(ire);
7688 				off += IP_ADDR_LEN;
7689 				goto redo_srr;
7690 			}
7691 			if (dst == htonl(INADDR_LOOPBACK)) {
7692 				ip1dbg(("ip_massage_options: loopback addr in "
7693 				    "source route!\n"));
7694 				break;
7695 			}
7696 			/*
7697 			 * Update ipha_dst to be the first hop and remove the
7698 			 * first hop from the source route (by overwriting
7699 			 * part of the option with NOP options).
7700 			 */
7701 			ipha->ipha_dst = dst;
7702 			/* Put the last entry in dst */
7703 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7704 			    3;
7705 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7706 
7707 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7708 			    ntohl(dst)));
7709 			/* Move down and overwrite */
7710 			opt[IP_ADDR_LEN] = opt[0];
7711 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7712 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7713 			for (i = 0; i < IP_ADDR_LEN; i++)
7714 				opt[i] = IPOPT_NOP;
7715 			break;
7716 		}
7717 	}
7718 	return (dst);
7719 }
7720 
7721 /*
7722  * Return the network mask
7723  * associated with the specified address.
7724  */
7725 ipaddr_t
7726 ip_net_mask(ipaddr_t addr)
7727 {
7728 	uchar_t	*up = (uchar_t *)&addr;
7729 	ipaddr_t mask = 0;
7730 	uchar_t	*maskp = (uchar_t *)&mask;
7731 
7732 #if defined(__i386) || defined(__amd64)
7733 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7734 #endif
7735 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7736 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7737 #endif
7738 	if (CLASSD(addr)) {
7739 		maskp[0] = 0xF0;
7740 		return (mask);
7741 	}
7742 
7743 	/* We assume Class E default netmask to be 32 */
7744 	if (CLASSE(addr))
7745 		return (0xffffffffU);
7746 
7747 	if (addr == 0)
7748 		return (0);
7749 	maskp[0] = 0xFF;
7750 	if ((up[0] & 0x80) == 0)
7751 		return (mask);
7752 
7753 	maskp[1] = 0xFF;
7754 	if ((up[0] & 0xC0) == 0x80)
7755 		return (mask);
7756 
7757 	maskp[2] = 0xFF;
7758 	if ((up[0] & 0xE0) == 0xC0)
7759 		return (mask);
7760 
7761 	/* Otherwise return no mask */
7762 	return ((ipaddr_t)0);
7763 }
7764 
7765 /*
7766  * Helper ill lookup function used by IPsec.
7767  */
7768 ill_t *
7769 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7770 {
7771 	ill_t *ret_ill;
7772 
7773 	ASSERT(ifindex != 0);
7774 
7775 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7776 	    ipst);
7777 	if (ret_ill == NULL) {
7778 		if (isv6) {
7779 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7780 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7781 			    ifindex));
7782 		} else {
7783 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7784 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7785 			    ifindex));
7786 		}
7787 		freemsg(first_mp);
7788 		return (NULL);
7789 	}
7790 	return (ret_ill);
7791 }
7792 
7793 /*
7794  * IPv4 -
7795  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7796  * out a packet to a destination address for which we do not have specific
7797  * (or sufficient) routing information.
7798  *
7799  * NOTE : These are the scopes of some of the variables that point at IRE,
7800  *	  which needs to be followed while making any future modifications
7801  *	  to avoid memory leaks.
7802  *
7803  *	- ire and sire are the entries looked up initially by
7804  *	  ire_ftable_lookup.
7805  *	- ipif_ire is used to hold the interface ire associated with
7806  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7807  *	  it before branching out to error paths.
7808  *	- save_ire is initialized before ire_create, so that ire returned
7809  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7810  *	  before breaking out of the switch.
7811  *
7812  *	Thus on failures, we have to REFRELE only ire and sire, if they
7813  *	are not NULL.
7814  */
7815 void
7816 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7817     zoneid_t zoneid, ip_stack_t *ipst)
7818 {
7819 	areq_t	*areq;
7820 	ipaddr_t gw = 0;
7821 	ire_t	*ire = NULL;
7822 	mblk_t	*res_mp;
7823 	ipaddr_t *addrp;
7824 	ipaddr_t nexthop_addr;
7825 	ipif_t  *src_ipif = NULL;
7826 	ill_t	*dst_ill = NULL;
7827 	ipha_t  *ipha;
7828 	ire_t	*sire = NULL;
7829 	mblk_t	*first_mp;
7830 	ire_t	*save_ire;
7831 	ushort_t ire_marks = 0;
7832 	boolean_t mctl_present;
7833 	ipsec_out_t *io;
7834 	mblk_t	*saved_mp;
7835 	mblk_t	*copy_mp = NULL;
7836 	mblk_t	*xmit_mp = NULL;
7837 	ipaddr_t save_dst;
7838 	uint32_t multirt_flags =
7839 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7840 	boolean_t multirt_is_resolvable;
7841 	boolean_t multirt_resolve_next;
7842 	boolean_t unspec_src;
7843 	boolean_t ip_nexthop = B_FALSE;
7844 	tsol_ire_gw_secattr_t *attrp = NULL;
7845 	tsol_gcgrp_t *gcgrp = NULL;
7846 	tsol_gcgrp_addr_t ga;
7847 	int multirt_res_failures = 0;
7848 	int multirt_res_attempts = 0;
7849 	int multirt_already_resolved = 0;
7850 	boolean_t multirt_no_icmp_error = B_FALSE;
7851 
7852 	if (ip_debug > 2) {
7853 		/* ip1dbg */
7854 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7855 	}
7856 
7857 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7858 	if (mctl_present) {
7859 		io = (ipsec_out_t *)first_mp->b_rptr;
7860 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7861 		ASSERT(zoneid == io->ipsec_out_zoneid);
7862 		ASSERT(zoneid != ALL_ZONES);
7863 	}
7864 
7865 	ipha = (ipha_t *)mp->b_rptr;
7866 
7867 	/* All multicast lookups come through ip_newroute_ipif() */
7868 	if (CLASSD(dst)) {
7869 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7870 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7871 		freemsg(first_mp);
7872 		return;
7873 	}
7874 
7875 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7876 		ip_nexthop = B_TRUE;
7877 		nexthop_addr = io->ipsec_out_nexthop_addr;
7878 	}
7879 	/*
7880 	 * If this IRE is created for forwarding or it is not for
7881 	 * traffic for congestion controlled protocols, mark it as temporary.
7882 	 */
7883 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7884 		ire_marks |= IRE_MARK_TEMPORARY;
7885 
7886 	/*
7887 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7888 	 * chain until it gets the most specific information available.
7889 	 * For example, we know that there is no IRE_CACHE for this dest,
7890 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7891 	 * ire_ftable_lookup will look up the gateway, etc.
7892 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7893 	 * to the destination, of equal netmask length in the forward table,
7894 	 * will be recursively explored. If no information is available
7895 	 * for the final gateway of that route, we force the returned ire
7896 	 * to be equal to sire using MATCH_IRE_PARENT.
7897 	 * At least, in this case we have a starting point (in the buckets)
7898 	 * to look for other routes to the destination in the forward table.
7899 	 * This is actually used only for multirouting, where a list
7900 	 * of routes has to be processed in sequence.
7901 	 *
7902 	 * In the process of coming up with the most specific information,
7903 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7904 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7905 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7906 	 * Two caveats when handling incomplete ire's in ip_newroute:
7907 	 * - we should be careful when accessing its ire_nce (specifically
7908 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7909 	 * - not all legacy code path callers are prepared to handle
7910 	 *   incomplete ire's, so we should not create/add incomplete
7911 	 *   ire_cache entries here. (See discussion about temporary solution
7912 	 *   further below).
7913 	 *
7914 	 * In order to minimize packet dropping, and to preserve existing
7915 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7916 	 * gateway, and instead use the IF_RESOLVER ire to send out
7917 	 * another request to ARP (this is achieved by passing the
7918 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7919 	 * arp response comes back in ip_wput_nondata, we will create
7920 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7921 	 *
7922 	 * Note that this is a temporary solution; the correct solution is
7923 	 * to create an incomplete  per-dst ire_cache entry, and send the
7924 	 * packet out when the gw's nce is resolved. In order to achieve this,
7925 	 * all packet processing must have been completed prior to calling
7926 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7927 	 * to be modified to accomodate this solution.
7928 	 */
7929 	if (ip_nexthop) {
7930 		/*
7931 		 * The first time we come here, we look for an IRE_INTERFACE
7932 		 * entry for the specified nexthop, set the dst to be the
7933 		 * nexthop address and create an IRE_CACHE entry for the
7934 		 * nexthop. The next time around, we are able to find an
7935 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7936 		 * nexthop address and create an IRE_CACHE entry for the
7937 		 * destination address via the specified nexthop.
7938 		 */
7939 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7940 		    msg_getlabel(mp), ipst);
7941 		if (ire != NULL) {
7942 			gw = nexthop_addr;
7943 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7944 		} else {
7945 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7946 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7947 			    msg_getlabel(mp),
7948 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7949 			    ipst);
7950 			if (ire != NULL) {
7951 				dst = nexthop_addr;
7952 			}
7953 		}
7954 	} else {
7955 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7956 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
7957 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7958 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7959 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7960 		    ipst);
7961 	}
7962 
7963 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7964 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7965 
7966 	/*
7967 	 * This loop is run only once in most cases.
7968 	 * We loop to resolve further routes only when the destination
7969 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7970 	 */
7971 	do {
7972 		/* Clear the previous iteration's values */
7973 		if (src_ipif != NULL) {
7974 			ipif_refrele(src_ipif);
7975 			src_ipif = NULL;
7976 		}
7977 		if (dst_ill != NULL) {
7978 			ill_refrele(dst_ill);
7979 			dst_ill = NULL;
7980 		}
7981 
7982 		multirt_resolve_next = B_FALSE;
7983 		/*
7984 		 * We check if packets have to be multirouted.
7985 		 * In this case, given the current <ire, sire> couple,
7986 		 * we look for the next suitable <ire, sire>.
7987 		 * This check is done in ire_multirt_lookup(),
7988 		 * which applies various criteria to find the next route
7989 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7990 		 * unchanged if it detects it has not been tried yet.
7991 		 */
7992 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7993 			ip3dbg(("ip_newroute: starting next_resolution "
7994 			    "with first_mp %p, tag %d\n",
7995 			    (void *)first_mp,
7996 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7997 
7998 			ASSERT(sire != NULL);
7999 			multirt_is_resolvable =
8000 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8001 			    &multirt_already_resolved, msg_getlabel(mp), ipst);
8002 
8003 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8004 			    "multirt_already_resolved %d, "
8005 			    "multirt_res_attempts %d, multirt_res_failures %d, "
8006 			    "ire %p, sire %p\n", multirt_is_resolvable,
8007 			    multirt_already_resolved, multirt_res_attempts,
8008 			    multirt_res_failures, (void *)ire, (void *)sire));
8009 
8010 			if (!multirt_is_resolvable) {
8011 				/*
8012 				 * No more multirt route to resolve; give up
8013 				 * (all routes resolved or no more
8014 				 * resolvable routes).
8015 				 */
8016 				if (ire != NULL) {
8017 					ire_refrele(ire);
8018 					ire = NULL;
8019 				}
8020 				/*
8021 				 * Generate ICMP error only if all attempts to
8022 				 * resolve multirt route failed and there is no
8023 				 * already resolved one.  Don't generate ICMP
8024 				 * error when:
8025 				 *
8026 				 *  1) there was no attempt to resolve
8027 				 *  2) at least one attempt passed
8028 				 *  3) a multirt route is already resolved
8029 				 *
8030 				 *  Case 1) may occur due to multiple
8031 				 *    resolution attempts during single
8032 				 *    ip_multirt_resolution_interval.
8033 				 *
8034 				 *  Case 2-3) means that CGTP destination is
8035 				 *    reachable via one link so we don't want to
8036 				 *    generate ICMP host unreachable error.
8037 				 */
8038 				if (multirt_res_attempts == 0 ||
8039 				    multirt_res_failures <
8040 				    multirt_res_attempts ||
8041 				    multirt_already_resolved > 0)
8042 					multirt_no_icmp_error = B_TRUE;
8043 			} else {
8044 				ASSERT(sire != NULL);
8045 				ASSERT(ire != NULL);
8046 
8047 				multirt_res_attempts++;
8048 			}
8049 		}
8050 
8051 		if (ire == NULL) {
8052 			if (ip_debug > 3) {
8053 				/* ip2dbg */
8054 				pr_addr_dbg("ip_newroute: "
8055 				    "can't resolve %s\n", AF_INET, &dst);
8056 			}
8057 			ip3dbg(("ip_newroute: "
8058 			    "ire %p, sire %p, multirt_no_icmp_error %d\n",
8059 			    (void *)ire, (void *)sire,
8060 			    (int)multirt_no_icmp_error));
8061 
8062 			if (sire != NULL) {
8063 				ire_refrele(sire);
8064 				sire = NULL;
8065 			}
8066 
8067 			if (multirt_no_icmp_error) {
8068 				/* There is no need to report an ICMP error. */
8069 				MULTIRT_DEBUG_UNTAG(first_mp);
8070 				freemsg(first_mp);
8071 				return;
8072 			}
8073 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8074 			    RTA_DST, ipst);
8075 			goto icmp_err_ret;
8076 		}
8077 
8078 		/*
8079 		 * Verify that the returned IRE does not have either
8080 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8081 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8082 		 */
8083 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8084 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8085 			goto icmp_err_ret;
8086 		}
8087 		/*
8088 		 * Increment the ire_ob_pkt_count field for ire if it is an
8089 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8090 		 * increment the same for the parent IRE, sire, if it is some
8091 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8092 		 */
8093 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8094 			UPDATE_OB_PKT_COUNT(ire);
8095 			ire->ire_last_used_time = lbolt;
8096 		}
8097 
8098 		if (sire != NULL) {
8099 			gw = sire->ire_gateway_addr;
8100 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8101 			    IRE_INTERFACE)) == 0);
8102 			UPDATE_OB_PKT_COUNT(sire);
8103 			sire->ire_last_used_time = lbolt;
8104 		}
8105 		/*
8106 		 * We have a route to reach the destination.  Find the
8107 		 * appropriate ill, then get a source address using
8108 		 * ipif_select_source().
8109 		 *
8110 		 * If we are here trying to create an IRE_CACHE for an offlink
8111 		 * destination and have an IRE_CACHE entry for VNI, then use
8112 		 * ire_stq instead since VNI's queue is a black hole.
8113 		 */
8114 		if ((ire->ire_type == IRE_CACHE) &&
8115 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8116 			dst_ill = ire->ire_stq->q_ptr;
8117 			ill_refhold(dst_ill);
8118 		} else {
8119 			ill_t *ill = ire->ire_ipif->ipif_ill;
8120 
8121 			if (IS_IPMP(ill)) {
8122 				dst_ill =
8123 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8124 			} else {
8125 				dst_ill = ill;
8126 				ill_refhold(dst_ill);
8127 			}
8128 		}
8129 
8130 		if (dst_ill == NULL) {
8131 			if (ip_debug > 2) {
8132 				pr_addr_dbg("ip_newroute: no dst "
8133 				    "ill for dst %s\n", AF_INET, &dst);
8134 			}
8135 			goto icmp_err_ret;
8136 		}
8137 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8138 
8139 		/*
8140 		 * Pick the best source address from dst_ill.
8141 		 *
8142 		 * 1) Try to pick the source address from the destination
8143 		 *    route. Clustering assumes that when we have multiple
8144 		 *    prefixes hosted on an interface, the prefix of the
8145 		 *    source address matches the prefix of the destination
8146 		 *    route. We do this only if the address is not
8147 		 *    DEPRECATED.
8148 		 *
8149 		 * 2) If the conn is in a different zone than the ire, we
8150 		 *    need to pick a source address from the right zone.
8151 		 */
8152 		ASSERT(src_ipif == NULL);
8153 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8154 			/*
8155 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8156 			 * Check that the ipif matching the requested source
8157 			 * address still exists.
8158 			 */
8159 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8160 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8161 		}
8162 
8163 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8164 
8165 		if (src_ipif == NULL &&
8166 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8167 			ire_marks |= IRE_MARK_USESRC_CHECK;
8168 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8169 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8170 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8171 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8172 			    ire->ire_zoneid != ALL_ZONES) ||
8173 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8174 				/*
8175 				 * If the destination is reachable via a
8176 				 * given gateway, the selected source address
8177 				 * should be in the same subnet as the gateway.
8178 				 * Otherwise, the destination is not reachable.
8179 				 *
8180 				 * If there are no interfaces on the same subnet
8181 				 * as the destination, ipif_select_source gives
8182 				 * first non-deprecated interface which might be
8183 				 * on a different subnet than the gateway.
8184 				 * This is not desirable. Hence pass the dst_ire
8185 				 * source address to ipif_select_source.
8186 				 * It is sure that the destination is reachable
8187 				 * with the dst_ire source address subnet.
8188 				 * So passing dst_ire source address to
8189 				 * ipif_select_source will make sure that the
8190 				 * selected source will be on the same subnet
8191 				 * as dst_ire source address.
8192 				 */
8193 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8194 
8195 				src_ipif = ipif_select_source(dst_ill, saddr,
8196 				    zoneid);
8197 				if (src_ipif == NULL) {
8198 					/*
8199 					 * In the case of multirouting, it may
8200 					 * happen that ipif_select_source fails
8201 					 * as DAD may disallow use of the
8202 					 * particular source interface.  Anyway,
8203 					 * we need to continue and attempt to
8204 					 * resolve other multirt routes.
8205 					 */
8206 					if ((sire != NULL) &&
8207 					    (sire->ire_flags & RTF_MULTIRT)) {
8208 						ire_refrele(ire);
8209 						ire = NULL;
8210 						multirt_resolve_next = B_TRUE;
8211 						multirt_res_failures++;
8212 						continue;
8213 					}
8214 
8215 					if (ip_debug > 2) {
8216 						pr_addr_dbg("ip_newroute: "
8217 						    "no src for dst %s ",
8218 						    AF_INET, &dst);
8219 						printf("on interface %s\n",
8220 						    dst_ill->ill_name);
8221 					}
8222 					goto icmp_err_ret;
8223 				}
8224 			} else {
8225 				src_ipif = ire->ire_ipif;
8226 				ASSERT(src_ipif != NULL);
8227 				/* hold src_ipif for uniformity */
8228 				ipif_refhold(src_ipif);
8229 			}
8230 		}
8231 
8232 		/*
8233 		 * Assign a source address while we have the conn.
8234 		 * We can't have ip_wput_ire pick a source address when the
8235 		 * packet returns from arp since we need to look at
8236 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8237 		 * going through arp.
8238 		 *
8239 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8240 		 *	  it uses ip6i to store this information.
8241 		 */
8242 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8243 			ipha->ipha_src = src_ipif->ipif_src_addr;
8244 
8245 		if (ip_debug > 3) {
8246 			/* ip2dbg */
8247 			pr_addr_dbg("ip_newroute: first hop %s\n",
8248 			    AF_INET, &gw);
8249 		}
8250 		ip2dbg(("\tire type %s (%d)\n",
8251 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8252 
8253 		/*
8254 		 * The TTL of multirouted packets is bounded by the
8255 		 * ip_multirt_ttl ndd variable.
8256 		 */
8257 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8258 			/* Force TTL of multirouted packets */
8259 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8260 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8261 				ip2dbg(("ip_newroute: forcing multirt TTL "
8262 				    "to %d (was %d), dst 0x%08x\n",
8263 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8264 				    ntohl(sire->ire_addr)));
8265 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8266 			}
8267 		}
8268 		/*
8269 		 * At this point in ip_newroute(), ire is either the
8270 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8271 		 * destination or an IRE_INTERFACE type that should be used
8272 		 * to resolve an on-subnet destination or an on-subnet
8273 		 * next-hop gateway.
8274 		 *
8275 		 * In the IRE_CACHE case, we have the following :
8276 		 *
8277 		 * 1) src_ipif - used for getting a source address.
8278 		 *
8279 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8280 		 *    means packets using this IRE_CACHE will go out on
8281 		 *    dst_ill.
8282 		 *
8283 		 * 3) The IRE sire will point to the prefix that is the
8284 		 *    longest  matching route for the destination. These
8285 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8286 		 *
8287 		 *    The newly created IRE_CACHE entry for the off-subnet
8288 		 *    destination is tied to both the prefix route and the
8289 		 *    interface route used to resolve the next-hop gateway
8290 		 *    via the ire_phandle and ire_ihandle fields,
8291 		 *    respectively.
8292 		 *
8293 		 * In the IRE_INTERFACE case, we have the following :
8294 		 *
8295 		 * 1) src_ipif - used for getting a source address.
8296 		 *
8297 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8298 		 *    means packets using the IRE_CACHE that we will build
8299 		 *    here will go out on dst_ill.
8300 		 *
8301 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8302 		 *    to be created will only be tied to the IRE_INTERFACE
8303 		 *    that was derived from the ire_ihandle field.
8304 		 *
8305 		 *    If sire is non-NULL, it means the destination is
8306 		 *    off-link and we will first create the IRE_CACHE for the
8307 		 *    gateway. Next time through ip_newroute, we will create
8308 		 *    the IRE_CACHE for the final destination as described
8309 		 *    above.
8310 		 *
8311 		 * In both cases, after the current resolution has been
8312 		 * completed (or possibly initialised, in the IRE_INTERFACE
8313 		 * case), the loop may be re-entered to attempt the resolution
8314 		 * of another RTF_MULTIRT route.
8315 		 *
8316 		 * When an IRE_CACHE entry for the off-subnet destination is
8317 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8318 		 * for further processing in emission loops.
8319 		 */
8320 		save_ire = ire;
8321 		switch (ire->ire_type) {
8322 		case IRE_CACHE: {
8323 			ire_t	*ipif_ire;
8324 
8325 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8326 			if (gw == 0)
8327 				gw = ire->ire_gateway_addr;
8328 			/*
8329 			 * We need 3 ire's to create a new cache ire for an
8330 			 * off-link destination from the cache ire of the
8331 			 * gateway.
8332 			 *
8333 			 *	1. The prefix ire 'sire' (Note that this does
8334 			 *	   not apply to the conn_nexthop_set case)
8335 			 *	2. The cache ire of the gateway 'ire'
8336 			 *	3. The interface ire 'ipif_ire'
8337 			 *
8338 			 * We have (1) and (2). We lookup (3) below.
8339 			 *
8340 			 * If there is no interface route to the gateway,
8341 			 * it is a race condition, where we found the cache
8342 			 * but the interface route has been deleted.
8343 			 */
8344 			if (ip_nexthop) {
8345 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8346 			} else {
8347 				ipif_ire =
8348 				    ire_ihandle_lookup_offlink(ire, sire);
8349 			}
8350 			if (ipif_ire == NULL) {
8351 				ip1dbg(("ip_newroute: "
8352 				    "ire_ihandle_lookup_offlink failed\n"));
8353 				goto icmp_err_ret;
8354 			}
8355 
8356 			/*
8357 			 * Check cached gateway IRE for any security
8358 			 * attributes; if found, associate the gateway
8359 			 * credentials group to the destination IRE.
8360 			 */
8361 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8362 				mutex_enter(&attrp->igsa_lock);
8363 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8364 					GCGRP_REFHOLD(gcgrp);
8365 				mutex_exit(&attrp->igsa_lock);
8366 			}
8367 
8368 			/*
8369 			 * XXX For the source of the resolver mp,
8370 			 * we are using the same DL_UNITDATA_REQ
8371 			 * (from save_ire->ire_nce->nce_res_mp)
8372 			 * though the save_ire is not pointing at the same ill.
8373 			 * This is incorrect. We need to send it up to the
8374 			 * resolver to get the right res_mp. For ethernets
8375 			 * this may be okay (ill_type == DL_ETHER).
8376 			 */
8377 
8378 			ire = ire_create(
8379 			    (uchar_t *)&dst,		/* dest address */
8380 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8381 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8382 			    (uchar_t *)&gw,		/* gateway address */
8383 			    &save_ire->ire_max_frag,
8384 			    save_ire->ire_nce,		/* src nce */
8385 			    dst_ill->ill_rq,		/* recv-from queue */
8386 			    dst_ill->ill_wq,		/* send-to queue */
8387 			    IRE_CACHE,			/* IRE type */
8388 			    src_ipif,
8389 			    (sire != NULL) ?
8390 			    sire->ire_mask : 0, 	/* Parent mask */
8391 			    (sire != NULL) ?
8392 			    sire->ire_phandle : 0,	/* Parent handle */
8393 			    ipif_ire->ire_ihandle,	/* Interface handle */
8394 			    (sire != NULL) ? (sire->ire_flags &
8395 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8396 			    (sire != NULL) ?
8397 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8398 			    NULL,
8399 			    gcgrp,
8400 			    ipst);
8401 
8402 			if (ire == NULL) {
8403 				if (gcgrp != NULL) {
8404 					GCGRP_REFRELE(gcgrp);
8405 					gcgrp = NULL;
8406 				}
8407 				ire_refrele(ipif_ire);
8408 				ire_refrele(save_ire);
8409 				break;
8410 			}
8411 
8412 			/* reference now held by IRE */
8413 			gcgrp = NULL;
8414 
8415 			ire->ire_marks |= ire_marks;
8416 
8417 			/*
8418 			 * Prevent sire and ipif_ire from getting deleted.
8419 			 * The newly created ire is tied to both of them via
8420 			 * the phandle and ihandle respectively.
8421 			 */
8422 			if (sire != NULL) {
8423 				IRB_REFHOLD(sire->ire_bucket);
8424 				/* Has it been removed already ? */
8425 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8426 					IRB_REFRELE(sire->ire_bucket);
8427 					ire_refrele(ipif_ire);
8428 					ire_refrele(save_ire);
8429 					break;
8430 				}
8431 			}
8432 
8433 			IRB_REFHOLD(ipif_ire->ire_bucket);
8434 			/* Has it been removed already ? */
8435 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8436 				IRB_REFRELE(ipif_ire->ire_bucket);
8437 				if (sire != NULL)
8438 					IRB_REFRELE(sire->ire_bucket);
8439 				ire_refrele(ipif_ire);
8440 				ire_refrele(save_ire);
8441 				break;
8442 			}
8443 
8444 			xmit_mp = first_mp;
8445 			/*
8446 			 * In the case of multirouting, a copy
8447 			 * of the packet is done before its sending.
8448 			 * The copy is used to attempt another
8449 			 * route resolution, in a next loop.
8450 			 */
8451 			if (ire->ire_flags & RTF_MULTIRT) {
8452 				copy_mp = copymsg(first_mp);
8453 				if (copy_mp != NULL) {
8454 					xmit_mp = copy_mp;
8455 					MULTIRT_DEBUG_TAG(first_mp);
8456 				}
8457 			}
8458 
8459 			ire_add_then_send(q, ire, xmit_mp);
8460 			ire_refrele(save_ire);
8461 
8462 			/* Assert that sire is not deleted yet. */
8463 			if (sire != NULL) {
8464 				ASSERT(sire->ire_ptpn != NULL);
8465 				IRB_REFRELE(sire->ire_bucket);
8466 			}
8467 
8468 			/* Assert that ipif_ire is not deleted yet. */
8469 			ASSERT(ipif_ire->ire_ptpn != NULL);
8470 			IRB_REFRELE(ipif_ire->ire_bucket);
8471 			ire_refrele(ipif_ire);
8472 
8473 			/*
8474 			 * If copy_mp is not NULL, multirouting was
8475 			 * requested. We loop to initiate a next
8476 			 * route resolution attempt, starting from sire.
8477 			 */
8478 			if (copy_mp != NULL) {
8479 				/*
8480 				 * Search for the next unresolved
8481 				 * multirt route.
8482 				 */
8483 				copy_mp = NULL;
8484 				ipif_ire = NULL;
8485 				ire = NULL;
8486 				multirt_resolve_next = B_TRUE;
8487 				continue;
8488 			}
8489 			if (sire != NULL)
8490 				ire_refrele(sire);
8491 			ipif_refrele(src_ipif);
8492 			ill_refrele(dst_ill);
8493 			return;
8494 		}
8495 		case IRE_IF_NORESOLVER: {
8496 			if (dst_ill->ill_resolver_mp == NULL) {
8497 				ip1dbg(("ip_newroute: dst_ill %p "
8498 				    "for IRE_IF_NORESOLVER ire %p has "
8499 				    "no ill_resolver_mp\n",
8500 				    (void *)dst_ill, (void *)ire));
8501 				break;
8502 			}
8503 
8504 			/*
8505 			 * TSol note: We are creating the ire cache for the
8506 			 * destination 'dst'. If 'dst' is offlink, going
8507 			 * through the first hop 'gw', the security attributes
8508 			 * of 'dst' must be set to point to the gateway
8509 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8510 			 * is possible that 'dst' is a potential gateway that is
8511 			 * referenced by some route that has some security
8512 			 * attributes. Thus in the former case, we need to do a
8513 			 * gcgrp_lookup of 'gw' while in the latter case we
8514 			 * need to do gcgrp_lookup of 'dst' itself.
8515 			 */
8516 			ga.ga_af = AF_INET;
8517 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8518 			    &ga.ga_addr);
8519 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8520 
8521 			ire = ire_create(
8522 			    (uchar_t *)&dst,		/* dest address */
8523 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8524 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8525 			    (uchar_t *)&gw,		/* gateway address */
8526 			    &save_ire->ire_max_frag,
8527 			    NULL,			/* no src nce */
8528 			    dst_ill->ill_rq,		/* recv-from queue */
8529 			    dst_ill->ill_wq,		/* send-to queue */
8530 			    IRE_CACHE,
8531 			    src_ipif,
8532 			    save_ire->ire_mask,		/* Parent mask */
8533 			    (sire != NULL) ?		/* Parent handle */
8534 			    sire->ire_phandle : 0,
8535 			    save_ire->ire_ihandle,	/* Interface handle */
8536 			    (sire != NULL) ? sire->ire_flags &
8537 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8538 			    &(save_ire->ire_uinfo),
8539 			    NULL,
8540 			    gcgrp,
8541 			    ipst);
8542 
8543 			if (ire == NULL) {
8544 				if (gcgrp != NULL) {
8545 					GCGRP_REFRELE(gcgrp);
8546 					gcgrp = NULL;
8547 				}
8548 				ire_refrele(save_ire);
8549 				break;
8550 			}
8551 
8552 			/* reference now held by IRE */
8553 			gcgrp = NULL;
8554 
8555 			ire->ire_marks |= ire_marks;
8556 
8557 			/* Prevent save_ire from getting deleted */
8558 			IRB_REFHOLD(save_ire->ire_bucket);
8559 			/* Has it been removed already ? */
8560 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8561 				IRB_REFRELE(save_ire->ire_bucket);
8562 				ire_refrele(save_ire);
8563 				break;
8564 			}
8565 
8566 			/*
8567 			 * In the case of multirouting, a copy
8568 			 * of the packet is made before it is sent.
8569 			 * The copy is used in the next
8570 			 * loop to attempt another resolution.
8571 			 */
8572 			xmit_mp = first_mp;
8573 			if ((sire != NULL) &&
8574 			    (sire->ire_flags & RTF_MULTIRT)) {
8575 				copy_mp = copymsg(first_mp);
8576 				if (copy_mp != NULL) {
8577 					xmit_mp = copy_mp;
8578 					MULTIRT_DEBUG_TAG(first_mp);
8579 				}
8580 			}
8581 			ire_add_then_send(q, ire, xmit_mp);
8582 
8583 			/* Assert that it is not deleted yet. */
8584 			ASSERT(save_ire->ire_ptpn != NULL);
8585 			IRB_REFRELE(save_ire->ire_bucket);
8586 			ire_refrele(save_ire);
8587 
8588 			if (copy_mp != NULL) {
8589 				/*
8590 				 * If we found a (no)resolver, we ignore any
8591 				 * trailing top priority IRE_CACHE in further
8592 				 * loops. This ensures that we do not omit any
8593 				 * (no)resolver.
8594 				 * This IRE_CACHE, if any, will be processed
8595 				 * by another thread entering ip_newroute().
8596 				 * IRE_CACHE entries, if any, will be processed
8597 				 * by another thread entering ip_newroute(),
8598 				 * (upon resolver response, for instance).
8599 				 * This aims to force parallel multirt
8600 				 * resolutions as soon as a packet must be sent.
8601 				 * In the best case, after the tx of only one
8602 				 * packet, all reachable routes are resolved.
8603 				 * Otherwise, the resolution of all RTF_MULTIRT
8604 				 * routes would require several emissions.
8605 				 */
8606 				multirt_flags &= ~MULTIRT_CACHEGW;
8607 
8608 				/*
8609 				 * Search for the next unresolved multirt
8610 				 * route.
8611 				 */
8612 				copy_mp = NULL;
8613 				save_ire = NULL;
8614 				ire = NULL;
8615 				multirt_resolve_next = B_TRUE;
8616 				continue;
8617 			}
8618 
8619 			/*
8620 			 * Don't need sire anymore
8621 			 */
8622 			if (sire != NULL)
8623 				ire_refrele(sire);
8624 
8625 			ipif_refrele(src_ipif);
8626 			ill_refrele(dst_ill);
8627 			return;
8628 		}
8629 		case IRE_IF_RESOLVER:
8630 			/*
8631 			 * We can't build an IRE_CACHE yet, but at least we
8632 			 * found a resolver that can help.
8633 			 */
8634 			res_mp = dst_ill->ill_resolver_mp;
8635 			if (!OK_RESOLVER_MP(res_mp))
8636 				break;
8637 
8638 			/*
8639 			 * To be at this point in the code with a non-zero gw
8640 			 * means that dst is reachable through a gateway that
8641 			 * we have never resolved.  By changing dst to the gw
8642 			 * addr we resolve the gateway first.
8643 			 * When ire_add_then_send() tries to put the IP dg
8644 			 * to dst, it will reenter ip_newroute() at which
8645 			 * time we will find the IRE_CACHE for the gw and
8646 			 * create another IRE_CACHE in case IRE_CACHE above.
8647 			 */
8648 			if (gw != INADDR_ANY) {
8649 				/*
8650 				 * The source ipif that was determined above was
8651 				 * relative to the destination address, not the
8652 				 * gateway's. If src_ipif was not taken out of
8653 				 * the IRE_IF_RESOLVER entry, we'll need to call
8654 				 * ipif_select_source() again.
8655 				 */
8656 				if (src_ipif != ire->ire_ipif) {
8657 					ipif_refrele(src_ipif);
8658 					src_ipif = ipif_select_source(dst_ill,
8659 					    gw, zoneid);
8660 					/*
8661 					 * In the case of multirouting, it may
8662 					 * happen that ipif_select_source fails
8663 					 * as DAD may disallow use of the
8664 					 * particular source interface.  Anyway,
8665 					 * we need to continue and attempt to
8666 					 * resolve other multirt routes.
8667 					 */
8668 					if (src_ipif == NULL) {
8669 						if (sire != NULL &&
8670 						    (sire->ire_flags &
8671 						    RTF_MULTIRT)) {
8672 							ire_refrele(ire);
8673 							ire = NULL;
8674 							multirt_resolve_next =
8675 							    B_TRUE;
8676 							multirt_res_failures++;
8677 							continue;
8678 						}
8679 						if (ip_debug > 2) {
8680 							pr_addr_dbg(
8681 							    "ip_newroute: no "
8682 							    "src for gw %s ",
8683 							    AF_INET, &gw);
8684 							printf("on "
8685 							    "interface %s\n",
8686 							    dst_ill->ill_name);
8687 						}
8688 						goto icmp_err_ret;
8689 					}
8690 				}
8691 				save_dst = dst;
8692 				dst = gw;
8693 				gw = INADDR_ANY;
8694 			}
8695 
8696 			/*
8697 			 * We obtain a partial IRE_CACHE which we will pass
8698 			 * along with the resolver query.  When the response
8699 			 * comes back it will be there ready for us to add.
8700 			 * The ire_max_frag is atomically set under the
8701 			 * irebucket lock in ire_add_v[46].
8702 			 */
8703 
8704 			ire = ire_create_mp(
8705 			    (uchar_t *)&dst,		/* dest address */
8706 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8707 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8708 			    (uchar_t *)&gw,		/* gateway address */
8709 			    NULL,			/* ire_max_frag */
8710 			    NULL,			/* no src nce */
8711 			    dst_ill->ill_rq,		/* recv-from queue */
8712 			    dst_ill->ill_wq,		/* send-to queue */
8713 			    IRE_CACHE,
8714 			    src_ipif,			/* Interface ipif */
8715 			    save_ire->ire_mask,		/* Parent mask */
8716 			    0,
8717 			    save_ire->ire_ihandle,	/* Interface handle */
8718 			    0,				/* flags if any */
8719 			    &(save_ire->ire_uinfo),
8720 			    NULL,
8721 			    NULL,
8722 			    ipst);
8723 
8724 			if (ire == NULL) {
8725 				ire_refrele(save_ire);
8726 				break;
8727 			}
8728 
8729 			if ((sire != NULL) &&
8730 			    (sire->ire_flags & RTF_MULTIRT)) {
8731 				copy_mp = copymsg(first_mp);
8732 				if (copy_mp != NULL)
8733 					MULTIRT_DEBUG_TAG(copy_mp);
8734 			}
8735 
8736 			ire->ire_marks |= ire_marks;
8737 
8738 			/*
8739 			 * Construct message chain for the resolver
8740 			 * of the form:
8741 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8742 			 * Packet could contain a IPSEC_OUT mp.
8743 			 *
8744 			 * NOTE : ire will be added later when the response
8745 			 * comes back from ARP. If the response does not
8746 			 * come back, ARP frees the packet. For this reason,
8747 			 * we can't REFHOLD the bucket of save_ire to prevent
8748 			 * deletions. We may not be able to REFRELE the bucket
8749 			 * if the response never comes back. Thus, before
8750 			 * adding the ire, ire_add_v4 will make sure that the
8751 			 * interface route does not get deleted. This is the
8752 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8753 			 * where we can always prevent deletions because of
8754 			 * the synchronous nature of adding IRES i.e
8755 			 * ire_add_then_send is called after creating the IRE.
8756 			 */
8757 			ASSERT(ire->ire_mp != NULL);
8758 			ire->ire_mp->b_cont = first_mp;
8759 			/* Have saved_mp handy, for cleanup if canput fails */
8760 			saved_mp = mp;
8761 			mp = copyb(res_mp);
8762 			if (mp == NULL) {
8763 				/* Prepare for cleanup */
8764 				mp = saved_mp; /* pkt */
8765 				ire_delete(ire); /* ire_mp */
8766 				ire = NULL;
8767 				ire_refrele(save_ire);
8768 				if (copy_mp != NULL) {
8769 					MULTIRT_DEBUG_UNTAG(copy_mp);
8770 					freemsg(copy_mp);
8771 					copy_mp = NULL;
8772 				}
8773 				break;
8774 			}
8775 			linkb(mp, ire->ire_mp);
8776 
8777 			/*
8778 			 * Fill in the source and dest addrs for the resolver.
8779 			 * NOTE: this depends on memory layouts imposed by
8780 			 * ill_init().
8781 			 */
8782 			areq = (areq_t *)mp->b_rptr;
8783 			addrp = (ipaddr_t *)((char *)areq +
8784 			    areq->areq_sender_addr_offset);
8785 			*addrp = save_ire->ire_src_addr;
8786 
8787 			ire_refrele(save_ire);
8788 			addrp = (ipaddr_t *)((char *)areq +
8789 			    areq->areq_target_addr_offset);
8790 			*addrp = dst;
8791 			/* Up to the resolver. */
8792 			if (canputnext(dst_ill->ill_rq) &&
8793 			    !(dst_ill->ill_arp_closing)) {
8794 				putnext(dst_ill->ill_rq, mp);
8795 				ire = NULL;
8796 				if (copy_mp != NULL) {
8797 					/*
8798 					 * If we found a resolver, we ignore
8799 					 * any trailing top priority IRE_CACHE
8800 					 * in the further loops. This ensures
8801 					 * that we do not omit any resolver.
8802 					 * IRE_CACHE entries, if any, will be
8803 					 * processed next time we enter
8804 					 * ip_newroute().
8805 					 */
8806 					multirt_flags &= ~MULTIRT_CACHEGW;
8807 					/*
8808 					 * Search for the next unresolved
8809 					 * multirt route.
8810 					 */
8811 					first_mp = copy_mp;
8812 					copy_mp = NULL;
8813 					/* Prepare the next resolution loop. */
8814 					mp = first_mp;
8815 					EXTRACT_PKT_MP(mp, first_mp,
8816 					    mctl_present);
8817 					if (mctl_present)
8818 						io = (ipsec_out_t *)
8819 						    first_mp->b_rptr;
8820 					ipha = (ipha_t *)mp->b_rptr;
8821 
8822 					ASSERT(sire != NULL);
8823 
8824 					dst = save_dst;
8825 					multirt_resolve_next = B_TRUE;
8826 					continue;
8827 				}
8828 
8829 				if (sire != NULL)
8830 					ire_refrele(sire);
8831 
8832 				/*
8833 				 * The response will come back in ip_wput
8834 				 * with db_type IRE_DB_TYPE.
8835 				 */
8836 				ipif_refrele(src_ipif);
8837 				ill_refrele(dst_ill);
8838 				return;
8839 			} else {
8840 				/* Prepare for cleanup */
8841 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8842 				    mp);
8843 				mp->b_cont = NULL;
8844 				freeb(mp); /* areq */
8845 				/*
8846 				 * this is an ire that is not added to the
8847 				 * cache. ire_freemblk will handle the release
8848 				 * of any resources associated with the ire.
8849 				 */
8850 				ire_delete(ire); /* ire_mp */
8851 				mp = saved_mp; /* pkt */
8852 				ire = NULL;
8853 				if (copy_mp != NULL) {
8854 					MULTIRT_DEBUG_UNTAG(copy_mp);
8855 					freemsg(copy_mp);
8856 					copy_mp = NULL;
8857 				}
8858 				break;
8859 			}
8860 		default:
8861 			break;
8862 		}
8863 	} while (multirt_resolve_next);
8864 
8865 	ip1dbg(("ip_newroute: dropped\n"));
8866 	/* Did this packet originate externally? */
8867 	if (mp->b_prev) {
8868 		mp->b_next = NULL;
8869 		mp->b_prev = NULL;
8870 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8871 	} else {
8872 		if (dst_ill != NULL) {
8873 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8874 		} else {
8875 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8876 		}
8877 	}
8878 	ASSERT(copy_mp == NULL);
8879 	MULTIRT_DEBUG_UNTAG(first_mp);
8880 	freemsg(first_mp);
8881 	if (ire != NULL)
8882 		ire_refrele(ire);
8883 	if (sire != NULL)
8884 		ire_refrele(sire);
8885 	if (src_ipif != NULL)
8886 		ipif_refrele(src_ipif);
8887 	if (dst_ill != NULL)
8888 		ill_refrele(dst_ill);
8889 	return;
8890 
8891 icmp_err_ret:
8892 	ip1dbg(("ip_newroute: no route\n"));
8893 	if (src_ipif != NULL)
8894 		ipif_refrele(src_ipif);
8895 	if (dst_ill != NULL)
8896 		ill_refrele(dst_ill);
8897 	if (sire != NULL)
8898 		ire_refrele(sire);
8899 	/* Did this packet originate externally? */
8900 	if (mp->b_prev) {
8901 		mp->b_next = NULL;
8902 		mp->b_prev = NULL;
8903 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8904 		q = WR(q);
8905 	} else {
8906 		/*
8907 		 * There is no outgoing ill, so just increment the
8908 		 * system MIB.
8909 		 */
8910 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8911 		/*
8912 		 * Since ip_wput() isn't close to finished, we fill
8913 		 * in enough of the header for credible error reporting.
8914 		 */
8915 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8916 			/* Failed */
8917 			MULTIRT_DEBUG_UNTAG(first_mp);
8918 			freemsg(first_mp);
8919 			if (ire != NULL)
8920 				ire_refrele(ire);
8921 			return;
8922 		}
8923 	}
8924 
8925 	/*
8926 	 * At this point we will have ire only if RTF_BLACKHOLE
8927 	 * or RTF_REJECT flags are set on the IRE. It will not
8928 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8929 	 */
8930 	if (ire != NULL) {
8931 		if (ire->ire_flags & RTF_BLACKHOLE) {
8932 			ire_refrele(ire);
8933 			MULTIRT_DEBUG_UNTAG(first_mp);
8934 			freemsg(first_mp);
8935 			return;
8936 		}
8937 		ire_refrele(ire);
8938 	}
8939 	if (ip_source_routed(ipha, ipst)) {
8940 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8941 		    zoneid, ipst);
8942 		return;
8943 	}
8944 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8945 }
8946 
8947 ip_opt_info_t zero_info;
8948 
8949 /*
8950  * IPv4 -
8951  * ip_newroute_ipif is called by ip_wput_multicast and
8952  * ip_rput_forward_multicast whenever we need to send
8953  * out a packet to a destination address for which we do not have specific
8954  * routing information. It is used when the packet will be sent out
8955  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8956  * socket option is set or icmp error message wants to go out on a particular
8957  * interface for a unicast packet.
8958  *
8959  * In most cases, the destination address is resolved thanks to the ipif
8960  * intrinsic resolver. However, there are some cases where the call to
8961  * ip_newroute_ipif must take into account the potential presence of
8962  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8963  * that uses the interface. This is specified through flags,
8964  * which can be a combination of:
8965  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8966  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8967  *   and flags. Additionally, the packet source address has to be set to
8968  *   the specified address. The caller is thus expected to set this flag
8969  *   if the packet has no specific source address yet.
8970  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8971  *   flag, the resulting ire will inherit the flag. All unresolved routes
8972  *   to the destination must be explored in the same call to
8973  *   ip_newroute_ipif().
8974  */
8975 static void
8976 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8977     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8978 {
8979 	areq_t	*areq;
8980 	ire_t	*ire = NULL;
8981 	mblk_t	*res_mp;
8982 	ipaddr_t *addrp;
8983 	mblk_t *first_mp;
8984 	ire_t	*save_ire = NULL;
8985 	ipif_t	*src_ipif = NULL;
8986 	ushort_t ire_marks = 0;
8987 	ill_t	*dst_ill = NULL;
8988 	ipha_t *ipha;
8989 	mblk_t	*saved_mp;
8990 	ire_t   *fire = NULL;
8991 	mblk_t  *copy_mp = NULL;
8992 	boolean_t multirt_resolve_next;
8993 	boolean_t unspec_src;
8994 	ipaddr_t ipha_dst;
8995 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8996 
8997 	/*
8998 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8999 	 * here for uniformity
9000 	 */
9001 	ipif_refhold(ipif);
9002 
9003 	/*
9004 	 * This loop is run only once in most cases.
9005 	 * We loop to resolve further routes only when the destination
9006 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9007 	 */
9008 	do {
9009 		if (dst_ill != NULL) {
9010 			ill_refrele(dst_ill);
9011 			dst_ill = NULL;
9012 		}
9013 		if (src_ipif != NULL) {
9014 			ipif_refrele(src_ipif);
9015 			src_ipif = NULL;
9016 		}
9017 		multirt_resolve_next = B_FALSE;
9018 
9019 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9020 		    ipif->ipif_ill->ill_name));
9021 
9022 		first_mp = mp;
9023 		if (DB_TYPE(mp) == M_CTL)
9024 			mp = mp->b_cont;
9025 		ipha = (ipha_t *)mp->b_rptr;
9026 
9027 		/*
9028 		 * Save the packet destination address, we may need it after
9029 		 * the packet has been consumed.
9030 		 */
9031 		ipha_dst = ipha->ipha_dst;
9032 
9033 		/*
9034 		 * If the interface is a pt-pt interface we look for an
9035 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9036 		 * local_address and the pt-pt destination address. Otherwise
9037 		 * we just match the local address.
9038 		 * NOTE: dst could be different than ipha->ipha_dst in case
9039 		 * of sending igmp multicast packets over a point-to-point
9040 		 * connection.
9041 		 * Thus we must be careful enough to check ipha_dst to be a
9042 		 * multicast address, otherwise it will take xmit_if path for
9043 		 * multicast packets resulting into kernel stack overflow by
9044 		 * repeated calls to ip_newroute_ipif from ire_send().
9045 		 */
9046 		if (CLASSD(ipha_dst) &&
9047 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9048 			goto err_ret;
9049 		}
9050 
9051 		/*
9052 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9053 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9054 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9055 		 * propagate its flags to the new ire.
9056 		 */
9057 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9058 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9059 			ip2dbg(("ip_newroute_ipif: "
9060 			    "ipif_lookup_multi_ire("
9061 			    "ipif %p, dst %08x) = fire %p\n",
9062 			    (void *)ipif, ntohl(dst), (void *)fire));
9063 		}
9064 
9065 		/*
9066 		 * Note: While we pick a dst_ill we are really only
9067 		 * interested in the ill for load spreading. The source
9068 		 * ipif is determined by source address selection below.
9069 		 */
9070 		if (IS_IPMP(ipif->ipif_ill)) {
9071 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9072 
9073 			if (CLASSD(ipha_dst))
9074 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9075 			else
9076 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9077 		} else {
9078 			dst_ill = ipif->ipif_ill;
9079 			ill_refhold(dst_ill);
9080 		}
9081 
9082 		if (dst_ill == NULL) {
9083 			if (ip_debug > 2) {
9084 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9085 				    "for dst %s\n", AF_INET, &dst);
9086 			}
9087 			goto err_ret;
9088 		}
9089 
9090 		/*
9091 		 * Pick a source address preferring non-deprecated ones.
9092 		 * Unlike ip_newroute, we don't do any source address
9093 		 * selection here since for multicast it really does not help
9094 		 * in inbound load spreading as in the unicast case.
9095 		 */
9096 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9097 		    (fire->ire_flags & RTF_SETSRC)) {
9098 			/*
9099 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9100 			 * on that interface. This ire has RTF_SETSRC flag, so
9101 			 * the source address of the packet must be changed.
9102 			 * Check that the ipif matching the requested source
9103 			 * address still exists.
9104 			 */
9105 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9106 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9107 		}
9108 
9109 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9110 
9111 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9112 		    (IS_IPMP(ipif->ipif_ill) ||
9113 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9114 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9115 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9116 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9117 		    (src_ipif == NULL) &&
9118 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9119 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9120 			if (src_ipif == NULL) {
9121 				if (ip_debug > 2) {
9122 					/* ip1dbg */
9123 					pr_addr_dbg("ip_newroute_ipif: "
9124 					    "no src for dst %s",
9125 					    AF_INET, &dst);
9126 				}
9127 				ip1dbg((" on interface %s\n",
9128 				    dst_ill->ill_name));
9129 				goto err_ret;
9130 			}
9131 			ipif_refrele(ipif);
9132 			ipif = src_ipif;
9133 			ipif_refhold(ipif);
9134 		}
9135 		if (src_ipif == NULL) {
9136 			src_ipif = ipif;
9137 			ipif_refhold(src_ipif);
9138 		}
9139 
9140 		/*
9141 		 * Assign a source address while we have the conn.
9142 		 * We can't have ip_wput_ire pick a source address when the
9143 		 * packet returns from arp since conn_unspec_src might be set
9144 		 * and we lose the conn when going through arp.
9145 		 */
9146 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9147 			ipha->ipha_src = src_ipif->ipif_src_addr;
9148 
9149 		/*
9150 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9151 		 * that the outgoing interface does not have an interface ire.
9152 		 */
9153 		if (CLASSD(ipha_dst) && (connp == NULL ||
9154 		    connp->conn_outgoing_ill == NULL) &&
9155 		    infop->ip_opt_ill_index == 0) {
9156 			/* ipif_to_ire returns an held ire */
9157 			ire = ipif_to_ire(ipif);
9158 			if (ire == NULL)
9159 				goto err_ret;
9160 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9161 				goto err_ret;
9162 			save_ire = ire;
9163 
9164 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9165 			    "flags %04x\n",
9166 			    (void *)ire, (void *)ipif, flags));
9167 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9168 			    (fire->ire_flags & RTF_MULTIRT)) {
9169 				/*
9170 				 * As requested by flags, an IRE_OFFSUBNET was
9171 				 * looked up on that interface. This ire has
9172 				 * RTF_MULTIRT flag, so the resolution loop will
9173 				 * be re-entered to resolve additional routes on
9174 				 * other interfaces. For that purpose, a copy of
9175 				 * the packet is performed at this point.
9176 				 */
9177 				fire->ire_last_used_time = lbolt;
9178 				copy_mp = copymsg(first_mp);
9179 				if (copy_mp) {
9180 					MULTIRT_DEBUG_TAG(copy_mp);
9181 				}
9182 			}
9183 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9184 			    (fire->ire_flags & RTF_SETSRC)) {
9185 				/*
9186 				 * As requested by flags, an IRE_OFFSUBET was
9187 				 * looked up on that interface. This ire has
9188 				 * RTF_SETSRC flag, so the source address of the
9189 				 * packet must be changed.
9190 				 */
9191 				ipha->ipha_src = fire->ire_src_addr;
9192 			}
9193 		} else {
9194 			/*
9195 			 * The only ways we can come here are:
9196 			 * 1) IP_BOUND_IF socket option is set
9197 			 * 2) SO_DONTROUTE socket option is set
9198 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9199 			 * In all cases, the new ire will not be added
9200 			 * into cache table.
9201 			 */
9202 			ASSERT(connp == NULL || connp->conn_dontroute ||
9203 			    connp->conn_outgoing_ill != NULL ||
9204 			    infop->ip_opt_ill_index != 0);
9205 			ire_marks |= IRE_MARK_NOADD;
9206 		}
9207 
9208 		switch (ipif->ipif_net_type) {
9209 		case IRE_IF_NORESOLVER: {
9210 			/* We have what we need to build an IRE_CACHE. */
9211 
9212 			if (dst_ill->ill_resolver_mp == NULL) {
9213 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9214 				    "for IRE_IF_NORESOLVER ire %p has "
9215 				    "no ill_resolver_mp\n",
9216 				    (void *)dst_ill, (void *)ire));
9217 				break;
9218 			}
9219 
9220 			/*
9221 			 * The new ire inherits the IRE_OFFSUBNET flags
9222 			 * and source address, if this was requested.
9223 			 */
9224 			ire = ire_create(
9225 			    (uchar_t *)&dst,		/* dest address */
9226 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9227 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9228 			    NULL,			/* gateway address */
9229 			    &ipif->ipif_mtu,
9230 			    NULL,			/* no src nce */
9231 			    dst_ill->ill_rq,		/* recv-from queue */
9232 			    dst_ill->ill_wq,		/* send-to queue */
9233 			    IRE_CACHE,
9234 			    src_ipif,
9235 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9236 			    (fire != NULL) ?		/* Parent handle */
9237 			    fire->ire_phandle : 0,
9238 			    (save_ire != NULL) ?	/* Interface handle */
9239 			    save_ire->ire_ihandle : 0,
9240 			    (fire != NULL) ?
9241 			    (fire->ire_flags &
9242 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9243 			    (save_ire == NULL ? &ire_uinfo_null :
9244 			    &save_ire->ire_uinfo),
9245 			    NULL,
9246 			    NULL,
9247 			    ipst);
9248 
9249 			if (ire == NULL) {
9250 				if (save_ire != NULL)
9251 					ire_refrele(save_ire);
9252 				break;
9253 			}
9254 
9255 			ire->ire_marks |= ire_marks;
9256 
9257 			/*
9258 			 * If IRE_MARK_NOADD is set then we need to convert
9259 			 * the max_fragp to a useable value now. This is
9260 			 * normally done in ire_add_v[46]. We also need to
9261 			 * associate the ire with an nce (normally would be
9262 			 * done in ip_wput_nondata()).
9263 			 *
9264 			 * Note that IRE_MARK_NOADD packets created here
9265 			 * do not have a non-null ire_mp pointer. The null
9266 			 * value of ire_bucket indicates that they were
9267 			 * never added.
9268 			 */
9269 			if (ire->ire_marks & IRE_MARK_NOADD) {
9270 				uint_t  max_frag;
9271 
9272 				max_frag = *ire->ire_max_fragp;
9273 				ire->ire_max_fragp = NULL;
9274 				ire->ire_max_frag = max_frag;
9275 
9276 				if ((ire->ire_nce = ndp_lookup_v4(
9277 				    ire_to_ill(ire),
9278 				    (ire->ire_gateway_addr != INADDR_ANY ?
9279 				    &ire->ire_gateway_addr : &ire->ire_addr),
9280 				    B_FALSE)) == NULL) {
9281 					if (save_ire != NULL)
9282 						ire_refrele(save_ire);
9283 					break;
9284 				}
9285 				ASSERT(ire->ire_nce->nce_state ==
9286 				    ND_REACHABLE);
9287 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9288 			}
9289 
9290 			/* Prevent save_ire from getting deleted */
9291 			if (save_ire != NULL) {
9292 				IRB_REFHOLD(save_ire->ire_bucket);
9293 				/* Has it been removed already ? */
9294 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9295 					IRB_REFRELE(save_ire->ire_bucket);
9296 					ire_refrele(save_ire);
9297 					break;
9298 				}
9299 			}
9300 
9301 			ire_add_then_send(q, ire, first_mp);
9302 
9303 			/* Assert that save_ire is not deleted yet. */
9304 			if (save_ire != NULL) {
9305 				ASSERT(save_ire->ire_ptpn != NULL);
9306 				IRB_REFRELE(save_ire->ire_bucket);
9307 				ire_refrele(save_ire);
9308 				save_ire = NULL;
9309 			}
9310 			if (fire != NULL) {
9311 				ire_refrele(fire);
9312 				fire = NULL;
9313 			}
9314 
9315 			/*
9316 			 * the resolution loop is re-entered if this
9317 			 * was requested through flags and if we
9318 			 * actually are in a multirouting case.
9319 			 */
9320 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9321 				boolean_t need_resolve =
9322 				    ire_multirt_need_resolve(ipha_dst,
9323 				    msg_getlabel(copy_mp), ipst);
9324 				if (!need_resolve) {
9325 					MULTIRT_DEBUG_UNTAG(copy_mp);
9326 					freemsg(copy_mp);
9327 					copy_mp = NULL;
9328 				} else {
9329 					/*
9330 					 * ipif_lookup_group() calls
9331 					 * ire_lookup_multi() that uses
9332 					 * ire_ftable_lookup() to find
9333 					 * an IRE_INTERFACE for the group.
9334 					 * In the multirt case,
9335 					 * ire_lookup_multi() then invokes
9336 					 * ire_multirt_lookup() to find
9337 					 * the next resolvable ire.
9338 					 * As a result, we obtain an new
9339 					 * interface, derived from the
9340 					 * next ire.
9341 					 */
9342 					ipif_refrele(ipif);
9343 					ipif = ipif_lookup_group(ipha_dst,
9344 					    zoneid, ipst);
9345 					ip2dbg(("ip_newroute_ipif: "
9346 					    "multirt dst %08x, ipif %p\n",
9347 					    htonl(dst), (void *)ipif));
9348 					if (ipif != NULL) {
9349 						mp = copy_mp;
9350 						copy_mp = NULL;
9351 						multirt_resolve_next = B_TRUE;
9352 						continue;
9353 					} else {
9354 						freemsg(copy_mp);
9355 					}
9356 				}
9357 			}
9358 			if (ipif != NULL)
9359 				ipif_refrele(ipif);
9360 			ill_refrele(dst_ill);
9361 			ipif_refrele(src_ipif);
9362 			return;
9363 		}
9364 		case IRE_IF_RESOLVER:
9365 			/*
9366 			 * We can't build an IRE_CACHE yet, but at least
9367 			 * we found a resolver that can help.
9368 			 */
9369 			res_mp = dst_ill->ill_resolver_mp;
9370 			if (!OK_RESOLVER_MP(res_mp))
9371 				break;
9372 
9373 			/*
9374 			 * We obtain a partial IRE_CACHE which we will pass
9375 			 * along with the resolver query.  When the response
9376 			 * comes back it will be there ready for us to add.
9377 			 * The new ire inherits the IRE_OFFSUBNET flags
9378 			 * and source address, if this was requested.
9379 			 * The ire_max_frag is atomically set under the
9380 			 * irebucket lock in ire_add_v[46]. Only in the
9381 			 * case of IRE_MARK_NOADD, we set it here itself.
9382 			 */
9383 			ire = ire_create_mp(
9384 			    (uchar_t *)&dst,		/* dest address */
9385 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9386 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9387 			    NULL,			/* gateway address */
9388 			    (ire_marks & IRE_MARK_NOADD) ?
9389 			    ipif->ipif_mtu : 0,		/* max_frag */
9390 			    NULL,			/* no src nce */
9391 			    dst_ill->ill_rq,		/* recv-from queue */
9392 			    dst_ill->ill_wq,		/* send-to queue */
9393 			    IRE_CACHE,
9394 			    src_ipif,
9395 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9396 			    (fire != NULL) ?		/* Parent handle */
9397 			    fire->ire_phandle : 0,
9398 			    (save_ire != NULL) ?	/* Interface handle */
9399 			    save_ire->ire_ihandle : 0,
9400 			    (fire != NULL) ?		/* flags if any */
9401 			    (fire->ire_flags &
9402 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9403 			    (save_ire == NULL ? &ire_uinfo_null :
9404 			    &save_ire->ire_uinfo),
9405 			    NULL,
9406 			    NULL,
9407 			    ipst);
9408 
9409 			if (save_ire != NULL) {
9410 				ire_refrele(save_ire);
9411 				save_ire = NULL;
9412 			}
9413 			if (ire == NULL)
9414 				break;
9415 
9416 			ire->ire_marks |= ire_marks;
9417 			/*
9418 			 * Construct message chain for the resolver of the
9419 			 * form:
9420 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9421 			 *
9422 			 * NOTE : ire will be added later when the response
9423 			 * comes back from ARP. If the response does not
9424 			 * come back, ARP frees the packet. For this reason,
9425 			 * we can't REFHOLD the bucket of save_ire to prevent
9426 			 * deletions. We may not be able to REFRELE the
9427 			 * bucket if the response never comes back.
9428 			 * Thus, before adding the ire, ire_add_v4 will make
9429 			 * sure that the interface route does not get deleted.
9430 			 * This is the only case unlike ip_newroute_v6,
9431 			 * ip_newroute_ipif_v6 where we can always prevent
9432 			 * deletions because ire_add_then_send is called after
9433 			 * creating the IRE.
9434 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9435 			 * does not add this IRE into the IRE CACHE.
9436 			 */
9437 			ASSERT(ire->ire_mp != NULL);
9438 			ire->ire_mp->b_cont = first_mp;
9439 			/* Have saved_mp handy, for cleanup if canput fails */
9440 			saved_mp = mp;
9441 			mp = copyb(res_mp);
9442 			if (mp == NULL) {
9443 				/* Prepare for cleanup */
9444 				mp = saved_mp; /* pkt */
9445 				ire_delete(ire); /* ire_mp */
9446 				ire = NULL;
9447 				if (copy_mp != NULL) {
9448 					MULTIRT_DEBUG_UNTAG(copy_mp);
9449 					freemsg(copy_mp);
9450 					copy_mp = NULL;
9451 				}
9452 				break;
9453 			}
9454 			linkb(mp, ire->ire_mp);
9455 
9456 			/*
9457 			 * Fill in the source and dest addrs for the resolver.
9458 			 * NOTE: this depends on memory layouts imposed by
9459 			 * ill_init().  There are corner cases above where we
9460 			 * might've created the IRE with an INADDR_ANY source
9461 			 * address (e.g., if the zeroth ipif on an underlying
9462 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9463 			 * on the ill has a usable test address).  If so, tell
9464 			 * ARP to use ipha_src as its sender address.
9465 			 */
9466 			areq = (areq_t *)mp->b_rptr;
9467 			addrp = (ipaddr_t *)((char *)areq +
9468 			    areq->areq_sender_addr_offset);
9469 			if (ire->ire_src_addr != INADDR_ANY)
9470 				*addrp = ire->ire_src_addr;
9471 			else
9472 				*addrp = ipha->ipha_src;
9473 			addrp = (ipaddr_t *)((char *)areq +
9474 			    areq->areq_target_addr_offset);
9475 			*addrp = dst;
9476 			/* Up to the resolver. */
9477 			if (canputnext(dst_ill->ill_rq) &&
9478 			    !(dst_ill->ill_arp_closing)) {
9479 				putnext(dst_ill->ill_rq, mp);
9480 				/*
9481 				 * The response will come back in ip_wput
9482 				 * with db_type IRE_DB_TYPE.
9483 				 */
9484 			} else {
9485 				mp->b_cont = NULL;
9486 				freeb(mp); /* areq */
9487 				ire_delete(ire); /* ire_mp */
9488 				saved_mp->b_next = NULL;
9489 				saved_mp->b_prev = NULL;
9490 				freemsg(first_mp); /* pkt */
9491 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9492 			}
9493 
9494 			if (fire != NULL) {
9495 				ire_refrele(fire);
9496 				fire = NULL;
9497 			}
9498 
9499 			/*
9500 			 * The resolution loop is re-entered if this was
9501 			 * requested through flags and we actually are
9502 			 * in a multirouting case.
9503 			 */
9504 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9505 				boolean_t need_resolve =
9506 				    ire_multirt_need_resolve(ipha_dst,
9507 				    msg_getlabel(copy_mp), ipst);
9508 				if (!need_resolve) {
9509 					MULTIRT_DEBUG_UNTAG(copy_mp);
9510 					freemsg(copy_mp);
9511 					copy_mp = NULL;
9512 				} else {
9513 					/*
9514 					 * ipif_lookup_group() calls
9515 					 * ire_lookup_multi() that uses
9516 					 * ire_ftable_lookup() to find
9517 					 * an IRE_INTERFACE for the group.
9518 					 * In the multirt case,
9519 					 * ire_lookup_multi() then invokes
9520 					 * ire_multirt_lookup() to find
9521 					 * the next resolvable ire.
9522 					 * As a result, we obtain an new
9523 					 * interface, derived from the
9524 					 * next ire.
9525 					 */
9526 					ipif_refrele(ipif);
9527 					ipif = ipif_lookup_group(ipha_dst,
9528 					    zoneid, ipst);
9529 					if (ipif != NULL) {
9530 						mp = copy_mp;
9531 						copy_mp = NULL;
9532 						multirt_resolve_next = B_TRUE;
9533 						continue;
9534 					} else {
9535 						freemsg(copy_mp);
9536 					}
9537 				}
9538 			}
9539 			if (ipif != NULL)
9540 				ipif_refrele(ipif);
9541 			ill_refrele(dst_ill);
9542 			ipif_refrele(src_ipif);
9543 			return;
9544 		default:
9545 			break;
9546 		}
9547 	} while (multirt_resolve_next);
9548 
9549 err_ret:
9550 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9551 	if (fire != NULL)
9552 		ire_refrele(fire);
9553 	ipif_refrele(ipif);
9554 	/* Did this packet originate externally? */
9555 	if (dst_ill != NULL)
9556 		ill_refrele(dst_ill);
9557 	if (src_ipif != NULL)
9558 		ipif_refrele(src_ipif);
9559 	if (mp->b_prev || mp->b_next) {
9560 		mp->b_next = NULL;
9561 		mp->b_prev = NULL;
9562 	} else {
9563 		/*
9564 		 * Since ip_wput() isn't close to finished, we fill
9565 		 * in enough of the header for credible error reporting.
9566 		 */
9567 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9568 			/* Failed */
9569 			freemsg(first_mp);
9570 			if (ire != NULL)
9571 				ire_refrele(ire);
9572 			return;
9573 		}
9574 	}
9575 	/*
9576 	 * At this point we will have ire only if RTF_BLACKHOLE
9577 	 * or RTF_REJECT flags are set on the IRE. It will not
9578 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9579 	 */
9580 	if (ire != NULL) {
9581 		if (ire->ire_flags & RTF_BLACKHOLE) {
9582 			ire_refrele(ire);
9583 			freemsg(first_mp);
9584 			return;
9585 		}
9586 		ire_refrele(ire);
9587 	}
9588 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9589 }
9590 
9591 /* Name/Value Table Lookup Routine */
9592 char *
9593 ip_nv_lookup(nv_t *nv, int value)
9594 {
9595 	if (!nv)
9596 		return (NULL);
9597 	for (; nv->nv_name; nv++) {
9598 		if (nv->nv_value == value)
9599 			return (nv->nv_name);
9600 	}
9601 	return ("unknown");
9602 }
9603 
9604 /*
9605  * This is a module open, i.e. this is a control stream for access
9606  * to a DLPI device.  We allocate an ill_t as the instance data in
9607  * this case.
9608  */
9609 int
9610 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9611 {
9612 	ill_t	*ill;
9613 	int	err;
9614 	zoneid_t zoneid;
9615 	netstack_t *ns;
9616 	ip_stack_t *ipst;
9617 
9618 	/*
9619 	 * Prevent unprivileged processes from pushing IP so that
9620 	 * they can't send raw IP.
9621 	 */
9622 	if (secpolicy_net_rawaccess(credp) != 0)
9623 		return (EPERM);
9624 
9625 	ns = netstack_find_by_cred(credp);
9626 	ASSERT(ns != NULL);
9627 	ipst = ns->netstack_ip;
9628 	ASSERT(ipst != NULL);
9629 
9630 	/*
9631 	 * For exclusive stacks we set the zoneid to zero
9632 	 * to make IP operate as if in the global zone.
9633 	 */
9634 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9635 		zoneid = GLOBAL_ZONEID;
9636 	else
9637 		zoneid = crgetzoneid(credp);
9638 
9639 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9640 	q->q_ptr = WR(q)->q_ptr = ill;
9641 	ill->ill_ipst = ipst;
9642 	ill->ill_zoneid = zoneid;
9643 
9644 	/*
9645 	 * ill_init initializes the ill fields and then sends down
9646 	 * down a DL_INFO_REQ after calling qprocson.
9647 	 */
9648 	err = ill_init(q, ill);
9649 	if (err != 0) {
9650 		mi_free(ill);
9651 		netstack_rele(ipst->ips_netstack);
9652 		q->q_ptr = NULL;
9653 		WR(q)->q_ptr = NULL;
9654 		return (err);
9655 	}
9656 
9657 	/* ill_init initializes the ipsq marking this thread as writer */
9658 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9659 	/* Wait for the DL_INFO_ACK */
9660 	mutex_enter(&ill->ill_lock);
9661 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9662 		/*
9663 		 * Return value of 0 indicates a pending signal.
9664 		 */
9665 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9666 		if (err == 0) {
9667 			mutex_exit(&ill->ill_lock);
9668 			(void) ip_close(q, 0);
9669 			return (EINTR);
9670 		}
9671 	}
9672 	mutex_exit(&ill->ill_lock);
9673 
9674 	/*
9675 	 * ip_rput_other could have set an error  in ill_error on
9676 	 * receipt of M_ERROR.
9677 	 */
9678 
9679 	err = ill->ill_error;
9680 	if (err != 0) {
9681 		(void) ip_close(q, 0);
9682 		return (err);
9683 	}
9684 
9685 	ill->ill_credp = credp;
9686 	crhold(credp);
9687 
9688 	mutex_enter(&ipst->ips_ip_mi_lock);
9689 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9690 	    credp);
9691 	mutex_exit(&ipst->ips_ip_mi_lock);
9692 	if (err) {
9693 		(void) ip_close(q, 0);
9694 		return (err);
9695 	}
9696 	return (0);
9697 }
9698 
9699 /* For /dev/ip aka AF_INET open */
9700 int
9701 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9702 {
9703 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9704 }
9705 
9706 /* For /dev/ip6 aka AF_INET6 open */
9707 int
9708 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9709 {
9710 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9711 }
9712 
9713 /* IP open routine. */
9714 int
9715 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9716     boolean_t isv6)
9717 {
9718 	conn_t 		*connp;
9719 	major_t		maj;
9720 	zoneid_t	zoneid;
9721 	netstack_t	*ns;
9722 	ip_stack_t	*ipst;
9723 
9724 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9725 
9726 	/* Allow reopen. */
9727 	if (q->q_ptr != NULL)
9728 		return (0);
9729 
9730 	if (sflag & MODOPEN) {
9731 		/* This is a module open */
9732 		return (ip_modopen(q, devp, flag, sflag, credp));
9733 	}
9734 
9735 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9736 		/*
9737 		 * Non streams based socket looking for a stream
9738 		 * to access IP
9739 		 */
9740 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9741 		    credp, isv6));
9742 	}
9743 
9744 	ns = netstack_find_by_cred(credp);
9745 	ASSERT(ns != NULL);
9746 	ipst = ns->netstack_ip;
9747 	ASSERT(ipst != NULL);
9748 
9749 	/*
9750 	 * For exclusive stacks we set the zoneid to zero
9751 	 * to make IP operate as if in the global zone.
9752 	 */
9753 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9754 		zoneid = GLOBAL_ZONEID;
9755 	else
9756 		zoneid = crgetzoneid(credp);
9757 
9758 	/*
9759 	 * We are opening as a device. This is an IP client stream, and we
9760 	 * allocate an conn_t as the instance data.
9761 	 */
9762 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9763 
9764 	/*
9765 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9766 	 * done by netstack_find_by_cred()
9767 	 */
9768 	netstack_rele(ipst->ips_netstack);
9769 
9770 	connp->conn_zoneid = zoneid;
9771 	connp->conn_sqp = NULL;
9772 	connp->conn_initial_sqp = NULL;
9773 	connp->conn_final_sqp = NULL;
9774 
9775 	connp->conn_upq = q;
9776 	q->q_ptr = WR(q)->q_ptr = connp;
9777 
9778 	if (flag & SO_SOCKSTR)
9779 		connp->conn_flags |= IPCL_SOCKET;
9780 
9781 	/* Minor tells us which /dev entry was opened */
9782 	if (isv6) {
9783 		connp->conn_af_isv6 = B_TRUE;
9784 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9785 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9786 	} else {
9787 		connp->conn_af_isv6 = B_FALSE;
9788 		connp->conn_pkt_isv6 = B_FALSE;
9789 	}
9790 
9791 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9792 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9793 		connp->conn_minor_arena = ip_minor_arena_la;
9794 	} else {
9795 		/*
9796 		 * Either minor numbers in the large arena were exhausted
9797 		 * or a non socket application is doing the open.
9798 		 * Try to allocate from the small arena.
9799 		 */
9800 		if ((connp->conn_dev =
9801 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9802 			/* CONN_DEC_REF takes care of netstack_rele() */
9803 			q->q_ptr = WR(q)->q_ptr = NULL;
9804 			CONN_DEC_REF(connp);
9805 			return (EBUSY);
9806 		}
9807 		connp->conn_minor_arena = ip_minor_arena_sa;
9808 	}
9809 
9810 	maj = getemajor(*devp);
9811 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9812 
9813 	/*
9814 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9815 	 */
9816 	connp->conn_cred = credp;
9817 
9818 	/*
9819 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9820 	 */
9821 	connp->conn_recv = ip_conn_input;
9822 
9823 	crhold(connp->conn_cred);
9824 
9825 	/*
9826 	 * If the caller has the process-wide flag set, then default to MAC
9827 	 * exempt mode.  This allows read-down to unlabeled hosts.
9828 	 */
9829 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9830 		connp->conn_mac_exempt = B_TRUE;
9831 
9832 	connp->conn_rq = q;
9833 	connp->conn_wq = WR(q);
9834 
9835 	/* Non-zero default values */
9836 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9837 
9838 	/*
9839 	 * Make the conn globally visible to walkers
9840 	 */
9841 	ASSERT(connp->conn_ref == 1);
9842 	mutex_enter(&connp->conn_lock);
9843 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9844 	mutex_exit(&connp->conn_lock);
9845 
9846 	qprocson(q);
9847 
9848 	return (0);
9849 }
9850 
9851 /*
9852  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9853  * Note that there is no race since either ip_output function works - it
9854  * is just an optimization to enter the best ip_output routine directly.
9855  */
9856 void
9857 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9858     ip_stack_t *ipst)
9859 {
9860 	if (isv6)  {
9861 		if (bump_mib) {
9862 			BUMP_MIB(&ipst->ips_ip6_mib,
9863 			    ipIfStatsOutSwitchIPVersion);
9864 		}
9865 		connp->conn_send = ip_output_v6;
9866 		connp->conn_pkt_isv6 = B_TRUE;
9867 	} else {
9868 		if (bump_mib) {
9869 			BUMP_MIB(&ipst->ips_ip_mib,
9870 			    ipIfStatsOutSwitchIPVersion);
9871 		}
9872 		connp->conn_send = ip_output;
9873 		connp->conn_pkt_isv6 = B_FALSE;
9874 	}
9875 
9876 }
9877 
9878 /*
9879  * See if IPsec needs loading because of the options in mp.
9880  */
9881 static boolean_t
9882 ipsec_opt_present(mblk_t *mp)
9883 {
9884 	uint8_t *optcp, *next_optcp, *opt_endcp;
9885 	struct opthdr *opt;
9886 	struct T_opthdr *topt;
9887 	int opthdr_len;
9888 	t_uscalar_t optname, optlevel;
9889 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9890 	ipsec_req_t *ipsr;
9891 
9892 	/*
9893 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9894 	 * return TRUE.
9895 	 */
9896 
9897 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9898 	opt_endcp = optcp + tor->OPT_length;
9899 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9900 		opthdr_len = sizeof (struct T_opthdr);
9901 	} else {		/* O_OPTMGMT_REQ */
9902 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9903 		opthdr_len = sizeof (struct opthdr);
9904 	}
9905 	for (; optcp < opt_endcp; optcp = next_optcp) {
9906 		if (optcp + opthdr_len > opt_endcp)
9907 			return (B_FALSE);	/* Not enough option header. */
9908 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9909 			topt = (struct T_opthdr *)optcp;
9910 			optlevel = topt->level;
9911 			optname = topt->name;
9912 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9913 		} else {
9914 			opt = (struct opthdr *)optcp;
9915 			optlevel = opt->level;
9916 			optname = opt->name;
9917 			next_optcp = optcp + opthdr_len +
9918 			    _TPI_ALIGN_OPT(opt->len);
9919 		}
9920 		if ((next_optcp < optcp) || /* wraparound pointer space */
9921 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9922 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9923 			return (B_FALSE); /* bad option buffer */
9924 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9925 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9926 			/*
9927 			 * Check to see if it's an all-bypass or all-zeroes
9928 			 * IPsec request.  Don't bother loading IPsec if
9929 			 * the socket doesn't want to use it.  (A good example
9930 			 * is a bypass request.)
9931 			 *
9932 			 * Basically, if any of the non-NEVER bits are set,
9933 			 * load IPsec.
9934 			 */
9935 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9936 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9937 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9938 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9939 			    != 0)
9940 				return (B_TRUE);
9941 		}
9942 	}
9943 	return (B_FALSE);
9944 }
9945 
9946 /*
9947  * If conn is is waiting for ipsec to finish loading, kick it.
9948  */
9949 /* ARGSUSED */
9950 static void
9951 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9952 {
9953 	t_scalar_t	optreq_prim;
9954 	mblk_t		*mp;
9955 	cred_t		*cr;
9956 	int		err = 0;
9957 
9958 	/*
9959 	 * This function is called, after ipsec loading is complete.
9960 	 * Since IP checks exclusively and atomically (i.e it prevents
9961 	 * ipsec load from completing until ip_optcom_req completes)
9962 	 * whether ipsec load is complete, there cannot be a race with IP
9963 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9964 	 */
9965 	mutex_enter(&connp->conn_lock);
9966 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9967 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9968 		mp = connp->conn_ipsec_opt_mp;
9969 		connp->conn_ipsec_opt_mp = NULL;
9970 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9971 		mutex_exit(&connp->conn_lock);
9972 
9973 		/*
9974 		 * All Solaris components should pass a db_credp
9975 		 * for this TPI message, hence we ASSERT.
9976 		 * But in case there is some other M_PROTO that looks
9977 		 * like a TPI message sent by some other kernel
9978 		 * component, we check and return an error.
9979 		 */
9980 		cr = msg_getcred(mp, NULL);
9981 		ASSERT(cr != NULL);
9982 		if (cr == NULL) {
9983 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
9984 			if (mp != NULL)
9985 				qreply(connp->conn_wq, mp);
9986 			return;
9987 		}
9988 
9989 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9990 
9991 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9992 		if (optreq_prim == T_OPTMGMT_REQ) {
9993 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9994 			    &ip_opt_obj, B_FALSE);
9995 		} else {
9996 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9997 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9998 			    &ip_opt_obj, B_FALSE);
9999 		}
10000 		if (err != EINPROGRESS)
10001 			CONN_OPER_PENDING_DONE(connp);
10002 		return;
10003 	}
10004 	mutex_exit(&connp->conn_lock);
10005 }
10006 
10007 /*
10008  * Called from the ipsec_loader thread, outside any perimeter, to tell
10009  * ip qenable any of the queues waiting for the ipsec loader to
10010  * complete.
10011  */
10012 void
10013 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10014 {
10015 	netstack_t *ns = ipss->ipsec_netstack;
10016 
10017 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10018 }
10019 
10020 /*
10021  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10022  * determines the grp on which it has to become exclusive, queues the mp
10023  * and IPSQ draining restarts the optmgmt
10024  */
10025 static boolean_t
10026 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10027 {
10028 	conn_t *connp = Q_TO_CONN(q);
10029 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10030 
10031 	/*
10032 	 * Take IPsec requests and treat them special.
10033 	 */
10034 	if (ipsec_opt_present(mp)) {
10035 		/* First check if IPsec is loaded. */
10036 		mutex_enter(&ipss->ipsec_loader_lock);
10037 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10038 			mutex_exit(&ipss->ipsec_loader_lock);
10039 			return (B_FALSE);
10040 		}
10041 		mutex_enter(&connp->conn_lock);
10042 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10043 
10044 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10045 		connp->conn_ipsec_opt_mp = mp;
10046 		mutex_exit(&connp->conn_lock);
10047 		mutex_exit(&ipss->ipsec_loader_lock);
10048 
10049 		ipsec_loader_loadnow(ipss);
10050 		return (B_TRUE);
10051 	}
10052 	return (B_FALSE);
10053 }
10054 
10055 /*
10056  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10057  * all of them are copied to the conn_t. If the req is "zero", the policy is
10058  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10059  * fields.
10060  * We keep only the latest setting of the policy and thus policy setting
10061  * is not incremental/cumulative.
10062  *
10063  * Requests to set policies with multiple alternative actions will
10064  * go through a different API.
10065  */
10066 int
10067 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10068 {
10069 	uint_t ah_req = 0;
10070 	uint_t esp_req = 0;
10071 	uint_t se_req = 0;
10072 	ipsec_act_t *actp = NULL;
10073 	uint_t nact;
10074 	ipsec_policy_head_t *ph;
10075 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
10076 	int error = 0;
10077 	netstack_t	*ns = connp->conn_netstack;
10078 	ip_stack_t	*ipst = ns->netstack_ip;
10079 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10080 
10081 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10082 
10083 	/*
10084 	 * The IP_SEC_OPT option does not allow variable length parameters,
10085 	 * hence a request cannot be NULL.
10086 	 */
10087 	if (req == NULL)
10088 		return (EINVAL);
10089 
10090 	ah_req = req->ipsr_ah_req;
10091 	esp_req = req->ipsr_esp_req;
10092 	se_req = req->ipsr_self_encap_req;
10093 
10094 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10095 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10096 		return (EINVAL);
10097 
10098 	/*
10099 	 * Are we dealing with a request to reset the policy (i.e.
10100 	 * zero requests).
10101 	 */
10102 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10103 	    (esp_req & REQ_MASK) == 0 &&
10104 	    (se_req & REQ_MASK) == 0);
10105 
10106 	if (!is_pol_reset) {
10107 		/*
10108 		 * If we couldn't load IPsec, fail with "protocol
10109 		 * not supported".
10110 		 * IPsec may not have been loaded for a request with zero
10111 		 * policies, so we don't fail in this case.
10112 		 */
10113 		mutex_enter(&ipss->ipsec_loader_lock);
10114 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10115 			mutex_exit(&ipss->ipsec_loader_lock);
10116 			return (EPROTONOSUPPORT);
10117 		}
10118 		mutex_exit(&ipss->ipsec_loader_lock);
10119 
10120 		/*
10121 		 * Test for valid requests. Invalid algorithms
10122 		 * need to be tested by IPsec code because new
10123 		 * algorithms can be added dynamically.
10124 		 */
10125 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10126 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10127 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10128 			return (EINVAL);
10129 		}
10130 
10131 		/*
10132 		 * Only privileged users can issue these
10133 		 * requests.
10134 		 */
10135 		if (((ah_req & IPSEC_PREF_NEVER) ||
10136 		    (esp_req & IPSEC_PREF_NEVER) ||
10137 		    (se_req & IPSEC_PREF_NEVER)) &&
10138 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10139 			return (EPERM);
10140 		}
10141 
10142 		/*
10143 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10144 		 * are mutually exclusive.
10145 		 */
10146 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10147 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10148 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10149 			/* Both of them are set */
10150 			return (EINVAL);
10151 		}
10152 	}
10153 
10154 	mutex_enter(&connp->conn_lock);
10155 
10156 	/*
10157 	 * If we have already cached policies in ip_bind_connected*(), don't
10158 	 * let them change now. We cache policies for connections
10159 	 * whose src,dst [addr, port] is known.
10160 	 */
10161 	if (connp->conn_policy_cached) {
10162 		mutex_exit(&connp->conn_lock);
10163 		return (EINVAL);
10164 	}
10165 
10166 	/*
10167 	 * We have a zero policies, reset the connection policy if already
10168 	 * set. This will cause the connection to inherit the
10169 	 * global policy, if any.
10170 	 */
10171 	if (is_pol_reset) {
10172 		if (connp->conn_policy != NULL) {
10173 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10174 			connp->conn_policy = NULL;
10175 		}
10176 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10177 		connp->conn_in_enforce_policy = B_FALSE;
10178 		connp->conn_out_enforce_policy = B_FALSE;
10179 		mutex_exit(&connp->conn_lock);
10180 		return (0);
10181 	}
10182 
10183 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10184 	    ipst->ips_netstack);
10185 	if (ph == NULL)
10186 		goto enomem;
10187 
10188 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10189 	if (actp == NULL)
10190 		goto enomem;
10191 
10192 	/*
10193 	 * Always insert IPv4 policy entries, since they can also apply to
10194 	 * ipv6 sockets being used in ipv4-compat mode.
10195 	 */
10196 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10197 	    IPSEC_TYPE_INBOUND, ns))
10198 		goto enomem;
10199 	is_pol_inserted = B_TRUE;
10200 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10201 	    IPSEC_TYPE_OUTBOUND, ns))
10202 		goto enomem;
10203 
10204 	/*
10205 	 * We're looking at a v6 socket, also insert the v6-specific
10206 	 * entries.
10207 	 */
10208 	if (connp->conn_af_isv6) {
10209 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10210 		    IPSEC_TYPE_INBOUND, ns))
10211 			goto enomem;
10212 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10213 		    IPSEC_TYPE_OUTBOUND, ns))
10214 			goto enomem;
10215 	}
10216 
10217 	ipsec_actvec_free(actp, nact);
10218 
10219 	/*
10220 	 * If the requests need security, set enforce_policy.
10221 	 * If the requests are IPSEC_PREF_NEVER, one should
10222 	 * still set conn_out_enforce_policy so that an ipsec_out
10223 	 * gets attached in ip_wput. This is needed so that
10224 	 * for connections that we don't cache policy in ip_bind,
10225 	 * if global policy matches in ip_wput_attach_policy, we
10226 	 * don't wrongly inherit global policy. Similarly, we need
10227 	 * to set conn_in_enforce_policy also so that we don't verify
10228 	 * policy wrongly.
10229 	 */
10230 	if ((ah_req & REQ_MASK) != 0 ||
10231 	    (esp_req & REQ_MASK) != 0 ||
10232 	    (se_req & REQ_MASK) != 0) {
10233 		connp->conn_in_enforce_policy = B_TRUE;
10234 		connp->conn_out_enforce_policy = B_TRUE;
10235 		connp->conn_flags |= IPCL_CHECK_POLICY;
10236 	}
10237 
10238 	mutex_exit(&connp->conn_lock);
10239 	return (error);
10240 #undef REQ_MASK
10241 
10242 	/*
10243 	 * Common memory-allocation-failure exit path.
10244 	 */
10245 enomem:
10246 	mutex_exit(&connp->conn_lock);
10247 	if (actp != NULL)
10248 		ipsec_actvec_free(actp, nact);
10249 	if (is_pol_inserted)
10250 		ipsec_polhead_flush(ph, ns);
10251 	return (ENOMEM);
10252 }
10253 
10254 /*
10255  * Only for options that pass in an IP addr. Currently only V4 options
10256  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10257  * So this function assumes level is IPPROTO_IP
10258  */
10259 int
10260 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10261     mblk_t *first_mp)
10262 {
10263 	ipif_t *ipif = NULL;
10264 	int error;
10265 	ill_t *ill;
10266 	int zoneid;
10267 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10268 
10269 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10270 
10271 	if (addr != INADDR_ANY || checkonly) {
10272 		ASSERT(connp != NULL);
10273 		zoneid = IPCL_ZONEID(connp);
10274 		if (option == IP_NEXTHOP) {
10275 			ipif = ipif_lookup_onlink_addr(addr,
10276 			    connp->conn_zoneid, ipst);
10277 		} else {
10278 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10279 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10280 			    &error, ipst);
10281 		}
10282 		if (ipif == NULL) {
10283 			if (error == EINPROGRESS)
10284 				return (error);
10285 			if ((option == IP_MULTICAST_IF) ||
10286 			    (option == IP_NEXTHOP))
10287 				return (EHOSTUNREACH);
10288 			else
10289 				return (EINVAL);
10290 		} else if (checkonly) {
10291 			if (option == IP_MULTICAST_IF) {
10292 				ill = ipif->ipif_ill;
10293 				/* not supported by the virtual network iface */
10294 				if (IS_VNI(ill)) {
10295 					ipif_refrele(ipif);
10296 					return (EINVAL);
10297 				}
10298 			}
10299 			ipif_refrele(ipif);
10300 			return (0);
10301 		}
10302 		ill = ipif->ipif_ill;
10303 		mutex_enter(&connp->conn_lock);
10304 		mutex_enter(&ill->ill_lock);
10305 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10306 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10307 			mutex_exit(&ill->ill_lock);
10308 			mutex_exit(&connp->conn_lock);
10309 			ipif_refrele(ipif);
10310 			return (option == IP_MULTICAST_IF ?
10311 			    EHOSTUNREACH : EINVAL);
10312 		}
10313 	} else {
10314 		mutex_enter(&connp->conn_lock);
10315 	}
10316 
10317 	/* None of the options below are supported on the VNI */
10318 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10319 		mutex_exit(&ill->ill_lock);
10320 		mutex_exit(&connp->conn_lock);
10321 		ipif_refrele(ipif);
10322 		return (EINVAL);
10323 	}
10324 
10325 	switch (option) {
10326 	case IP_MULTICAST_IF:
10327 		connp->conn_multicast_ipif = ipif;
10328 		break;
10329 	case IP_NEXTHOP:
10330 		connp->conn_nexthop_v4 = addr;
10331 		connp->conn_nexthop_set = B_TRUE;
10332 		break;
10333 	}
10334 
10335 	if (ipif != NULL) {
10336 		mutex_exit(&ill->ill_lock);
10337 		mutex_exit(&connp->conn_lock);
10338 		ipif_refrele(ipif);
10339 		return (0);
10340 	}
10341 	mutex_exit(&connp->conn_lock);
10342 	/* We succeded in cleared the option */
10343 	return (0);
10344 }
10345 
10346 /*
10347  * For options that pass in an ifindex specifying the ill. V6 options always
10348  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10349  */
10350 int
10351 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10352     int level, int option, mblk_t *first_mp)
10353 {
10354 	ill_t *ill = NULL;
10355 	int error = 0;
10356 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10357 
10358 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10359 	if (ifindex != 0) {
10360 		ASSERT(connp != NULL);
10361 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10362 		    first_mp, ip_restart_optmgmt, &error, ipst);
10363 		if (ill != NULL) {
10364 			if (checkonly) {
10365 				/* not supported by the virtual network iface */
10366 				if (IS_VNI(ill)) {
10367 					ill_refrele(ill);
10368 					return (EINVAL);
10369 				}
10370 				ill_refrele(ill);
10371 				return (0);
10372 			}
10373 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10374 			    0, NULL)) {
10375 				ill_refrele(ill);
10376 				ill = NULL;
10377 				mutex_enter(&connp->conn_lock);
10378 				goto setit;
10379 			}
10380 			mutex_enter(&connp->conn_lock);
10381 			mutex_enter(&ill->ill_lock);
10382 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10383 				mutex_exit(&ill->ill_lock);
10384 				mutex_exit(&connp->conn_lock);
10385 				ill_refrele(ill);
10386 				ill = NULL;
10387 				mutex_enter(&connp->conn_lock);
10388 			}
10389 			goto setit;
10390 		} else if (error == EINPROGRESS) {
10391 			return (error);
10392 		} else {
10393 			error = 0;
10394 		}
10395 	}
10396 	mutex_enter(&connp->conn_lock);
10397 setit:
10398 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10399 
10400 	/*
10401 	 * The options below assume that the ILL (if any) transmits and/or
10402 	 * receives traffic. Neither of which is true for the virtual network
10403 	 * interface, so fail setting these on a VNI.
10404 	 */
10405 	if (IS_VNI(ill)) {
10406 		ASSERT(ill != NULL);
10407 		mutex_exit(&ill->ill_lock);
10408 		mutex_exit(&connp->conn_lock);
10409 		ill_refrele(ill);
10410 		return (EINVAL);
10411 	}
10412 
10413 	if (level == IPPROTO_IP) {
10414 		switch (option) {
10415 		case IP_BOUND_IF:
10416 			connp->conn_incoming_ill = ill;
10417 			connp->conn_outgoing_ill = ill;
10418 			break;
10419 
10420 		case IP_MULTICAST_IF:
10421 			/*
10422 			 * This option is an internal special. The socket
10423 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10424 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10425 			 * specifies an ifindex and we try first on V6 ill's.
10426 			 * If we don't find one, we they try using on v4 ill's
10427 			 * intenally and we come here.
10428 			 */
10429 			if (!checkonly && ill != NULL) {
10430 				ipif_t	*ipif;
10431 				ipif = ill->ill_ipif;
10432 
10433 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10434 					mutex_exit(&ill->ill_lock);
10435 					mutex_exit(&connp->conn_lock);
10436 					ill_refrele(ill);
10437 					ill = NULL;
10438 					mutex_enter(&connp->conn_lock);
10439 				} else {
10440 					connp->conn_multicast_ipif = ipif;
10441 				}
10442 			}
10443 			break;
10444 
10445 		case IP_DHCPINIT_IF:
10446 			if (connp->conn_dhcpinit_ill != NULL) {
10447 				/*
10448 				 * We've locked the conn so conn_cleanup_ill()
10449 				 * cannot clear conn_dhcpinit_ill -- so it's
10450 				 * safe to access the ill.
10451 				 */
10452 				ill_t *oill = connp->conn_dhcpinit_ill;
10453 
10454 				ASSERT(oill->ill_dhcpinit != 0);
10455 				atomic_dec_32(&oill->ill_dhcpinit);
10456 				connp->conn_dhcpinit_ill = NULL;
10457 			}
10458 
10459 			if (ill != NULL) {
10460 				connp->conn_dhcpinit_ill = ill;
10461 				atomic_inc_32(&ill->ill_dhcpinit);
10462 			}
10463 			break;
10464 		}
10465 	} else {
10466 		switch (option) {
10467 		case IPV6_BOUND_IF:
10468 			connp->conn_incoming_ill = ill;
10469 			connp->conn_outgoing_ill = ill;
10470 			break;
10471 
10472 		case IPV6_MULTICAST_IF:
10473 			/*
10474 			 * Set conn_multicast_ill to be the IPv6 ill.
10475 			 * Set conn_multicast_ipif to be an IPv4 ipif
10476 			 * for ifindex to make IPv4 mapped addresses
10477 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10478 			 * Even if no IPv6 ill exists for the ifindex
10479 			 * we need to check for an IPv4 ifindex in order
10480 			 * for this to work with mapped addresses. In that
10481 			 * case only set conn_multicast_ipif.
10482 			 */
10483 			if (!checkonly) {
10484 				if (ifindex == 0) {
10485 					connp->conn_multicast_ill = NULL;
10486 					connp->conn_multicast_ipif = NULL;
10487 				} else if (ill != NULL) {
10488 					connp->conn_multicast_ill = ill;
10489 				}
10490 			}
10491 			break;
10492 		}
10493 	}
10494 
10495 	if (ill != NULL) {
10496 		mutex_exit(&ill->ill_lock);
10497 		mutex_exit(&connp->conn_lock);
10498 		ill_refrele(ill);
10499 		return (0);
10500 	}
10501 	mutex_exit(&connp->conn_lock);
10502 	/*
10503 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10504 	 * locate the ill and could not set the option (ifindex != 0)
10505 	 */
10506 	return (ifindex == 0 ? 0 : EINVAL);
10507 }
10508 
10509 /* This routine sets socket options. */
10510 /* ARGSUSED */
10511 int
10512 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10513     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10514     void *dummy, cred_t *cr, mblk_t *first_mp)
10515 {
10516 	int		*i1 = (int *)invalp;
10517 	conn_t		*connp = Q_TO_CONN(q);
10518 	int		error = 0;
10519 	boolean_t	checkonly;
10520 	ire_t		*ire;
10521 	boolean_t	found;
10522 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10523 
10524 	switch (optset_context) {
10525 
10526 	case SETFN_OPTCOM_CHECKONLY:
10527 		checkonly = B_TRUE;
10528 		/*
10529 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10530 		 * inlen != 0 implies value supplied and
10531 		 * 	we have to "pretend" to set it.
10532 		 * inlen == 0 implies that there is no
10533 		 * 	value part in T_CHECK request and just validation
10534 		 * done elsewhere should be enough, we just return here.
10535 		 */
10536 		if (inlen == 0) {
10537 			*outlenp = 0;
10538 			return (0);
10539 		}
10540 		break;
10541 	case SETFN_OPTCOM_NEGOTIATE:
10542 	case SETFN_UD_NEGOTIATE:
10543 	case SETFN_CONN_NEGOTIATE:
10544 		checkonly = B_FALSE;
10545 		break;
10546 	default:
10547 		/*
10548 		 * We should never get here
10549 		 */
10550 		*outlenp = 0;
10551 		return (EINVAL);
10552 	}
10553 
10554 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10555 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10556 
10557 	/*
10558 	 * For fixed length options, no sanity check
10559 	 * of passed in length is done. It is assumed *_optcom_req()
10560 	 * routines do the right thing.
10561 	 */
10562 
10563 	switch (level) {
10564 	case SOL_SOCKET:
10565 		/*
10566 		 * conn_lock protects the bitfields, and is used to
10567 		 * set the fields atomically.
10568 		 */
10569 		switch (name) {
10570 		case SO_BROADCAST:
10571 			if (!checkonly) {
10572 				/* TODO: use value someplace? */
10573 				mutex_enter(&connp->conn_lock);
10574 				connp->conn_broadcast = *i1 ? 1 : 0;
10575 				mutex_exit(&connp->conn_lock);
10576 			}
10577 			break;	/* goto sizeof (int) option return */
10578 		case SO_USELOOPBACK:
10579 			if (!checkonly) {
10580 				/* TODO: use value someplace? */
10581 				mutex_enter(&connp->conn_lock);
10582 				connp->conn_loopback = *i1 ? 1 : 0;
10583 				mutex_exit(&connp->conn_lock);
10584 			}
10585 			break;	/* goto sizeof (int) option return */
10586 		case SO_DONTROUTE:
10587 			if (!checkonly) {
10588 				mutex_enter(&connp->conn_lock);
10589 				connp->conn_dontroute = *i1 ? 1 : 0;
10590 				mutex_exit(&connp->conn_lock);
10591 			}
10592 			break;	/* goto sizeof (int) option return */
10593 		case SO_REUSEADDR:
10594 			if (!checkonly) {
10595 				mutex_enter(&connp->conn_lock);
10596 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10597 				mutex_exit(&connp->conn_lock);
10598 			}
10599 			break;	/* goto sizeof (int) option return */
10600 		case SO_PROTOTYPE:
10601 			if (!checkonly) {
10602 				mutex_enter(&connp->conn_lock);
10603 				connp->conn_proto = *i1;
10604 				mutex_exit(&connp->conn_lock);
10605 			}
10606 			break;	/* goto sizeof (int) option return */
10607 		case SO_ALLZONES:
10608 			if (!checkonly) {
10609 				mutex_enter(&connp->conn_lock);
10610 				if (IPCL_IS_BOUND(connp)) {
10611 					mutex_exit(&connp->conn_lock);
10612 					return (EINVAL);
10613 				}
10614 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10615 				mutex_exit(&connp->conn_lock);
10616 			}
10617 			break;	/* goto sizeof (int) option return */
10618 		case SO_ANON_MLP:
10619 			if (!checkonly) {
10620 				mutex_enter(&connp->conn_lock);
10621 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10622 				mutex_exit(&connp->conn_lock);
10623 			}
10624 			break;	/* goto sizeof (int) option return */
10625 		case SO_MAC_EXEMPT:
10626 			if (secpolicy_net_mac_aware(cr) != 0 ||
10627 			    IPCL_IS_BOUND(connp))
10628 				return (EACCES);
10629 			if (!checkonly) {
10630 				mutex_enter(&connp->conn_lock);
10631 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10632 				mutex_exit(&connp->conn_lock);
10633 			}
10634 			break;	/* goto sizeof (int) option return */
10635 		default:
10636 			/*
10637 			 * "soft" error (negative)
10638 			 * option not handled at this level
10639 			 * Note: Do not modify *outlenp
10640 			 */
10641 			return (-EINVAL);
10642 		}
10643 		break;
10644 	case IPPROTO_IP:
10645 		switch (name) {
10646 		case IP_NEXTHOP:
10647 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10648 				return (EPERM);
10649 			/* FALLTHRU */
10650 		case IP_MULTICAST_IF: {
10651 			ipaddr_t addr = *i1;
10652 
10653 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10654 			    first_mp);
10655 			if (error != 0)
10656 				return (error);
10657 			break;	/* goto sizeof (int) option return */
10658 		}
10659 
10660 		case IP_MULTICAST_TTL:
10661 			/* Recorded in transport above IP */
10662 			*outvalp = *invalp;
10663 			*outlenp = sizeof (uchar_t);
10664 			return (0);
10665 		case IP_MULTICAST_LOOP:
10666 			if (!checkonly) {
10667 				mutex_enter(&connp->conn_lock);
10668 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10669 				mutex_exit(&connp->conn_lock);
10670 			}
10671 			*outvalp = *invalp;
10672 			*outlenp = sizeof (uchar_t);
10673 			return (0);
10674 		case IP_ADD_MEMBERSHIP:
10675 		case MCAST_JOIN_GROUP:
10676 		case IP_DROP_MEMBERSHIP:
10677 		case MCAST_LEAVE_GROUP: {
10678 			struct ip_mreq *mreqp;
10679 			struct group_req *greqp;
10680 			ire_t *ire;
10681 			boolean_t done = B_FALSE;
10682 			ipaddr_t group, ifaddr;
10683 			struct sockaddr_in *sin;
10684 			uint32_t *ifindexp;
10685 			boolean_t mcast_opt = B_TRUE;
10686 			mcast_record_t fmode;
10687 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10688 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10689 
10690 			switch (name) {
10691 			case IP_ADD_MEMBERSHIP:
10692 				mcast_opt = B_FALSE;
10693 				/* FALLTHRU */
10694 			case MCAST_JOIN_GROUP:
10695 				fmode = MODE_IS_EXCLUDE;
10696 				optfn = ip_opt_add_group;
10697 				break;
10698 
10699 			case IP_DROP_MEMBERSHIP:
10700 				mcast_opt = B_FALSE;
10701 				/* FALLTHRU */
10702 			case MCAST_LEAVE_GROUP:
10703 				fmode = MODE_IS_INCLUDE;
10704 				optfn = ip_opt_delete_group;
10705 				break;
10706 			}
10707 
10708 			if (mcast_opt) {
10709 				greqp = (struct group_req *)i1;
10710 				sin = (struct sockaddr_in *)&greqp->gr_group;
10711 				if (sin->sin_family != AF_INET) {
10712 					*outlenp = 0;
10713 					return (ENOPROTOOPT);
10714 				}
10715 				group = (ipaddr_t)sin->sin_addr.s_addr;
10716 				ifaddr = INADDR_ANY;
10717 				ifindexp = &greqp->gr_interface;
10718 			} else {
10719 				mreqp = (struct ip_mreq *)i1;
10720 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10721 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10722 				ifindexp = NULL;
10723 			}
10724 
10725 			/*
10726 			 * In the multirouting case, we need to replicate
10727 			 * the request on all interfaces that will take part
10728 			 * in replication.  We do so because multirouting is
10729 			 * reflective, thus we will probably receive multi-
10730 			 * casts on those interfaces.
10731 			 * The ip_multirt_apply_membership() succeeds if the
10732 			 * operation succeeds on at least one interface.
10733 			 */
10734 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10735 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10736 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10737 			if (ire != NULL) {
10738 				if (ire->ire_flags & RTF_MULTIRT) {
10739 					error = ip_multirt_apply_membership(
10740 					    optfn, ire, connp, checkonly, group,
10741 					    fmode, INADDR_ANY, first_mp);
10742 					done = B_TRUE;
10743 				}
10744 				ire_refrele(ire);
10745 			}
10746 			if (!done) {
10747 				error = optfn(connp, checkonly, group, ifaddr,
10748 				    ifindexp, fmode, INADDR_ANY, first_mp);
10749 			}
10750 			if (error) {
10751 				/*
10752 				 * EINPROGRESS is a soft error, needs retry
10753 				 * so don't make *outlenp zero.
10754 				 */
10755 				if (error != EINPROGRESS)
10756 					*outlenp = 0;
10757 				return (error);
10758 			}
10759 			/* OK return - copy input buffer into output buffer */
10760 			if (invalp != outvalp) {
10761 				/* don't trust bcopy for identical src/dst */
10762 				bcopy(invalp, outvalp, inlen);
10763 			}
10764 			*outlenp = inlen;
10765 			return (0);
10766 		}
10767 		case IP_BLOCK_SOURCE:
10768 		case IP_UNBLOCK_SOURCE:
10769 		case IP_ADD_SOURCE_MEMBERSHIP:
10770 		case IP_DROP_SOURCE_MEMBERSHIP:
10771 		case MCAST_BLOCK_SOURCE:
10772 		case MCAST_UNBLOCK_SOURCE:
10773 		case MCAST_JOIN_SOURCE_GROUP:
10774 		case MCAST_LEAVE_SOURCE_GROUP: {
10775 			struct ip_mreq_source *imreqp;
10776 			struct group_source_req *gsreqp;
10777 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10778 			uint32_t ifindex = 0;
10779 			mcast_record_t fmode;
10780 			struct sockaddr_in *sin;
10781 			ire_t *ire;
10782 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10783 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10784 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10785 
10786 			switch (name) {
10787 			case IP_BLOCK_SOURCE:
10788 				mcast_opt = B_FALSE;
10789 				/* FALLTHRU */
10790 			case MCAST_BLOCK_SOURCE:
10791 				fmode = MODE_IS_EXCLUDE;
10792 				optfn = ip_opt_add_group;
10793 				break;
10794 
10795 			case IP_UNBLOCK_SOURCE:
10796 				mcast_opt = B_FALSE;
10797 				/* FALLTHRU */
10798 			case MCAST_UNBLOCK_SOURCE:
10799 				fmode = MODE_IS_EXCLUDE;
10800 				optfn = ip_opt_delete_group;
10801 				break;
10802 
10803 			case IP_ADD_SOURCE_MEMBERSHIP:
10804 				mcast_opt = B_FALSE;
10805 				/* FALLTHRU */
10806 			case MCAST_JOIN_SOURCE_GROUP:
10807 				fmode = MODE_IS_INCLUDE;
10808 				optfn = ip_opt_add_group;
10809 				break;
10810 
10811 			case IP_DROP_SOURCE_MEMBERSHIP:
10812 				mcast_opt = B_FALSE;
10813 				/* FALLTHRU */
10814 			case MCAST_LEAVE_SOURCE_GROUP:
10815 				fmode = MODE_IS_INCLUDE;
10816 				optfn = ip_opt_delete_group;
10817 				break;
10818 			}
10819 
10820 			if (mcast_opt) {
10821 				gsreqp = (struct group_source_req *)i1;
10822 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10823 					*outlenp = 0;
10824 					return (ENOPROTOOPT);
10825 				}
10826 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10827 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10828 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10829 				src = (ipaddr_t)sin->sin_addr.s_addr;
10830 				ifindex = gsreqp->gsr_interface;
10831 			} else {
10832 				imreqp = (struct ip_mreq_source *)i1;
10833 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10834 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10835 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10836 			}
10837 
10838 			/*
10839 			 * In the multirouting case, we need to replicate
10840 			 * the request as noted in the mcast cases above.
10841 			 */
10842 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10843 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10844 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10845 			if (ire != NULL) {
10846 				if (ire->ire_flags & RTF_MULTIRT) {
10847 					error = ip_multirt_apply_membership(
10848 					    optfn, ire, connp, checkonly, grp,
10849 					    fmode, src, first_mp);
10850 					done = B_TRUE;
10851 				}
10852 				ire_refrele(ire);
10853 			}
10854 			if (!done) {
10855 				error = optfn(connp, checkonly, grp, ifaddr,
10856 				    &ifindex, fmode, src, first_mp);
10857 			}
10858 			if (error != 0) {
10859 				/*
10860 				 * EINPROGRESS is a soft error, needs retry
10861 				 * so don't make *outlenp zero.
10862 				 */
10863 				if (error != EINPROGRESS)
10864 					*outlenp = 0;
10865 				return (error);
10866 			}
10867 			/* OK return - copy input buffer into output buffer */
10868 			if (invalp != outvalp) {
10869 				bcopy(invalp, outvalp, inlen);
10870 			}
10871 			*outlenp = inlen;
10872 			return (0);
10873 		}
10874 		case IP_SEC_OPT:
10875 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10876 			if (error != 0) {
10877 				*outlenp = 0;
10878 				return (error);
10879 			}
10880 			break;
10881 		case IP_HDRINCL:
10882 		case IP_OPTIONS:
10883 		case T_IP_OPTIONS:
10884 		case IP_TOS:
10885 		case T_IP_TOS:
10886 		case IP_TTL:
10887 		case IP_RECVDSTADDR:
10888 		case IP_RECVOPTS:
10889 			/* OK return - copy input buffer into output buffer */
10890 			if (invalp != outvalp) {
10891 				/* don't trust bcopy for identical src/dst */
10892 				bcopy(invalp, outvalp, inlen);
10893 			}
10894 			*outlenp = inlen;
10895 			return (0);
10896 		case IP_RECVIF:
10897 			/* Retrieve the inbound interface index */
10898 			if (!checkonly) {
10899 				mutex_enter(&connp->conn_lock);
10900 				connp->conn_recvif = *i1 ? 1 : 0;
10901 				mutex_exit(&connp->conn_lock);
10902 			}
10903 			break;	/* goto sizeof (int) option return */
10904 		case IP_RECVPKTINFO:
10905 			if (!checkonly) {
10906 				mutex_enter(&connp->conn_lock);
10907 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10908 				mutex_exit(&connp->conn_lock);
10909 			}
10910 			break;	/* goto sizeof (int) option return */
10911 		case IP_RECVSLLA:
10912 			/* Retrieve the source link layer address */
10913 			if (!checkonly) {
10914 				mutex_enter(&connp->conn_lock);
10915 				connp->conn_recvslla = *i1 ? 1 : 0;
10916 				mutex_exit(&connp->conn_lock);
10917 			}
10918 			break;	/* goto sizeof (int) option return */
10919 		case MRT_INIT:
10920 		case MRT_DONE:
10921 		case MRT_ADD_VIF:
10922 		case MRT_DEL_VIF:
10923 		case MRT_ADD_MFC:
10924 		case MRT_DEL_MFC:
10925 		case MRT_ASSERT:
10926 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10927 				*outlenp = 0;
10928 				return (error);
10929 			}
10930 			error = ip_mrouter_set((int)name, q, checkonly,
10931 			    (uchar_t *)invalp, inlen, first_mp);
10932 			if (error) {
10933 				*outlenp = 0;
10934 				return (error);
10935 			}
10936 			/* OK return - copy input buffer into output buffer */
10937 			if (invalp != outvalp) {
10938 				/* don't trust bcopy for identical src/dst */
10939 				bcopy(invalp, outvalp, inlen);
10940 			}
10941 			*outlenp = inlen;
10942 			return (0);
10943 		case IP_BOUND_IF:
10944 		case IP_DHCPINIT_IF:
10945 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10946 			    level, name, first_mp);
10947 			if (error != 0)
10948 				return (error);
10949 			break; 		/* goto sizeof (int) option return */
10950 
10951 		case IP_UNSPEC_SRC:
10952 			/* Allow sending with a zero source address */
10953 			if (!checkonly) {
10954 				mutex_enter(&connp->conn_lock);
10955 				connp->conn_unspec_src = *i1 ? 1 : 0;
10956 				mutex_exit(&connp->conn_lock);
10957 			}
10958 			break;	/* goto sizeof (int) option return */
10959 		default:
10960 			/*
10961 			 * "soft" error (negative)
10962 			 * option not handled at this level
10963 			 * Note: Do not modify *outlenp
10964 			 */
10965 			return (-EINVAL);
10966 		}
10967 		break;
10968 	case IPPROTO_IPV6:
10969 		switch (name) {
10970 		case IPV6_BOUND_IF:
10971 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10972 			    level, name, first_mp);
10973 			if (error != 0)
10974 				return (error);
10975 			break; 		/* goto sizeof (int) option return */
10976 
10977 		case IPV6_MULTICAST_IF:
10978 			/*
10979 			 * The only possible errors are EINPROGRESS and
10980 			 * EINVAL. EINPROGRESS will be restarted and is not
10981 			 * a hard error. We call this option on both V4 and V6
10982 			 * If both return EINVAL, then this call returns
10983 			 * EINVAL. If at least one of them succeeds we
10984 			 * return success.
10985 			 */
10986 			found = B_FALSE;
10987 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10988 			    level, name, first_mp);
10989 			if (error == EINPROGRESS)
10990 				return (error);
10991 			if (error == 0)
10992 				found = B_TRUE;
10993 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10994 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10995 			if (error == 0)
10996 				found = B_TRUE;
10997 			if (!found)
10998 				return (error);
10999 			break; 		/* goto sizeof (int) option return */
11000 
11001 		case IPV6_MULTICAST_HOPS:
11002 			/* Recorded in transport above IP */
11003 			break;	/* goto sizeof (int) option return */
11004 		case IPV6_MULTICAST_LOOP:
11005 			if (!checkonly) {
11006 				mutex_enter(&connp->conn_lock);
11007 				connp->conn_multicast_loop = *i1;
11008 				mutex_exit(&connp->conn_lock);
11009 			}
11010 			break;	/* goto sizeof (int) option return */
11011 		case IPV6_JOIN_GROUP:
11012 		case MCAST_JOIN_GROUP:
11013 		case IPV6_LEAVE_GROUP:
11014 		case MCAST_LEAVE_GROUP: {
11015 			struct ipv6_mreq *ip_mreqp;
11016 			struct group_req *greqp;
11017 			ire_t *ire;
11018 			boolean_t done = B_FALSE;
11019 			in6_addr_t groupv6;
11020 			uint32_t ifindex;
11021 			boolean_t mcast_opt = B_TRUE;
11022 			mcast_record_t fmode;
11023 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11024 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11025 
11026 			switch (name) {
11027 			case IPV6_JOIN_GROUP:
11028 				mcast_opt = B_FALSE;
11029 				/* FALLTHRU */
11030 			case MCAST_JOIN_GROUP:
11031 				fmode = MODE_IS_EXCLUDE;
11032 				optfn = ip_opt_add_group_v6;
11033 				break;
11034 
11035 			case IPV6_LEAVE_GROUP:
11036 				mcast_opt = B_FALSE;
11037 				/* FALLTHRU */
11038 			case MCAST_LEAVE_GROUP:
11039 				fmode = MODE_IS_INCLUDE;
11040 				optfn = ip_opt_delete_group_v6;
11041 				break;
11042 			}
11043 
11044 			if (mcast_opt) {
11045 				struct sockaddr_in *sin;
11046 				struct sockaddr_in6 *sin6;
11047 				greqp = (struct group_req *)i1;
11048 				if (greqp->gr_group.ss_family == AF_INET) {
11049 					sin = (struct sockaddr_in *)
11050 					    &(greqp->gr_group);
11051 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11052 					    &groupv6);
11053 				} else {
11054 					sin6 = (struct sockaddr_in6 *)
11055 					    &(greqp->gr_group);
11056 					groupv6 = sin6->sin6_addr;
11057 				}
11058 				ifindex = greqp->gr_interface;
11059 			} else {
11060 				ip_mreqp = (struct ipv6_mreq *)i1;
11061 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11062 				ifindex = ip_mreqp->ipv6mr_interface;
11063 			}
11064 			/*
11065 			 * In the multirouting case, we need to replicate
11066 			 * the request on all interfaces that will take part
11067 			 * in replication.  We do so because multirouting is
11068 			 * reflective, thus we will probably receive multi-
11069 			 * casts on those interfaces.
11070 			 * The ip_multirt_apply_membership_v6() succeeds if
11071 			 * the operation succeeds on at least one interface.
11072 			 */
11073 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11074 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11075 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11076 			if (ire != NULL) {
11077 				if (ire->ire_flags & RTF_MULTIRT) {
11078 					error = ip_multirt_apply_membership_v6(
11079 					    optfn, ire, connp, checkonly,
11080 					    &groupv6, fmode, &ipv6_all_zeros,
11081 					    first_mp);
11082 					done = B_TRUE;
11083 				}
11084 				ire_refrele(ire);
11085 			}
11086 			if (!done) {
11087 				error = optfn(connp, checkonly, &groupv6,
11088 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11089 			}
11090 			if (error) {
11091 				/*
11092 				 * EINPROGRESS is a soft error, needs retry
11093 				 * so don't make *outlenp zero.
11094 				 */
11095 				if (error != EINPROGRESS)
11096 					*outlenp = 0;
11097 				return (error);
11098 			}
11099 			/* OK return - copy input buffer into output buffer */
11100 			if (invalp != outvalp) {
11101 				/* don't trust bcopy for identical src/dst */
11102 				bcopy(invalp, outvalp, inlen);
11103 			}
11104 			*outlenp = inlen;
11105 			return (0);
11106 		}
11107 		case MCAST_BLOCK_SOURCE:
11108 		case MCAST_UNBLOCK_SOURCE:
11109 		case MCAST_JOIN_SOURCE_GROUP:
11110 		case MCAST_LEAVE_SOURCE_GROUP: {
11111 			struct group_source_req *gsreqp;
11112 			in6_addr_t v6grp, v6src;
11113 			uint32_t ifindex;
11114 			mcast_record_t fmode;
11115 			ire_t *ire;
11116 			boolean_t done = B_FALSE;
11117 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11118 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11119 
11120 			switch (name) {
11121 			case MCAST_BLOCK_SOURCE:
11122 				fmode = MODE_IS_EXCLUDE;
11123 				optfn = ip_opt_add_group_v6;
11124 				break;
11125 			case MCAST_UNBLOCK_SOURCE:
11126 				fmode = MODE_IS_EXCLUDE;
11127 				optfn = ip_opt_delete_group_v6;
11128 				break;
11129 			case MCAST_JOIN_SOURCE_GROUP:
11130 				fmode = MODE_IS_INCLUDE;
11131 				optfn = ip_opt_add_group_v6;
11132 				break;
11133 			case MCAST_LEAVE_SOURCE_GROUP:
11134 				fmode = MODE_IS_INCLUDE;
11135 				optfn = ip_opt_delete_group_v6;
11136 				break;
11137 			}
11138 
11139 			gsreqp = (struct group_source_req *)i1;
11140 			ifindex = gsreqp->gsr_interface;
11141 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11142 				struct sockaddr_in *s;
11143 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11144 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11145 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11146 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11147 			} else {
11148 				struct sockaddr_in6 *s6;
11149 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11150 				v6grp = s6->sin6_addr;
11151 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11152 				v6src = s6->sin6_addr;
11153 			}
11154 
11155 			/*
11156 			 * In the multirouting case, we need to replicate
11157 			 * the request as noted in the mcast cases above.
11158 			 */
11159 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11160 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11161 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11162 			if (ire != NULL) {
11163 				if (ire->ire_flags & RTF_MULTIRT) {
11164 					error = ip_multirt_apply_membership_v6(
11165 					    optfn, ire, connp, checkonly,
11166 					    &v6grp, fmode, &v6src, first_mp);
11167 					done = B_TRUE;
11168 				}
11169 				ire_refrele(ire);
11170 			}
11171 			if (!done) {
11172 				error = optfn(connp, checkonly, &v6grp,
11173 				    ifindex, fmode, &v6src, first_mp);
11174 			}
11175 			if (error != 0) {
11176 				/*
11177 				 * EINPROGRESS is a soft error, needs retry
11178 				 * so don't make *outlenp zero.
11179 				 */
11180 				if (error != EINPROGRESS)
11181 					*outlenp = 0;
11182 				return (error);
11183 			}
11184 			/* OK return - copy input buffer into output buffer */
11185 			if (invalp != outvalp) {
11186 				bcopy(invalp, outvalp, inlen);
11187 			}
11188 			*outlenp = inlen;
11189 			return (0);
11190 		}
11191 		case IPV6_UNICAST_HOPS:
11192 			/* Recorded in transport above IP */
11193 			break;	/* goto sizeof (int) option return */
11194 		case IPV6_UNSPEC_SRC:
11195 			/* Allow sending with a zero source address */
11196 			if (!checkonly) {
11197 				mutex_enter(&connp->conn_lock);
11198 				connp->conn_unspec_src = *i1 ? 1 : 0;
11199 				mutex_exit(&connp->conn_lock);
11200 			}
11201 			break;	/* goto sizeof (int) option return */
11202 		case IPV6_RECVPKTINFO:
11203 			if (!checkonly) {
11204 				mutex_enter(&connp->conn_lock);
11205 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11206 				mutex_exit(&connp->conn_lock);
11207 			}
11208 			break;	/* goto sizeof (int) option return */
11209 		case IPV6_RECVTCLASS:
11210 			if (!checkonly) {
11211 				if (*i1 < 0 || *i1 > 1) {
11212 					return (EINVAL);
11213 				}
11214 				mutex_enter(&connp->conn_lock);
11215 				connp->conn_ipv6_recvtclass = *i1;
11216 				mutex_exit(&connp->conn_lock);
11217 			}
11218 			break;
11219 		case IPV6_RECVPATHMTU:
11220 			if (!checkonly) {
11221 				if (*i1 < 0 || *i1 > 1) {
11222 					return (EINVAL);
11223 				}
11224 				mutex_enter(&connp->conn_lock);
11225 				connp->conn_ipv6_recvpathmtu = *i1;
11226 				mutex_exit(&connp->conn_lock);
11227 			}
11228 			break;
11229 		case IPV6_RECVHOPLIMIT:
11230 			if (!checkonly) {
11231 				mutex_enter(&connp->conn_lock);
11232 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11233 				mutex_exit(&connp->conn_lock);
11234 			}
11235 			break;	/* goto sizeof (int) option return */
11236 		case IPV6_RECVHOPOPTS:
11237 			if (!checkonly) {
11238 				mutex_enter(&connp->conn_lock);
11239 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11240 				mutex_exit(&connp->conn_lock);
11241 			}
11242 			break;	/* goto sizeof (int) option return */
11243 		case IPV6_RECVDSTOPTS:
11244 			if (!checkonly) {
11245 				mutex_enter(&connp->conn_lock);
11246 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11247 				mutex_exit(&connp->conn_lock);
11248 			}
11249 			break;	/* goto sizeof (int) option return */
11250 		case IPV6_RECVRTHDR:
11251 			if (!checkonly) {
11252 				mutex_enter(&connp->conn_lock);
11253 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11254 				mutex_exit(&connp->conn_lock);
11255 			}
11256 			break;	/* goto sizeof (int) option return */
11257 		case IPV6_RECVRTHDRDSTOPTS:
11258 			if (!checkonly) {
11259 				mutex_enter(&connp->conn_lock);
11260 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11261 				mutex_exit(&connp->conn_lock);
11262 			}
11263 			break;	/* goto sizeof (int) option return */
11264 		case IPV6_PKTINFO:
11265 			if (inlen == 0)
11266 				return (-EINVAL);	/* clearing option */
11267 			error = ip6_set_pktinfo(cr, connp,
11268 			    (struct in6_pktinfo *)invalp);
11269 			if (error != 0)
11270 				*outlenp = 0;
11271 			else
11272 				*outlenp = inlen;
11273 			return (error);
11274 		case IPV6_NEXTHOP: {
11275 			struct sockaddr_in6 *sin6;
11276 
11277 			/* Verify that the nexthop is reachable */
11278 			if (inlen == 0)
11279 				return (-EINVAL);	/* clearing option */
11280 
11281 			sin6 = (struct sockaddr_in6 *)invalp;
11282 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11283 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11284 			    NULL, MATCH_IRE_DEFAULT, ipst);
11285 
11286 			if (ire == NULL) {
11287 				*outlenp = 0;
11288 				return (EHOSTUNREACH);
11289 			}
11290 			ire_refrele(ire);
11291 			return (-EINVAL);
11292 		}
11293 		case IPV6_SEC_OPT:
11294 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11295 			if (error != 0) {
11296 				*outlenp = 0;
11297 				return (error);
11298 			}
11299 			break;
11300 		case IPV6_SRC_PREFERENCES: {
11301 			/*
11302 			 * This is implemented strictly in the ip module
11303 			 * (here and in tcp_opt_*() to accomodate tcp
11304 			 * sockets).  Modules above ip pass this option
11305 			 * down here since ip is the only one that needs to
11306 			 * be aware of source address preferences.
11307 			 *
11308 			 * This socket option only affects connected
11309 			 * sockets that haven't already bound to a specific
11310 			 * IPv6 address.  In other words, sockets that
11311 			 * don't call bind() with an address other than the
11312 			 * unspecified address and that call connect().
11313 			 * ip_bind_connected_v6() passes these preferences
11314 			 * to the ipif_select_source_v6() function.
11315 			 */
11316 			if (inlen != sizeof (uint32_t))
11317 				return (EINVAL);
11318 			error = ip6_set_src_preferences(connp,
11319 			    *(uint32_t *)invalp);
11320 			if (error != 0) {
11321 				*outlenp = 0;
11322 				return (error);
11323 			} else {
11324 				*outlenp = sizeof (uint32_t);
11325 			}
11326 			break;
11327 		}
11328 		case IPV6_V6ONLY:
11329 			if (*i1 < 0 || *i1 > 1) {
11330 				return (EINVAL);
11331 			}
11332 			mutex_enter(&connp->conn_lock);
11333 			connp->conn_ipv6_v6only = *i1;
11334 			mutex_exit(&connp->conn_lock);
11335 			break;
11336 		default:
11337 			return (-EINVAL);
11338 		}
11339 		break;
11340 	default:
11341 		/*
11342 		 * "soft" error (negative)
11343 		 * option not handled at this level
11344 		 * Note: Do not modify *outlenp
11345 		 */
11346 		return (-EINVAL);
11347 	}
11348 	/*
11349 	 * Common case of return from an option that is sizeof (int)
11350 	 */
11351 	*(int *)outvalp = *i1;
11352 	*outlenp = sizeof (int);
11353 	return (0);
11354 }
11355 
11356 /*
11357  * This routine gets default values of certain options whose default
11358  * values are maintained by protocol specific code
11359  */
11360 /* ARGSUSED */
11361 int
11362 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11363 {
11364 	int *i1 = (int *)ptr;
11365 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11366 
11367 	switch (level) {
11368 	case IPPROTO_IP:
11369 		switch (name) {
11370 		case IP_MULTICAST_TTL:
11371 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11372 			return (sizeof (uchar_t));
11373 		case IP_MULTICAST_LOOP:
11374 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11375 			return (sizeof (uchar_t));
11376 		default:
11377 			return (-1);
11378 		}
11379 	case IPPROTO_IPV6:
11380 		switch (name) {
11381 		case IPV6_UNICAST_HOPS:
11382 			*i1 = ipst->ips_ipv6_def_hops;
11383 			return (sizeof (int));
11384 		case IPV6_MULTICAST_HOPS:
11385 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11386 			return (sizeof (int));
11387 		case IPV6_MULTICAST_LOOP:
11388 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11389 			return (sizeof (int));
11390 		case IPV6_V6ONLY:
11391 			*i1 = 1;
11392 			return (sizeof (int));
11393 		default:
11394 			return (-1);
11395 		}
11396 	default:
11397 		return (-1);
11398 	}
11399 	/* NOTREACHED */
11400 }
11401 
11402 /*
11403  * Given a destination address and a pointer to where to put the information
11404  * this routine fills in the mtuinfo.
11405  */
11406 int
11407 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11408     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11409 {
11410 	ire_t *ire;
11411 	ip_stack_t	*ipst = ns->netstack_ip;
11412 
11413 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11414 		return (-1);
11415 
11416 	bzero(mtuinfo, sizeof (*mtuinfo));
11417 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11418 	mtuinfo->ip6m_addr.sin6_port = port;
11419 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11420 
11421 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11422 	if (ire != NULL) {
11423 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11424 		ire_refrele(ire);
11425 	} else {
11426 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11427 	}
11428 	return (sizeof (struct ip6_mtuinfo));
11429 }
11430 
11431 /*
11432  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11433  * checking of cred and that ip_g_mrouter is set should be done and
11434  * isn't.  This doesn't matter as the error checking is done properly for the
11435  * other MRT options coming in through ip_opt_set.
11436  */
11437 int
11438 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11439 {
11440 	conn_t		*connp = Q_TO_CONN(q);
11441 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11442 
11443 	switch (level) {
11444 	case IPPROTO_IP:
11445 		switch (name) {
11446 		case MRT_VERSION:
11447 		case MRT_ASSERT:
11448 			(void) ip_mrouter_get(name, q, ptr);
11449 			return (sizeof (int));
11450 		case IP_SEC_OPT:
11451 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11452 		case IP_NEXTHOP:
11453 			if (connp->conn_nexthop_set) {
11454 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11455 				return (sizeof (ipaddr_t));
11456 			} else
11457 				return (0);
11458 		case IP_RECVPKTINFO:
11459 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11460 			return (sizeof (int));
11461 		default:
11462 			break;
11463 		}
11464 		break;
11465 	case IPPROTO_IPV6:
11466 		switch (name) {
11467 		case IPV6_SEC_OPT:
11468 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11469 		case IPV6_SRC_PREFERENCES: {
11470 			return (ip6_get_src_preferences(connp,
11471 			    (uint32_t *)ptr));
11472 		}
11473 		case IPV6_V6ONLY:
11474 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11475 			return (sizeof (int));
11476 		case IPV6_PATHMTU:
11477 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11478 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11479 		default:
11480 			break;
11481 		}
11482 		break;
11483 	default:
11484 		break;
11485 	}
11486 	return (-1);
11487 }
11488 /* Named Dispatch routine to get a current value out of our parameter table. */
11489 /* ARGSUSED */
11490 static int
11491 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11492 {
11493 	ipparam_t *ippa = (ipparam_t *)cp;
11494 
11495 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11496 	return (0);
11497 }
11498 
11499 /* ARGSUSED */
11500 static int
11501 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11502 {
11503 
11504 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11505 	return (0);
11506 }
11507 
11508 /*
11509  * Set ip{,6}_forwarding values.  This means walking through all of the
11510  * ill's and toggling their forwarding values.
11511  */
11512 /* ARGSUSED */
11513 static int
11514 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11515 {
11516 	long new_value;
11517 	int *forwarding_value = (int *)cp;
11518 	ill_t *ill;
11519 	boolean_t isv6;
11520 	ill_walk_context_t ctx;
11521 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11522 
11523 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11524 
11525 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11526 	    new_value < 0 || new_value > 1) {
11527 		return (EINVAL);
11528 	}
11529 
11530 	*forwarding_value = new_value;
11531 
11532 	/*
11533 	 * Regardless of the current value of ip_forwarding, set all per-ill
11534 	 * values of ip_forwarding to the value being set.
11535 	 *
11536 	 * Bring all the ill's up to date with the new global value.
11537 	 */
11538 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11539 
11540 	if (isv6)
11541 		ill = ILL_START_WALK_V6(&ctx, ipst);
11542 	else
11543 		ill = ILL_START_WALK_V4(&ctx, ipst);
11544 
11545 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11546 		(void) ill_forward_set(ill, new_value != 0);
11547 
11548 	rw_exit(&ipst->ips_ill_g_lock);
11549 	return (0);
11550 }
11551 
11552 /*
11553  * Walk through the param array specified registering each element with the
11554  * Named Dispatch handler. This is called only during init. So it is ok
11555  * not to acquire any locks
11556  */
11557 static boolean_t
11558 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11559     ipndp_t *ipnd, size_t ipnd_cnt)
11560 {
11561 	for (; ippa_cnt-- > 0; ippa++) {
11562 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11563 			if (!nd_load(ndp, ippa->ip_param_name,
11564 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11565 				nd_free(ndp);
11566 				return (B_FALSE);
11567 			}
11568 		}
11569 	}
11570 
11571 	for (; ipnd_cnt-- > 0; ipnd++) {
11572 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11573 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11574 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11575 			    ipnd->ip_ndp_data)) {
11576 				nd_free(ndp);
11577 				return (B_FALSE);
11578 			}
11579 		}
11580 	}
11581 
11582 	return (B_TRUE);
11583 }
11584 
11585 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11586 /* ARGSUSED */
11587 static int
11588 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11589 {
11590 	long		new_value;
11591 	ipparam_t	*ippa = (ipparam_t *)cp;
11592 
11593 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11594 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11595 		return (EINVAL);
11596 	}
11597 	ippa->ip_param_value = new_value;
11598 	return (0);
11599 }
11600 
11601 /*
11602  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11603  * When an ipf is passed here for the first time, if
11604  * we already have in-order fragments on the queue, we convert from the fast-
11605  * path reassembly scheme to the hard-case scheme.  From then on, additional
11606  * fragments are reassembled here.  We keep track of the start and end offsets
11607  * of each piece, and the number of holes in the chain.  When the hole count
11608  * goes to zero, we are done!
11609  *
11610  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11611  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11612  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11613  * after the call to ip_reassemble().
11614  */
11615 int
11616 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11617     size_t msg_len)
11618 {
11619 	uint_t	end;
11620 	mblk_t	*next_mp;
11621 	mblk_t	*mp1;
11622 	uint_t	offset;
11623 	boolean_t incr_dups = B_TRUE;
11624 	boolean_t offset_zero_seen = B_FALSE;
11625 	boolean_t pkt_boundary_checked = B_FALSE;
11626 
11627 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11628 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11629 
11630 	/* Add in byte count */
11631 	ipf->ipf_count += msg_len;
11632 	if (ipf->ipf_end) {
11633 		/*
11634 		 * We were part way through in-order reassembly, but now there
11635 		 * is a hole.  We walk through messages already queued, and
11636 		 * mark them for hard case reassembly.  We know that up till
11637 		 * now they were in order starting from offset zero.
11638 		 */
11639 		offset = 0;
11640 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11641 			IP_REASS_SET_START(mp1, offset);
11642 			if (offset == 0) {
11643 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11644 				offset = -ipf->ipf_nf_hdr_len;
11645 			}
11646 			offset += mp1->b_wptr - mp1->b_rptr;
11647 			IP_REASS_SET_END(mp1, offset);
11648 		}
11649 		/* One hole at the end. */
11650 		ipf->ipf_hole_cnt = 1;
11651 		/* Brand it as a hard case, forever. */
11652 		ipf->ipf_end = 0;
11653 	}
11654 	/* Walk through all the new pieces. */
11655 	do {
11656 		end = start + (mp->b_wptr - mp->b_rptr);
11657 		/*
11658 		 * If start is 0, decrease 'end' only for the first mblk of
11659 		 * the fragment. Otherwise 'end' can get wrong value in the
11660 		 * second pass of the loop if first mblk is exactly the
11661 		 * size of ipf_nf_hdr_len.
11662 		 */
11663 		if (start == 0 && !offset_zero_seen) {
11664 			/* First segment */
11665 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11666 			end -= ipf->ipf_nf_hdr_len;
11667 			offset_zero_seen = B_TRUE;
11668 		}
11669 		next_mp = mp->b_cont;
11670 		/*
11671 		 * We are checking to see if there is any interesing data
11672 		 * to process.  If there isn't and the mblk isn't the
11673 		 * one which carries the unfragmentable header then we
11674 		 * drop it.  It's possible to have just the unfragmentable
11675 		 * header come through without any data.  That needs to be
11676 		 * saved.
11677 		 *
11678 		 * If the assert at the top of this function holds then the
11679 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11680 		 * is infrequently traveled enough that the test is left in
11681 		 * to protect against future code changes which break that
11682 		 * invariant.
11683 		 */
11684 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11685 			/* Empty.  Blast it. */
11686 			IP_REASS_SET_START(mp, 0);
11687 			IP_REASS_SET_END(mp, 0);
11688 			/*
11689 			 * If the ipf points to the mblk we are about to free,
11690 			 * update ipf to point to the next mblk (or NULL
11691 			 * if none).
11692 			 */
11693 			if (ipf->ipf_mp->b_cont == mp)
11694 				ipf->ipf_mp->b_cont = next_mp;
11695 			freeb(mp);
11696 			continue;
11697 		}
11698 		mp->b_cont = NULL;
11699 		IP_REASS_SET_START(mp, start);
11700 		IP_REASS_SET_END(mp, end);
11701 		if (!ipf->ipf_tail_mp) {
11702 			ipf->ipf_tail_mp = mp;
11703 			ipf->ipf_mp->b_cont = mp;
11704 			if (start == 0 || !more) {
11705 				ipf->ipf_hole_cnt = 1;
11706 				/*
11707 				 * if the first fragment comes in more than one
11708 				 * mblk, this loop will be executed for each
11709 				 * mblk. Need to adjust hole count so exiting
11710 				 * this routine will leave hole count at 1.
11711 				 */
11712 				if (next_mp)
11713 					ipf->ipf_hole_cnt++;
11714 			} else
11715 				ipf->ipf_hole_cnt = 2;
11716 			continue;
11717 		} else if (ipf->ipf_last_frag_seen && !more &&
11718 		    !pkt_boundary_checked) {
11719 			/*
11720 			 * We check datagram boundary only if this fragment
11721 			 * claims to be the last fragment and we have seen a
11722 			 * last fragment in the past too. We do this only
11723 			 * once for a given fragment.
11724 			 *
11725 			 * start cannot be 0 here as fragments with start=0
11726 			 * and MF=0 gets handled as a complete packet. These
11727 			 * fragments should not reach here.
11728 			 */
11729 
11730 			if (start + msgdsize(mp) !=
11731 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11732 				/*
11733 				 * We have two fragments both of which claim
11734 				 * to be the last fragment but gives conflicting
11735 				 * information about the whole datagram size.
11736 				 * Something fishy is going on. Drop the
11737 				 * fragment and free up the reassembly list.
11738 				 */
11739 				return (IP_REASS_FAILED);
11740 			}
11741 
11742 			/*
11743 			 * We shouldn't come to this code block again for this
11744 			 * particular fragment.
11745 			 */
11746 			pkt_boundary_checked = B_TRUE;
11747 		}
11748 
11749 		/* New stuff at or beyond tail? */
11750 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11751 		if (start >= offset) {
11752 			if (ipf->ipf_last_frag_seen) {
11753 				/* current fragment is beyond last fragment */
11754 				return (IP_REASS_FAILED);
11755 			}
11756 			/* Link it on end. */
11757 			ipf->ipf_tail_mp->b_cont = mp;
11758 			ipf->ipf_tail_mp = mp;
11759 			if (more) {
11760 				if (start != offset)
11761 					ipf->ipf_hole_cnt++;
11762 			} else if (start == offset && next_mp == NULL)
11763 					ipf->ipf_hole_cnt--;
11764 			continue;
11765 		}
11766 		mp1 = ipf->ipf_mp->b_cont;
11767 		offset = IP_REASS_START(mp1);
11768 		/* New stuff at the front? */
11769 		if (start < offset) {
11770 			if (start == 0) {
11771 				if (end >= offset) {
11772 					/* Nailed the hole at the begining. */
11773 					ipf->ipf_hole_cnt--;
11774 				}
11775 			} else if (end < offset) {
11776 				/*
11777 				 * A hole, stuff, and a hole where there used
11778 				 * to be just a hole.
11779 				 */
11780 				ipf->ipf_hole_cnt++;
11781 			}
11782 			mp->b_cont = mp1;
11783 			/* Check for overlap. */
11784 			while (end > offset) {
11785 				if (end < IP_REASS_END(mp1)) {
11786 					mp->b_wptr -= end - offset;
11787 					IP_REASS_SET_END(mp, offset);
11788 					BUMP_MIB(ill->ill_ip_mib,
11789 					    ipIfStatsReasmPartDups);
11790 					break;
11791 				}
11792 				/* Did we cover another hole? */
11793 				if ((mp1->b_cont &&
11794 				    IP_REASS_END(mp1) !=
11795 				    IP_REASS_START(mp1->b_cont) &&
11796 				    end >= IP_REASS_START(mp1->b_cont)) ||
11797 				    (!ipf->ipf_last_frag_seen && !more)) {
11798 					ipf->ipf_hole_cnt--;
11799 				}
11800 				/* Clip out mp1. */
11801 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11802 					/*
11803 					 * After clipping out mp1, this guy
11804 					 * is now hanging off the end.
11805 					 */
11806 					ipf->ipf_tail_mp = mp;
11807 				}
11808 				IP_REASS_SET_START(mp1, 0);
11809 				IP_REASS_SET_END(mp1, 0);
11810 				/* Subtract byte count */
11811 				ipf->ipf_count -= mp1->b_datap->db_lim -
11812 				    mp1->b_datap->db_base;
11813 				freeb(mp1);
11814 				BUMP_MIB(ill->ill_ip_mib,
11815 				    ipIfStatsReasmPartDups);
11816 				mp1 = mp->b_cont;
11817 				if (!mp1)
11818 					break;
11819 				offset = IP_REASS_START(mp1);
11820 			}
11821 			ipf->ipf_mp->b_cont = mp;
11822 			continue;
11823 		}
11824 		/*
11825 		 * The new piece starts somewhere between the start of the head
11826 		 * and before the end of the tail.
11827 		 */
11828 		for (; mp1; mp1 = mp1->b_cont) {
11829 			offset = IP_REASS_END(mp1);
11830 			if (start < offset) {
11831 				if (end <= offset) {
11832 					/* Nothing new. */
11833 					IP_REASS_SET_START(mp, 0);
11834 					IP_REASS_SET_END(mp, 0);
11835 					/* Subtract byte count */
11836 					ipf->ipf_count -= mp->b_datap->db_lim -
11837 					    mp->b_datap->db_base;
11838 					if (incr_dups) {
11839 						ipf->ipf_num_dups++;
11840 						incr_dups = B_FALSE;
11841 					}
11842 					freeb(mp);
11843 					BUMP_MIB(ill->ill_ip_mib,
11844 					    ipIfStatsReasmDuplicates);
11845 					break;
11846 				}
11847 				/*
11848 				 * Trim redundant stuff off beginning of new
11849 				 * piece.
11850 				 */
11851 				IP_REASS_SET_START(mp, offset);
11852 				mp->b_rptr += offset - start;
11853 				BUMP_MIB(ill->ill_ip_mib,
11854 				    ipIfStatsReasmPartDups);
11855 				start = offset;
11856 				if (!mp1->b_cont) {
11857 					/*
11858 					 * After trimming, this guy is now
11859 					 * hanging off the end.
11860 					 */
11861 					mp1->b_cont = mp;
11862 					ipf->ipf_tail_mp = mp;
11863 					if (!more) {
11864 						ipf->ipf_hole_cnt--;
11865 					}
11866 					break;
11867 				}
11868 			}
11869 			if (start >= IP_REASS_START(mp1->b_cont))
11870 				continue;
11871 			/* Fill a hole */
11872 			if (start > offset)
11873 				ipf->ipf_hole_cnt++;
11874 			mp->b_cont = mp1->b_cont;
11875 			mp1->b_cont = mp;
11876 			mp1 = mp->b_cont;
11877 			offset = IP_REASS_START(mp1);
11878 			if (end >= offset) {
11879 				ipf->ipf_hole_cnt--;
11880 				/* Check for overlap. */
11881 				while (end > offset) {
11882 					if (end < IP_REASS_END(mp1)) {
11883 						mp->b_wptr -= end - offset;
11884 						IP_REASS_SET_END(mp, offset);
11885 						/*
11886 						 * TODO we might bump
11887 						 * this up twice if there is
11888 						 * overlap at both ends.
11889 						 */
11890 						BUMP_MIB(ill->ill_ip_mib,
11891 						    ipIfStatsReasmPartDups);
11892 						break;
11893 					}
11894 					/* Did we cover another hole? */
11895 					if ((mp1->b_cont &&
11896 					    IP_REASS_END(mp1)
11897 					    != IP_REASS_START(mp1->b_cont) &&
11898 					    end >=
11899 					    IP_REASS_START(mp1->b_cont)) ||
11900 					    (!ipf->ipf_last_frag_seen &&
11901 					    !more)) {
11902 						ipf->ipf_hole_cnt--;
11903 					}
11904 					/* Clip out mp1. */
11905 					if ((mp->b_cont = mp1->b_cont) ==
11906 					    NULL) {
11907 						/*
11908 						 * After clipping out mp1,
11909 						 * this guy is now hanging
11910 						 * off the end.
11911 						 */
11912 						ipf->ipf_tail_mp = mp;
11913 					}
11914 					IP_REASS_SET_START(mp1, 0);
11915 					IP_REASS_SET_END(mp1, 0);
11916 					/* Subtract byte count */
11917 					ipf->ipf_count -=
11918 					    mp1->b_datap->db_lim -
11919 					    mp1->b_datap->db_base;
11920 					freeb(mp1);
11921 					BUMP_MIB(ill->ill_ip_mib,
11922 					    ipIfStatsReasmPartDups);
11923 					mp1 = mp->b_cont;
11924 					if (!mp1)
11925 						break;
11926 					offset = IP_REASS_START(mp1);
11927 				}
11928 			}
11929 			break;
11930 		}
11931 	} while (start = end, mp = next_mp);
11932 
11933 	/* Fragment just processed could be the last one. Remember this fact */
11934 	if (!more)
11935 		ipf->ipf_last_frag_seen = B_TRUE;
11936 
11937 	/* Still got holes? */
11938 	if (ipf->ipf_hole_cnt)
11939 		return (IP_REASS_PARTIAL);
11940 	/* Clean up overloaded fields to avoid upstream disasters. */
11941 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11942 		IP_REASS_SET_START(mp1, 0);
11943 		IP_REASS_SET_END(mp1, 0);
11944 	}
11945 	return (IP_REASS_COMPLETE);
11946 }
11947 
11948 /*
11949  * ipsec processing for the fast path, used for input UDP Packets
11950  * Returns true if ready for passup to UDP.
11951  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
11952  * was an ESP-in-UDP packet, etc.).
11953  */
11954 static boolean_t
11955 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11956     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
11957 {
11958 	uint32_t	ill_index;
11959 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11960 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11961 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11962 	udp_t		*udp = connp->conn_udp;
11963 
11964 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11965 	/* The ill_index of the incoming ILL */
11966 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11967 
11968 	/* pass packet up to the transport */
11969 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11970 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11971 		    NULL, mctl_present);
11972 		if (*first_mpp == NULL) {
11973 			return (B_FALSE);
11974 		}
11975 	}
11976 
11977 	/* Initiate IPPF processing for fastpath UDP */
11978 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11979 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11980 		if (*mpp == NULL) {
11981 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11982 			    "deferred/dropped during IPPF processing\n"));
11983 			return (B_FALSE);
11984 		}
11985 	}
11986 	/*
11987 	 * Remove 0-spi if it's 0, or move everything behind
11988 	 * the UDP header over it and forward to ESP via
11989 	 * ip_proto_input().
11990 	 */
11991 	if (udp->udp_nat_t_endpoint) {
11992 		if (mctl_present) {
11993 			/* mctl_present *shouldn't* happen. */
11994 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
11995 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
11996 			    &ipss->ipsec_dropper);
11997 			*first_mpp = NULL;
11998 			return (B_FALSE);
11999 		}
12000 
12001 		/* "ill" is "recv_ill" in actuality. */
12002 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12003 			return (B_FALSE);
12004 
12005 		/* Else continue like a normal UDP packet. */
12006 	}
12007 
12008 	/*
12009 	 * We make the checks as below since we are in the fast path
12010 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12011 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12012 	 */
12013 	if (connp->conn_recvif || connp->conn_recvslla ||
12014 	    connp->conn_ip_recvpktinfo) {
12015 		if (connp->conn_recvif) {
12016 			in_flags = IPF_RECVIF;
12017 		}
12018 		/*
12019 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12020 		 * so the flag passed to ip_add_info is based on IP version
12021 		 * of connp.
12022 		 */
12023 		if (connp->conn_ip_recvpktinfo) {
12024 			if (connp->conn_af_isv6) {
12025 				/*
12026 				 * V6 only needs index
12027 				 */
12028 				in_flags |= IPF_RECVIF;
12029 			} else {
12030 				/*
12031 				 * V4 needs index + matching address.
12032 				 */
12033 				in_flags |= IPF_RECVADDR;
12034 			}
12035 		}
12036 		if (connp->conn_recvslla) {
12037 			in_flags |= IPF_RECVSLLA;
12038 		}
12039 		/*
12040 		 * since in_flags are being set ill will be
12041 		 * referenced in ip_add_info, so it better not
12042 		 * be NULL.
12043 		 */
12044 		/*
12045 		 * the actual data will be contained in b_cont
12046 		 * upon successful return of the following call.
12047 		 * If the call fails then the original mblk is
12048 		 * returned.
12049 		 */
12050 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12051 		    ipst);
12052 	}
12053 
12054 	return (B_TRUE);
12055 }
12056 
12057 /*
12058  * Fragmentation reassembly.  Each ILL has a hash table for
12059  * queuing packets undergoing reassembly for all IPIFs
12060  * associated with the ILL.  The hash is based on the packet
12061  * IP ident field.  The ILL frag hash table was allocated
12062  * as a timer block at the time the ILL was created.  Whenever
12063  * there is anything on the reassembly queue, the timer will
12064  * be running.  Returns B_TRUE if successful else B_FALSE;
12065  * frees mp on failure.
12066  */
12067 static boolean_t
12068 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12069     uint32_t *cksum_val, uint16_t *cksum_flags)
12070 {
12071 	uint32_t	frag_offset_flags;
12072 	mblk_t		*mp = *mpp;
12073 	mblk_t		*t_mp;
12074 	ipaddr_t	dst;
12075 	uint8_t		proto = ipha->ipha_protocol;
12076 	uint32_t	sum_val;
12077 	uint16_t	sum_flags;
12078 	ipf_t		*ipf;
12079 	ipf_t		**ipfp;
12080 	ipfb_t		*ipfb;
12081 	uint16_t	ident;
12082 	uint32_t	offset;
12083 	ipaddr_t	src;
12084 	uint_t		hdr_length;
12085 	uint32_t	end;
12086 	mblk_t		*mp1;
12087 	mblk_t		*tail_mp;
12088 	size_t		count;
12089 	size_t		msg_len;
12090 	uint8_t		ecn_info = 0;
12091 	uint32_t	packet_size;
12092 	boolean_t	pruned = B_FALSE;
12093 	ip_stack_t *ipst = ill->ill_ipst;
12094 
12095 	if (cksum_val != NULL)
12096 		*cksum_val = 0;
12097 	if (cksum_flags != NULL)
12098 		*cksum_flags = 0;
12099 
12100 	/*
12101 	 * Drop the fragmented as early as possible, if
12102 	 * we don't have resource(s) to re-assemble.
12103 	 */
12104 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12105 		freemsg(mp);
12106 		return (B_FALSE);
12107 	}
12108 
12109 	/* Check for fragmentation offset; return if there's none */
12110 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12111 	    (IPH_MF | IPH_OFFSET)) == 0)
12112 		return (B_TRUE);
12113 
12114 	/*
12115 	 * We utilize hardware computed checksum info only for UDP since
12116 	 * IP fragmentation is a normal occurrence for the protocol.  In
12117 	 * addition, checksum offload support for IP fragments carrying
12118 	 * UDP payload is commonly implemented across network adapters.
12119 	 */
12120 	ASSERT(recv_ill != NULL);
12121 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12122 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12123 		mblk_t *mp1 = mp->b_cont;
12124 		int32_t len;
12125 
12126 		/* Record checksum information from the packet */
12127 		sum_val = (uint32_t)DB_CKSUM16(mp);
12128 		sum_flags = DB_CKSUMFLAGS(mp);
12129 
12130 		/* IP payload offset from beginning of mblk */
12131 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12132 
12133 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12134 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12135 		    offset >= DB_CKSUMSTART(mp) &&
12136 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12137 			uint32_t adj;
12138 			/*
12139 			 * Partial checksum has been calculated by hardware
12140 			 * and attached to the packet; in addition, any
12141 			 * prepended extraneous data is even byte aligned.
12142 			 * If any such data exists, we adjust the checksum;
12143 			 * this would also handle any postpended data.
12144 			 */
12145 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12146 			    mp, mp1, len, adj);
12147 
12148 			/* One's complement subtract extraneous checksum */
12149 			if (adj >= sum_val)
12150 				sum_val = ~(adj - sum_val) & 0xFFFF;
12151 			else
12152 				sum_val -= adj;
12153 		}
12154 	} else {
12155 		sum_val = 0;
12156 		sum_flags = 0;
12157 	}
12158 
12159 	/* Clear hardware checksumming flag */
12160 	DB_CKSUMFLAGS(mp) = 0;
12161 
12162 	ident = ipha->ipha_ident;
12163 	offset = (frag_offset_flags << 3) & 0xFFFF;
12164 	src = ipha->ipha_src;
12165 	dst = ipha->ipha_dst;
12166 	hdr_length = IPH_HDR_LENGTH(ipha);
12167 	end = ntohs(ipha->ipha_length) - hdr_length;
12168 
12169 	/* If end == 0 then we have a packet with no data, so just free it */
12170 	if (end == 0) {
12171 		freemsg(mp);
12172 		return (B_FALSE);
12173 	}
12174 
12175 	/* Record the ECN field info. */
12176 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12177 	if (offset != 0) {
12178 		/*
12179 		 * If this isn't the first piece, strip the header, and
12180 		 * add the offset to the end value.
12181 		 */
12182 		mp->b_rptr += hdr_length;
12183 		end += offset;
12184 	}
12185 
12186 	msg_len = MBLKSIZE(mp);
12187 	tail_mp = mp;
12188 	while (tail_mp->b_cont != NULL) {
12189 		tail_mp = tail_mp->b_cont;
12190 		msg_len += MBLKSIZE(tail_mp);
12191 	}
12192 
12193 	/* If the reassembly list for this ILL will get too big, prune it */
12194 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12195 	    ipst->ips_ip_reass_queue_bytes) {
12196 		ill_frag_prune(ill,
12197 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12198 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12199 		pruned = B_TRUE;
12200 	}
12201 
12202 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12203 	mutex_enter(&ipfb->ipfb_lock);
12204 
12205 	ipfp = &ipfb->ipfb_ipf;
12206 	/* Try to find an existing fragment queue for this packet. */
12207 	for (;;) {
12208 		ipf = ipfp[0];
12209 		if (ipf != NULL) {
12210 			/*
12211 			 * It has to match on ident and src/dst address.
12212 			 */
12213 			if (ipf->ipf_ident == ident &&
12214 			    ipf->ipf_src == src &&
12215 			    ipf->ipf_dst == dst &&
12216 			    ipf->ipf_protocol == proto) {
12217 				/*
12218 				 * If we have received too many
12219 				 * duplicate fragments for this packet
12220 				 * free it.
12221 				 */
12222 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12223 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12224 					freemsg(mp);
12225 					mutex_exit(&ipfb->ipfb_lock);
12226 					return (B_FALSE);
12227 				}
12228 				/* Found it. */
12229 				break;
12230 			}
12231 			ipfp = &ipf->ipf_hash_next;
12232 			continue;
12233 		}
12234 
12235 		/*
12236 		 * If we pruned the list, do we want to store this new
12237 		 * fragment?. We apply an optimization here based on the
12238 		 * fact that most fragments will be received in order.
12239 		 * So if the offset of this incoming fragment is zero,
12240 		 * it is the first fragment of a new packet. We will
12241 		 * keep it.  Otherwise drop the fragment, as we have
12242 		 * probably pruned the packet already (since the
12243 		 * packet cannot be found).
12244 		 */
12245 		if (pruned && offset != 0) {
12246 			mutex_exit(&ipfb->ipfb_lock);
12247 			freemsg(mp);
12248 			return (B_FALSE);
12249 		}
12250 
12251 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12252 			/*
12253 			 * Too many fragmented packets in this hash
12254 			 * bucket. Free the oldest.
12255 			 */
12256 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12257 		}
12258 
12259 		/* New guy.  Allocate a frag message. */
12260 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12261 		if (mp1 == NULL) {
12262 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12263 			freemsg(mp);
12264 reass_done:
12265 			mutex_exit(&ipfb->ipfb_lock);
12266 			return (B_FALSE);
12267 		}
12268 
12269 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12270 		mp1->b_cont = mp;
12271 
12272 		/* Initialize the fragment header. */
12273 		ipf = (ipf_t *)mp1->b_rptr;
12274 		ipf->ipf_mp = mp1;
12275 		ipf->ipf_ptphn = ipfp;
12276 		ipfp[0] = ipf;
12277 		ipf->ipf_hash_next = NULL;
12278 		ipf->ipf_ident = ident;
12279 		ipf->ipf_protocol = proto;
12280 		ipf->ipf_src = src;
12281 		ipf->ipf_dst = dst;
12282 		ipf->ipf_nf_hdr_len = 0;
12283 		/* Record reassembly start time. */
12284 		ipf->ipf_timestamp = gethrestime_sec();
12285 		/* Record ipf generation and account for frag header */
12286 		ipf->ipf_gen = ill->ill_ipf_gen++;
12287 		ipf->ipf_count = MBLKSIZE(mp1);
12288 		ipf->ipf_last_frag_seen = B_FALSE;
12289 		ipf->ipf_ecn = ecn_info;
12290 		ipf->ipf_num_dups = 0;
12291 		ipfb->ipfb_frag_pkts++;
12292 		ipf->ipf_checksum = 0;
12293 		ipf->ipf_checksum_flags = 0;
12294 
12295 		/* Store checksum value in fragment header */
12296 		if (sum_flags != 0) {
12297 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12298 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12299 			ipf->ipf_checksum = sum_val;
12300 			ipf->ipf_checksum_flags = sum_flags;
12301 		}
12302 
12303 		/*
12304 		 * We handle reassembly two ways.  In the easy case,
12305 		 * where all the fragments show up in order, we do
12306 		 * minimal bookkeeping, and just clip new pieces on
12307 		 * the end.  If we ever see a hole, then we go off
12308 		 * to ip_reassemble which has to mark the pieces and
12309 		 * keep track of the number of holes, etc.  Obviously,
12310 		 * the point of having both mechanisms is so we can
12311 		 * handle the easy case as efficiently as possible.
12312 		 */
12313 		if (offset == 0) {
12314 			/* Easy case, in-order reassembly so far. */
12315 			ipf->ipf_count += msg_len;
12316 			ipf->ipf_tail_mp = tail_mp;
12317 			/*
12318 			 * Keep track of next expected offset in
12319 			 * ipf_end.
12320 			 */
12321 			ipf->ipf_end = end;
12322 			ipf->ipf_nf_hdr_len = hdr_length;
12323 		} else {
12324 			/* Hard case, hole at the beginning. */
12325 			ipf->ipf_tail_mp = NULL;
12326 			/*
12327 			 * ipf_end == 0 means that we have given up
12328 			 * on easy reassembly.
12329 			 */
12330 			ipf->ipf_end = 0;
12331 
12332 			/* Forget checksum offload from now on */
12333 			ipf->ipf_checksum_flags = 0;
12334 
12335 			/*
12336 			 * ipf_hole_cnt is set by ip_reassemble.
12337 			 * ipf_count is updated by ip_reassemble.
12338 			 * No need to check for return value here
12339 			 * as we don't expect reassembly to complete
12340 			 * or fail for the first fragment itself.
12341 			 */
12342 			(void) ip_reassemble(mp, ipf,
12343 			    (frag_offset_flags & IPH_OFFSET) << 3,
12344 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12345 		}
12346 		/* Update per ipfb and ill byte counts */
12347 		ipfb->ipfb_count += ipf->ipf_count;
12348 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12349 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12350 		/* If the frag timer wasn't already going, start it. */
12351 		mutex_enter(&ill->ill_lock);
12352 		ill_frag_timer_start(ill);
12353 		mutex_exit(&ill->ill_lock);
12354 		goto reass_done;
12355 	}
12356 
12357 	/*
12358 	 * If the packet's flag has changed (it could be coming up
12359 	 * from an interface different than the previous, therefore
12360 	 * possibly different checksum capability), then forget about
12361 	 * any stored checksum states.  Otherwise add the value to
12362 	 * the existing one stored in the fragment header.
12363 	 */
12364 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12365 		sum_val += ipf->ipf_checksum;
12366 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12367 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12368 		ipf->ipf_checksum = sum_val;
12369 	} else if (ipf->ipf_checksum_flags != 0) {
12370 		/* Forget checksum offload from now on */
12371 		ipf->ipf_checksum_flags = 0;
12372 	}
12373 
12374 	/*
12375 	 * We have a new piece of a datagram which is already being
12376 	 * reassembled.  Update the ECN info if all IP fragments
12377 	 * are ECN capable.  If there is one which is not, clear
12378 	 * all the info.  If there is at least one which has CE
12379 	 * code point, IP needs to report that up to transport.
12380 	 */
12381 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12382 		if (ecn_info == IPH_ECN_CE)
12383 			ipf->ipf_ecn = IPH_ECN_CE;
12384 	} else {
12385 		ipf->ipf_ecn = IPH_ECN_NECT;
12386 	}
12387 	if (offset && ipf->ipf_end == offset) {
12388 		/* The new fragment fits at the end */
12389 		ipf->ipf_tail_mp->b_cont = mp;
12390 		/* Update the byte count */
12391 		ipf->ipf_count += msg_len;
12392 		/* Update per ipfb and ill byte counts */
12393 		ipfb->ipfb_count += msg_len;
12394 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12395 		atomic_add_32(&ill->ill_frag_count, msg_len);
12396 		if (frag_offset_flags & IPH_MF) {
12397 			/* More to come. */
12398 			ipf->ipf_end = end;
12399 			ipf->ipf_tail_mp = tail_mp;
12400 			goto reass_done;
12401 		}
12402 	} else {
12403 		/* Go do the hard cases. */
12404 		int ret;
12405 
12406 		if (offset == 0)
12407 			ipf->ipf_nf_hdr_len = hdr_length;
12408 
12409 		/* Save current byte count */
12410 		count = ipf->ipf_count;
12411 		ret = ip_reassemble(mp, ipf,
12412 		    (frag_offset_flags & IPH_OFFSET) << 3,
12413 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12414 		/* Count of bytes added and subtracted (freeb()ed) */
12415 		count = ipf->ipf_count - count;
12416 		if (count) {
12417 			/* Update per ipfb and ill byte counts */
12418 			ipfb->ipfb_count += count;
12419 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12420 			atomic_add_32(&ill->ill_frag_count, count);
12421 		}
12422 		if (ret == IP_REASS_PARTIAL) {
12423 			goto reass_done;
12424 		} else if (ret == IP_REASS_FAILED) {
12425 			/* Reassembly failed. Free up all resources */
12426 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12427 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12428 				IP_REASS_SET_START(t_mp, 0);
12429 				IP_REASS_SET_END(t_mp, 0);
12430 			}
12431 			freemsg(mp);
12432 			goto reass_done;
12433 		}
12434 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12435 	}
12436 	/*
12437 	 * We have completed reassembly.  Unhook the frag header from
12438 	 * the reassembly list.
12439 	 *
12440 	 * Before we free the frag header, record the ECN info
12441 	 * to report back to the transport.
12442 	 */
12443 	ecn_info = ipf->ipf_ecn;
12444 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12445 	ipfp = ipf->ipf_ptphn;
12446 
12447 	/* We need to supply these to caller */
12448 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12449 		sum_val = ipf->ipf_checksum;
12450 	else
12451 		sum_val = 0;
12452 
12453 	mp1 = ipf->ipf_mp;
12454 	count = ipf->ipf_count;
12455 	ipf = ipf->ipf_hash_next;
12456 	if (ipf != NULL)
12457 		ipf->ipf_ptphn = ipfp;
12458 	ipfp[0] = ipf;
12459 	atomic_add_32(&ill->ill_frag_count, -count);
12460 	ASSERT(ipfb->ipfb_count >= count);
12461 	ipfb->ipfb_count -= count;
12462 	ipfb->ipfb_frag_pkts--;
12463 	mutex_exit(&ipfb->ipfb_lock);
12464 	/* Ditch the frag header. */
12465 	mp = mp1->b_cont;
12466 
12467 	freeb(mp1);
12468 
12469 	/* Restore original IP length in header. */
12470 	packet_size = (uint32_t)msgdsize(mp);
12471 	if (packet_size > IP_MAXPACKET) {
12472 		freemsg(mp);
12473 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12474 		return (B_FALSE);
12475 	}
12476 
12477 	if (DB_REF(mp) > 1) {
12478 		mblk_t *mp2 = copymsg(mp);
12479 
12480 		freemsg(mp);
12481 		if (mp2 == NULL) {
12482 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12483 			return (B_FALSE);
12484 		}
12485 		mp = mp2;
12486 	}
12487 	ipha = (ipha_t *)mp->b_rptr;
12488 
12489 	ipha->ipha_length = htons((uint16_t)packet_size);
12490 	/* We're now complete, zip the frag state */
12491 	ipha->ipha_fragment_offset_and_flags = 0;
12492 	/* Record the ECN info. */
12493 	ipha->ipha_type_of_service &= 0xFC;
12494 	ipha->ipha_type_of_service |= ecn_info;
12495 	*mpp = mp;
12496 
12497 	/* Reassembly is successful; return checksum information if needed */
12498 	if (cksum_val != NULL)
12499 		*cksum_val = sum_val;
12500 	if (cksum_flags != NULL)
12501 		*cksum_flags = sum_flags;
12502 
12503 	return (B_TRUE);
12504 }
12505 
12506 /*
12507  * Perform ip header check sum update local options.
12508  * return B_TRUE if all is well, else return B_FALSE and release
12509  * the mp. caller is responsible for decrementing ire ref cnt.
12510  */
12511 static boolean_t
12512 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12513     ip_stack_t *ipst)
12514 {
12515 	mblk_t		*first_mp;
12516 	boolean_t	mctl_present;
12517 	uint16_t	sum;
12518 
12519 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12520 	/*
12521 	 * Don't do the checksum if it has gone through AH/ESP
12522 	 * processing.
12523 	 */
12524 	if (!mctl_present) {
12525 		sum = ip_csum_hdr(ipha);
12526 		if (sum != 0) {
12527 			if (ill != NULL) {
12528 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12529 			} else {
12530 				BUMP_MIB(&ipst->ips_ip_mib,
12531 				    ipIfStatsInCksumErrs);
12532 			}
12533 			freemsg(first_mp);
12534 			return (B_FALSE);
12535 		}
12536 	}
12537 
12538 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12539 		if (mctl_present)
12540 			freeb(first_mp);
12541 		return (B_FALSE);
12542 	}
12543 
12544 	return (B_TRUE);
12545 }
12546 
12547 /*
12548  * All udp packet are delivered to the local host via this routine.
12549  */
12550 void
12551 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12552     ill_t *recv_ill)
12553 {
12554 	uint32_t	sum;
12555 	uint32_t	u1;
12556 	boolean_t	mctl_present;
12557 	conn_t		*connp;
12558 	mblk_t		*first_mp;
12559 	uint16_t	*up;
12560 	ill_t		*ill = (ill_t *)q->q_ptr;
12561 	uint16_t	reass_hck_flags = 0;
12562 	ip_stack_t	*ipst;
12563 
12564 	ASSERT(recv_ill != NULL);
12565 	ipst = recv_ill->ill_ipst;
12566 
12567 #define	rptr    ((uchar_t *)ipha)
12568 
12569 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12570 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12571 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12572 	ASSERT(ill != NULL);
12573 
12574 	/*
12575 	 * FAST PATH for udp packets
12576 	 */
12577 
12578 	/* u1 is # words of IP options */
12579 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12580 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12581 
12582 	/* IP options present */
12583 	if (u1 != 0)
12584 		goto ipoptions;
12585 
12586 	/* Check the IP header checksum.  */
12587 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12588 		/* Clear the IP header h/w cksum flag */
12589 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12590 	} else if (!mctl_present) {
12591 		/*
12592 		 * Don't verify header checksum if this packet is coming
12593 		 * back from AH/ESP as we already did it.
12594 		 */
12595 #define	uph	((uint16_t *)ipha)
12596 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12597 		    uph[6] + uph[7] + uph[8] + uph[9];
12598 #undef	uph
12599 		/* finish doing IP checksum */
12600 		sum = (sum & 0xFFFF) + (sum >> 16);
12601 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12602 		if (sum != 0 && sum != 0xFFFF) {
12603 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12604 			freemsg(first_mp);
12605 			return;
12606 		}
12607 	}
12608 
12609 	/*
12610 	 * Count for SNMP of inbound packets for ire.
12611 	 * if mctl is present this might be a secure packet and
12612 	 * has already been counted for in ip_proto_input().
12613 	 */
12614 	if (!mctl_present) {
12615 		UPDATE_IB_PKT_COUNT(ire);
12616 		ire->ire_last_used_time = lbolt;
12617 	}
12618 
12619 	/* packet part of fragmented IP packet? */
12620 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12621 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12622 		goto fragmented;
12623 	}
12624 
12625 	/* u1 = IP header length (20 bytes) */
12626 	u1 = IP_SIMPLE_HDR_LENGTH;
12627 
12628 	/* packet does not contain complete IP & UDP headers */
12629 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12630 		goto udppullup;
12631 
12632 	/* up points to UDP header */
12633 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12634 #define	iphs    ((uint16_t *)ipha)
12635 
12636 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12637 	if (up[3] != 0) {
12638 		mblk_t *mp1 = mp->b_cont;
12639 		boolean_t cksum_err;
12640 		uint16_t hck_flags = 0;
12641 
12642 		/* Pseudo-header checksum */
12643 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12644 		    iphs[9] + up[2];
12645 
12646 		/*
12647 		 * Revert to software checksum calculation if the interface
12648 		 * isn't capable of checksum offload or if IPsec is present.
12649 		 */
12650 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12651 			hck_flags = DB_CKSUMFLAGS(mp);
12652 
12653 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12654 			IP_STAT(ipst, ip_in_sw_cksum);
12655 
12656 		IP_CKSUM_RECV(hck_flags, u1,
12657 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12658 		    (int32_t)((uchar_t *)up - rptr),
12659 		    mp, mp1, cksum_err);
12660 
12661 		if (cksum_err) {
12662 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12663 			if (hck_flags & HCK_FULLCKSUM)
12664 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12665 			else if (hck_flags & HCK_PARTIALCKSUM)
12666 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12667 			else
12668 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12669 
12670 			freemsg(first_mp);
12671 			return;
12672 		}
12673 	}
12674 
12675 	/* Non-fragmented broadcast or multicast packet? */
12676 	if (ire->ire_type == IRE_BROADCAST)
12677 		goto udpslowpath;
12678 
12679 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12680 	    ire->ire_zoneid, ipst)) != NULL) {
12681 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12682 		IP_STAT(ipst, ip_udp_fast_path);
12683 
12684 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12685 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12686 			freemsg(mp);
12687 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12688 		} else {
12689 			if (!mctl_present) {
12690 				BUMP_MIB(ill->ill_ip_mib,
12691 				    ipIfStatsHCInDelivers);
12692 			}
12693 			/*
12694 			 * mp and first_mp can change.
12695 			 */
12696 			if (ip_udp_check(q, connp, recv_ill,
12697 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12698 				/* Send it upstream */
12699 				(connp->conn_recv)(connp, mp, NULL);
12700 			}
12701 		}
12702 		/*
12703 		 * freeb() cannot deal with null mblk being passed
12704 		 * in and first_mp can be set to null in the call
12705 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12706 		 */
12707 		if (mctl_present && first_mp != NULL) {
12708 			freeb(first_mp);
12709 		}
12710 		CONN_DEC_REF(connp);
12711 		return;
12712 	}
12713 
12714 	/*
12715 	 * if we got here we know the packet is not fragmented and
12716 	 * has no options. The classifier could not find a conn_t and
12717 	 * most likely its an icmp packet so send it through slow path.
12718 	 */
12719 
12720 	goto udpslowpath;
12721 
12722 ipoptions:
12723 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12724 		goto slow_done;
12725 	}
12726 
12727 	UPDATE_IB_PKT_COUNT(ire);
12728 	ire->ire_last_used_time = lbolt;
12729 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12730 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12731 fragmented:
12732 		/*
12733 		 * "sum" and "reass_hck_flags" are non-zero if the
12734 		 * reassembled packet has a valid hardware computed
12735 		 * checksum information associated with it.
12736 		 */
12737 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12738 		    &reass_hck_flags)) {
12739 			goto slow_done;
12740 		}
12741 
12742 		/*
12743 		 * Make sure that first_mp points back to mp as
12744 		 * the mp we came in with could have changed in
12745 		 * ip_rput_fragment().
12746 		 */
12747 		ASSERT(!mctl_present);
12748 		ipha = (ipha_t *)mp->b_rptr;
12749 		first_mp = mp;
12750 	}
12751 
12752 	/* Now we have a complete datagram, destined for this machine. */
12753 	u1 = IPH_HDR_LENGTH(ipha);
12754 	/* Pull up the UDP header, if necessary. */
12755 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12756 udppullup:
12757 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12758 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12759 			freemsg(first_mp);
12760 			goto slow_done;
12761 		}
12762 		ipha = (ipha_t *)mp->b_rptr;
12763 	}
12764 
12765 	/*
12766 	 * Validate the checksum for the reassembled packet; for the
12767 	 * pullup case we calculate the payload checksum in software.
12768 	 */
12769 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12770 	if (up[3] != 0) {
12771 		boolean_t cksum_err;
12772 
12773 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12774 			IP_STAT(ipst, ip_in_sw_cksum);
12775 
12776 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12777 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12778 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12779 		    iphs[9] + up[2], sum, cksum_err);
12780 
12781 		if (cksum_err) {
12782 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12783 
12784 			if (reass_hck_flags & HCK_FULLCKSUM)
12785 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12786 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12787 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12788 			else
12789 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12790 
12791 			freemsg(first_mp);
12792 			goto slow_done;
12793 		}
12794 	}
12795 udpslowpath:
12796 
12797 	/* Clear hardware checksum flag to be safe */
12798 	DB_CKSUMFLAGS(mp) = 0;
12799 
12800 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12801 	    (ire->ire_type == IRE_BROADCAST),
12802 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12803 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12804 
12805 slow_done:
12806 	IP_STAT(ipst, ip_udp_slow_path);
12807 	return;
12808 
12809 #undef  iphs
12810 #undef  rptr
12811 }
12812 
12813 static boolean_t
12814 ip_iptun_input(mblk_t *ipsec_mp, mblk_t *data_mp, ipha_t *ipha, ill_t *ill,
12815     ire_t *ire, ip_stack_t *ipst)
12816 {
12817 	conn_t	*connp;
12818 
12819 	ASSERT(ipsec_mp == NULL || ipsec_mp->b_cont == data_mp);
12820 
12821 	if ((connp = ipcl_classify_v4(data_mp, ipha->ipha_protocol,
12822 	    IP_SIMPLE_HDR_LENGTH, ire->ire_zoneid, ipst)) != NULL) {
12823 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12824 		connp->conn_recv(connp, ipsec_mp != NULL ? ipsec_mp : data_mp,
12825 		    NULL);
12826 		CONN_DEC_REF(connp);
12827 		return (B_TRUE);
12828 	}
12829 	return (B_FALSE);
12830 }
12831 
12832 /* ARGSUSED */
12833 static mblk_t *
12834 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12835     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12836     ill_rx_ring_t *ill_ring)
12837 {
12838 	conn_t		*connp;
12839 	uint32_t	sum;
12840 	uint32_t	u1;
12841 	uint16_t	*up;
12842 	int		offset;
12843 	ssize_t		len;
12844 	mblk_t		*mp1;
12845 	boolean_t	syn_present = B_FALSE;
12846 	tcph_t		*tcph;
12847 	uint_t		tcph_flags;
12848 	uint_t		ip_hdr_len;
12849 	ill_t		*ill = (ill_t *)q->q_ptr;
12850 	zoneid_t	zoneid = ire->ire_zoneid;
12851 	boolean_t	cksum_err;
12852 	uint16_t	hck_flags = 0;
12853 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12854 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12855 
12856 #define	rptr	((uchar_t *)ipha)
12857 
12858 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12859 	ASSERT(ill != NULL);
12860 
12861 	/*
12862 	 * FAST PATH for tcp packets
12863 	 */
12864 
12865 	/* u1 is # words of IP options */
12866 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12867 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12868 
12869 	/* IP options present */
12870 	if (u1) {
12871 		goto ipoptions;
12872 	} else if (!mctl_present) {
12873 		/* Check the IP header checksum.  */
12874 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12875 			/* Clear the IP header h/w cksum flag */
12876 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12877 		} else if (!mctl_present) {
12878 			/*
12879 			 * Don't verify header checksum if this packet
12880 			 * is coming back from AH/ESP as we already did it.
12881 			 */
12882 #define	uph	((uint16_t *)ipha)
12883 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12884 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12885 #undef	uph
12886 			/* finish doing IP checksum */
12887 			sum = (sum & 0xFFFF) + (sum >> 16);
12888 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12889 			if (sum != 0 && sum != 0xFFFF) {
12890 				BUMP_MIB(ill->ill_ip_mib,
12891 				    ipIfStatsInCksumErrs);
12892 				goto error;
12893 			}
12894 		}
12895 	}
12896 
12897 	if (!mctl_present) {
12898 		UPDATE_IB_PKT_COUNT(ire);
12899 		ire->ire_last_used_time = lbolt;
12900 	}
12901 
12902 	/* packet part of fragmented IP packet? */
12903 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12904 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12905 		goto fragmented;
12906 	}
12907 
12908 	/* u1 = IP header length (20 bytes) */
12909 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12910 
12911 	/* does packet contain IP+TCP headers? */
12912 	len = mp->b_wptr - rptr;
12913 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12914 		IP_STAT(ipst, ip_tcppullup);
12915 		goto tcppullup;
12916 	}
12917 
12918 	/* TCP options present? */
12919 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12920 
12921 	/*
12922 	 * If options need to be pulled up, then goto tcpoptions.
12923 	 * otherwise we are still in the fast path
12924 	 */
12925 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12926 		IP_STAT(ipst, ip_tcpoptions);
12927 		goto tcpoptions;
12928 	}
12929 
12930 	/* multiple mblks of tcp data? */
12931 	if ((mp1 = mp->b_cont) != NULL) {
12932 		IP_STAT(ipst, ip_multipkttcp);
12933 		len += msgdsize(mp1);
12934 	}
12935 
12936 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12937 
12938 	/* part of pseudo checksum */
12939 
12940 	/* TCP datagram length */
12941 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12942 
12943 #define	iphs    ((uint16_t *)ipha)
12944 
12945 #ifdef	_BIG_ENDIAN
12946 	u1 += IPPROTO_TCP;
12947 #else
12948 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12949 #endif
12950 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12951 
12952 	/*
12953 	 * Revert to software checksum calculation if the interface
12954 	 * isn't capable of checksum offload or if IPsec is present.
12955 	 */
12956 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12957 		hck_flags = DB_CKSUMFLAGS(mp);
12958 
12959 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12960 		IP_STAT(ipst, ip_in_sw_cksum);
12961 
12962 	IP_CKSUM_RECV(hck_flags, u1,
12963 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12964 	    (int32_t)((uchar_t *)up - rptr),
12965 	    mp, mp1, cksum_err);
12966 
12967 	if (cksum_err) {
12968 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12969 
12970 		if (hck_flags & HCK_FULLCKSUM)
12971 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12972 		else if (hck_flags & HCK_PARTIALCKSUM)
12973 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12974 		else
12975 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12976 
12977 		goto error;
12978 	}
12979 
12980 try_again:
12981 
12982 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12983 	    zoneid, ipst)) == NULL) {
12984 		/* Send the TH_RST */
12985 		goto no_conn;
12986 	}
12987 
12988 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12989 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
12990 
12991 	/*
12992 	 * TCP FAST PATH for AF_INET socket.
12993 	 *
12994 	 * TCP fast path to avoid extra work. An AF_INET socket type
12995 	 * does not have facility to receive extra information via
12996 	 * ip_process or ip_add_info. Also, when the connection was
12997 	 * established, we made a check if this connection is impacted
12998 	 * by any global IPsec policy or per connection policy (a
12999 	 * policy that comes in effect later will not apply to this
13000 	 * connection). Since all this can be determined at the
13001 	 * connection establishment time, a quick check of flags
13002 	 * can avoid extra work.
13003 	 */
13004 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13005 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13006 		ASSERT(first_mp == mp);
13007 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13008 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13009 			SET_SQUEUE(mp, tcp_rput_data, connp);
13010 			return (mp);
13011 		}
13012 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13013 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13014 		SET_SQUEUE(mp, tcp_input, connp);
13015 		return (mp);
13016 	}
13017 
13018 	if (tcph_flags == TH_SYN) {
13019 		if (IPCL_IS_TCP(connp)) {
13020 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13021 			DB_CKSUMSTART(mp) =
13022 			    (intptr_t)ip_squeue_get(ill_ring);
13023 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13024 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13025 				BUMP_MIB(ill->ill_ip_mib,
13026 				    ipIfStatsHCInDelivers);
13027 				SET_SQUEUE(mp, connp->conn_recv, connp);
13028 				return (mp);
13029 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13030 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13031 				BUMP_MIB(ill->ill_ip_mib,
13032 				    ipIfStatsHCInDelivers);
13033 				ip_squeue_enter_unbound++;
13034 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13035 				    connp);
13036 				return (mp);
13037 			}
13038 			syn_present = B_TRUE;
13039 		}
13040 	}
13041 
13042 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13043 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13044 
13045 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13046 		/* No need to send this packet to TCP */
13047 		if ((flags & TH_RST) || (flags & TH_URG)) {
13048 			CONN_DEC_REF(connp);
13049 			freemsg(first_mp);
13050 			return (NULL);
13051 		}
13052 		if (flags & TH_ACK) {
13053 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13054 			    ipst->ips_netstack->netstack_tcp, connp);
13055 			CONN_DEC_REF(connp);
13056 			return (NULL);
13057 		}
13058 
13059 		CONN_DEC_REF(connp);
13060 		freemsg(first_mp);
13061 		return (NULL);
13062 	}
13063 
13064 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13065 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13066 		    ipha, NULL, mctl_present);
13067 		if (first_mp == NULL) {
13068 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13069 			CONN_DEC_REF(connp);
13070 			return (NULL);
13071 		}
13072 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13073 			ASSERT(syn_present);
13074 			if (mctl_present) {
13075 				ASSERT(first_mp != mp);
13076 				first_mp->b_datap->db_struioflag |=
13077 				    STRUIO_POLICY;
13078 			} else {
13079 				ASSERT(first_mp == mp);
13080 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13081 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13082 			}
13083 		} else {
13084 			/*
13085 			 * Discard first_mp early since we're dealing with a
13086 			 * fully-connected conn_t and tcp doesn't do policy in
13087 			 * this case.
13088 			 */
13089 			if (mctl_present) {
13090 				freeb(first_mp);
13091 				mctl_present = B_FALSE;
13092 			}
13093 			first_mp = mp;
13094 		}
13095 	}
13096 
13097 	/* Initiate IPPF processing for fastpath */
13098 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13099 		uint32_t	ill_index;
13100 
13101 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13102 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13103 		if (mp == NULL) {
13104 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13105 			    "deferred/dropped during IPPF processing\n"));
13106 			CONN_DEC_REF(connp);
13107 			if (mctl_present)
13108 				freeb(first_mp);
13109 			return (NULL);
13110 		} else if (mctl_present) {
13111 			/*
13112 			 * ip_process might return a new mp.
13113 			 */
13114 			ASSERT(first_mp != mp);
13115 			first_mp->b_cont = mp;
13116 		} else {
13117 			first_mp = mp;
13118 		}
13119 
13120 	}
13121 
13122 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13123 		/*
13124 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13125 		 * make sure IPF_RECVIF is passed to ip_add_info.
13126 		 */
13127 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13128 		    IPCL_ZONEID(connp), ipst);
13129 		if (mp == NULL) {
13130 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13131 			CONN_DEC_REF(connp);
13132 			if (mctl_present)
13133 				freeb(first_mp);
13134 			return (NULL);
13135 		} else if (mctl_present) {
13136 			/*
13137 			 * ip_add_info might return a new mp.
13138 			 */
13139 			ASSERT(first_mp != mp);
13140 			first_mp->b_cont = mp;
13141 		} else {
13142 			first_mp = mp;
13143 		}
13144 	}
13145 
13146 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13147 	if (IPCL_IS_TCP(connp)) {
13148 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13149 		return (first_mp);
13150 	} else {
13151 		/* SOCK_RAW, IPPROTO_TCP case */
13152 		(connp->conn_recv)(connp, first_mp, NULL);
13153 		CONN_DEC_REF(connp);
13154 		return (NULL);
13155 	}
13156 
13157 no_conn:
13158 	/* Initiate IPPf processing, if needed. */
13159 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13160 		uint32_t ill_index;
13161 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13162 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13163 		if (first_mp == NULL) {
13164 			return (NULL);
13165 		}
13166 	}
13167 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13168 
13169 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13170 	    ipst->ips_netstack->netstack_tcp, NULL);
13171 	return (NULL);
13172 ipoptions:
13173 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13174 		goto slow_done;
13175 	}
13176 
13177 	UPDATE_IB_PKT_COUNT(ire);
13178 	ire->ire_last_used_time = lbolt;
13179 
13180 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13181 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13182 fragmented:
13183 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13184 			if (mctl_present)
13185 				freeb(first_mp);
13186 			goto slow_done;
13187 		}
13188 		/*
13189 		 * Make sure that first_mp points back to mp as
13190 		 * the mp we came in with could have changed in
13191 		 * ip_rput_fragment().
13192 		 */
13193 		ASSERT(!mctl_present);
13194 		ipha = (ipha_t *)mp->b_rptr;
13195 		first_mp = mp;
13196 	}
13197 
13198 	/* Now we have a complete datagram, destined for this machine. */
13199 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13200 
13201 	len = mp->b_wptr - mp->b_rptr;
13202 	/* Pull up a minimal TCP header, if necessary. */
13203 	if (len < (u1 + 20)) {
13204 tcppullup:
13205 		if (!pullupmsg(mp, u1 + 20)) {
13206 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13207 			goto error;
13208 		}
13209 		ipha = (ipha_t *)mp->b_rptr;
13210 		len = mp->b_wptr - mp->b_rptr;
13211 	}
13212 
13213 	/*
13214 	 * Extract the offset field from the TCP header.  As usual, we
13215 	 * try to help the compiler more than the reader.
13216 	 */
13217 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13218 	if (offset != 5) {
13219 tcpoptions:
13220 		if (offset < 5) {
13221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13222 			goto error;
13223 		}
13224 		/*
13225 		 * There must be TCP options.
13226 		 * Make sure we can grab them.
13227 		 */
13228 		offset <<= 2;
13229 		offset += u1;
13230 		if (len < offset) {
13231 			if (!pullupmsg(mp, offset)) {
13232 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13233 				goto error;
13234 			}
13235 			ipha = (ipha_t *)mp->b_rptr;
13236 			len = mp->b_wptr - rptr;
13237 		}
13238 	}
13239 
13240 	/* Get the total packet length in len, including headers. */
13241 	if (mp->b_cont)
13242 		len = msgdsize(mp);
13243 
13244 	/*
13245 	 * Check the TCP checksum by pulling together the pseudo-
13246 	 * header checksum, and passing it to ip_csum to be added in
13247 	 * with the TCP datagram.
13248 	 *
13249 	 * Since we are not using the hwcksum if available we must
13250 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13251 	 * If either of these fails along the way the mblk is freed.
13252 	 * If this logic ever changes and mblk is reused to say send
13253 	 * ICMP's back, then this flag may need to be cleared in
13254 	 * other places as well.
13255 	 */
13256 	DB_CKSUMFLAGS(mp) = 0;
13257 
13258 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13259 
13260 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13261 #ifdef	_BIG_ENDIAN
13262 	u1 += IPPROTO_TCP;
13263 #else
13264 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13265 #endif
13266 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13267 	/*
13268 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13269 	 */
13270 	IP_STAT(ipst, ip_in_sw_cksum);
13271 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13272 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13273 		goto error;
13274 	}
13275 
13276 	IP_STAT(ipst, ip_tcp_slow_path);
13277 	goto try_again;
13278 #undef  iphs
13279 #undef  rptr
13280 
13281 error:
13282 	freemsg(first_mp);
13283 slow_done:
13284 	return (NULL);
13285 }
13286 
13287 /* ARGSUSED */
13288 static void
13289 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13290     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13291 {
13292 	conn_t		*connp;
13293 	uint32_t	sum;
13294 	uint32_t	u1;
13295 	ssize_t		len;
13296 	sctp_hdr_t	*sctph;
13297 	zoneid_t	zoneid = ire->ire_zoneid;
13298 	uint32_t	pktsum;
13299 	uint32_t	calcsum;
13300 	uint32_t	ports;
13301 	in6_addr_t	map_src, map_dst;
13302 	ill_t		*ill = (ill_t *)q->q_ptr;
13303 	ip_stack_t	*ipst;
13304 	sctp_stack_t	*sctps;
13305 	boolean_t	sctp_csum_err = B_FALSE;
13306 
13307 	ASSERT(recv_ill != NULL);
13308 	ipst = recv_ill->ill_ipst;
13309 	sctps = ipst->ips_netstack->netstack_sctp;
13310 
13311 #define	rptr	((uchar_t *)ipha)
13312 
13313 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13314 	ASSERT(ill != NULL);
13315 
13316 	/* u1 is # words of IP options */
13317 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13318 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13319 
13320 	/* IP options present */
13321 	if (u1 > 0) {
13322 		goto ipoptions;
13323 	} else {
13324 		/* Check the IP header checksum.  */
13325 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13326 		    !mctl_present) {
13327 #define	uph	((uint16_t *)ipha)
13328 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13329 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13330 #undef	uph
13331 			/* finish doing IP checksum */
13332 			sum = (sum & 0xFFFF) + (sum >> 16);
13333 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13334 			/*
13335 			 * Don't verify header checksum if this packet
13336 			 * is coming back from AH/ESP as we already did it.
13337 			 */
13338 			if (sum != 0 && sum != 0xFFFF) {
13339 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13340 				goto error;
13341 			}
13342 		}
13343 		/*
13344 		 * Since there is no SCTP h/w cksum support yet, just
13345 		 * clear the flag.
13346 		 */
13347 		DB_CKSUMFLAGS(mp) = 0;
13348 	}
13349 
13350 	/*
13351 	 * Don't verify header checksum if this packet is coming
13352 	 * back from AH/ESP as we already did it.
13353 	 */
13354 	if (!mctl_present) {
13355 		UPDATE_IB_PKT_COUNT(ire);
13356 		ire->ire_last_used_time = lbolt;
13357 	}
13358 
13359 	/* packet part of fragmented IP packet? */
13360 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13361 	if (u1 & (IPH_MF | IPH_OFFSET))
13362 		goto fragmented;
13363 
13364 	/* u1 = IP header length (20 bytes) */
13365 	u1 = IP_SIMPLE_HDR_LENGTH;
13366 
13367 find_sctp_client:
13368 	/* Pullup if we don't have the sctp common header. */
13369 	len = MBLKL(mp);
13370 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13371 		if (mp->b_cont == NULL ||
13372 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13373 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13374 			goto error;
13375 		}
13376 		ipha = (ipha_t *)mp->b_rptr;
13377 		len = MBLKL(mp);
13378 	}
13379 
13380 	sctph = (sctp_hdr_t *)(rptr + u1);
13381 #ifdef	DEBUG
13382 	if (!skip_sctp_cksum) {
13383 #endif
13384 		pktsum = sctph->sh_chksum;
13385 		sctph->sh_chksum = 0;
13386 		calcsum = sctp_cksum(mp, u1);
13387 		sctph->sh_chksum = pktsum;
13388 		if (calcsum != pktsum)
13389 			sctp_csum_err = B_TRUE;
13390 #ifdef	DEBUG	/* skip_sctp_cksum */
13391 	}
13392 #endif
13393 	/* get the ports */
13394 	ports = *(uint32_t *)&sctph->sh_sport;
13395 
13396 	IRE_REFRELE(ire);
13397 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13398 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13399 	if (sctp_csum_err) {
13400 		/*
13401 		 * No potential sctp checksum errors go to the Sun
13402 		 * sctp stack however they might be Adler-32 summed
13403 		 * packets a userland stack bound to a raw IP socket
13404 		 * could reasonably use. Note though that Adler-32 is
13405 		 * a long deprecated algorithm and customer sctp
13406 		 * networks should eventually migrate to CRC-32 at
13407 		 * which time this facility should be removed.
13408 		 */
13409 		flags |= IP_FF_SCTP_CSUM_ERR;
13410 		goto no_conn;
13411 	}
13412 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13413 	    sctps)) == NULL) {
13414 		/* Check for raw socket or OOTB handling */
13415 		goto no_conn;
13416 	}
13417 
13418 	/* Found a client; up it goes */
13419 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13420 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13421 	return;
13422 
13423 no_conn:
13424 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13425 	    ports, mctl_present, flags, B_TRUE, zoneid);
13426 	return;
13427 
13428 ipoptions:
13429 	DB_CKSUMFLAGS(mp) = 0;
13430 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13431 		goto slow_done;
13432 
13433 	UPDATE_IB_PKT_COUNT(ire);
13434 	ire->ire_last_used_time = lbolt;
13435 
13436 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13437 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13438 fragmented:
13439 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13440 			goto slow_done;
13441 		/*
13442 		 * Make sure that first_mp points back to mp as
13443 		 * the mp we came in with could have changed in
13444 		 * ip_rput_fragment().
13445 		 */
13446 		ASSERT(!mctl_present);
13447 		ipha = (ipha_t *)mp->b_rptr;
13448 		first_mp = mp;
13449 	}
13450 
13451 	/* Now we have a complete datagram, destined for this machine. */
13452 	u1 = IPH_HDR_LENGTH(ipha);
13453 	goto find_sctp_client;
13454 #undef  iphs
13455 #undef  rptr
13456 
13457 error:
13458 	freemsg(first_mp);
13459 slow_done:
13460 	IRE_REFRELE(ire);
13461 }
13462 
13463 #define	VER_BITS	0xF0
13464 #define	VERSION_6	0x60
13465 
13466 static boolean_t
13467 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13468     ipaddr_t *dstp, ip_stack_t *ipst)
13469 {
13470 	uint_t	opt_len;
13471 	ipha_t *ipha;
13472 	ssize_t len;
13473 	uint_t	pkt_len;
13474 
13475 	ASSERT(ill != NULL);
13476 	IP_STAT(ipst, ip_ipoptions);
13477 	ipha = *iphapp;
13478 
13479 #define	rptr    ((uchar_t *)ipha)
13480 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13481 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13482 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13483 		freemsg(mp);
13484 		return (B_FALSE);
13485 	}
13486 
13487 	/* multiple mblk or too short */
13488 	pkt_len = ntohs(ipha->ipha_length);
13489 
13490 	/* Get the number of words of IP options in the IP header. */
13491 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13492 	if (opt_len) {
13493 		/* IP Options present!  Validate and process. */
13494 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13495 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13496 			goto done;
13497 		}
13498 		/*
13499 		 * Recompute complete header length and make sure we
13500 		 * have access to all of it.
13501 		 */
13502 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13503 		if (len > (mp->b_wptr - rptr)) {
13504 			if (len > pkt_len) {
13505 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13506 				goto done;
13507 			}
13508 			if (!pullupmsg(mp, len)) {
13509 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13510 				goto done;
13511 			}
13512 			ipha = (ipha_t *)mp->b_rptr;
13513 		}
13514 		/*
13515 		 * Go off to ip_rput_options which returns the next hop
13516 		 * destination address, which may have been affected
13517 		 * by source routing.
13518 		 */
13519 		IP_STAT(ipst, ip_opt);
13520 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13521 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13522 			return (B_FALSE);
13523 		}
13524 	}
13525 	*iphapp = ipha;
13526 	return (B_TRUE);
13527 done:
13528 	/* clear b_prev - used by ip_mroute_decap */
13529 	mp->b_prev = NULL;
13530 	freemsg(mp);
13531 	return (B_FALSE);
13532 #undef  rptr
13533 }
13534 
13535 /*
13536  * Deal with the fact that there is no ire for the destination.
13537  */
13538 static ire_t *
13539 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13540 {
13541 	ipha_t	*ipha;
13542 	ill_t	*ill;
13543 	ire_t	*ire;
13544 	ip_stack_t *ipst;
13545 	enum	ire_forward_action ret_action;
13546 
13547 	ipha = (ipha_t *)mp->b_rptr;
13548 	ill = (ill_t *)q->q_ptr;
13549 
13550 	ASSERT(ill != NULL);
13551 	ipst = ill->ill_ipst;
13552 
13553 	/*
13554 	 * No IRE for this destination, so it can't be for us.
13555 	 * Unless we are forwarding, drop the packet.
13556 	 * We have to let source routed packets through
13557 	 * since we don't yet know if they are 'ping -l'
13558 	 * packets i.e. if they will go out over the
13559 	 * same interface as they came in on.
13560 	 */
13561 	if (ll_multicast) {
13562 		freemsg(mp);
13563 		return (NULL);
13564 	}
13565 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13566 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13567 		freemsg(mp);
13568 		return (NULL);
13569 	}
13570 
13571 	/*
13572 	 * Mark this packet as having originated externally.
13573 	 *
13574 	 * For non-forwarding code path, ire_send later double
13575 	 * checks this interface to see if it is still exists
13576 	 * post-ARP resolution.
13577 	 *
13578 	 * Also, IPQOS uses this to differentiate between
13579 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13580 	 * QOS packet processing in ip_wput_attach_llhdr().
13581 	 * The QoS module can mark the b_band for a fastpath message
13582 	 * or the dl_priority field in a unitdata_req header for
13583 	 * CoS marking. This info can only be found in
13584 	 * ip_wput_attach_llhdr().
13585 	 */
13586 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13587 	/*
13588 	 * Clear the indication that this may have a hardware checksum
13589 	 * as we are not using it
13590 	 */
13591 	DB_CKSUMFLAGS(mp) = 0;
13592 
13593 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13594 	    msg_getlabel(mp), ipst);
13595 
13596 	if (ire == NULL && ret_action == Forward_check_multirt) {
13597 		/* Let ip_newroute handle CGTP  */
13598 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13599 		return (NULL);
13600 	}
13601 
13602 	if (ire != NULL)
13603 		return (ire);
13604 
13605 	mp->b_prev = mp->b_next = 0;
13606 
13607 	if (ret_action == Forward_blackhole) {
13608 		freemsg(mp);
13609 		return (NULL);
13610 	}
13611 	/* send icmp unreachable */
13612 	q = WR(q);
13613 	/* Sent by forwarding path, and router is global zone */
13614 	if (ip_source_routed(ipha, ipst)) {
13615 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13616 		    GLOBAL_ZONEID, ipst);
13617 	} else {
13618 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13619 		    ipst);
13620 	}
13621 
13622 	return (NULL);
13623 
13624 }
13625 
13626 /*
13627  * check ip header length and align it.
13628  */
13629 static boolean_t
13630 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13631 {
13632 	ssize_t len;
13633 	ill_t *ill;
13634 	ipha_t	*ipha;
13635 
13636 	len = MBLKL(mp);
13637 
13638 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13639 		ill = (ill_t *)q->q_ptr;
13640 
13641 		if (!OK_32PTR(mp->b_rptr))
13642 			IP_STAT(ipst, ip_notaligned1);
13643 		else
13644 			IP_STAT(ipst, ip_notaligned2);
13645 		/* Guard against bogus device drivers */
13646 		if (len < 0) {
13647 			/* clear b_prev - used by ip_mroute_decap */
13648 			mp->b_prev = NULL;
13649 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13650 			freemsg(mp);
13651 			return (B_FALSE);
13652 		}
13653 
13654 		if (ip_rput_pullups++ == 0) {
13655 			ipha = (ipha_t *)mp->b_rptr;
13656 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13657 			    "ip_check_and_align_header: %s forced us to "
13658 			    " pullup pkt, hdr len %ld, hdr addr %p",
13659 			    ill->ill_name, len, (void *)ipha);
13660 		}
13661 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13662 			/* clear b_prev - used by ip_mroute_decap */
13663 			mp->b_prev = NULL;
13664 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13665 			freemsg(mp);
13666 			return (B_FALSE);
13667 		}
13668 	}
13669 	return (B_TRUE);
13670 }
13671 
13672 /*
13673  * Handle the situation where a packet came in on `ill' but matched an IRE
13674  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13675  * for interface statistics.
13676  */
13677 ire_t *
13678 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13679 {
13680 	ire_t		*new_ire;
13681 	ill_t		*ire_ill;
13682 	uint_t		ifindex;
13683 	ip_stack_t	*ipst = ill->ill_ipst;
13684 	boolean_t	strict_check = B_FALSE;
13685 
13686 	/*
13687 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13688 	 * issue (e.g. packet received on an underlying interface matched an
13689 	 * IRE_LOCAL on its associated group interface).
13690 	 */
13691 	if (ire->ire_rfq != NULL &&
13692 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13693 		return (ire);
13694 	}
13695 
13696 	/*
13697 	 * Do another ire lookup here, using the ingress ill, to see if the
13698 	 * interface is in a usesrc group.
13699 	 * As long as the ills belong to the same group, we don't consider
13700 	 * them to be arriving on the wrong interface. Thus, if the switch
13701 	 * is doing inbound load spreading, we won't drop packets when the
13702 	 * ip*_strict_dst_multihoming switch is on.
13703 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13704 	 * where the local address may not be unique. In this case we were
13705 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13706 	 * actually returned. The new lookup, which is more specific, should
13707 	 * only find the IRE_LOCAL associated with the ingress ill if one
13708 	 * exists.
13709 	 */
13710 
13711 	if (ire->ire_ipversion == IPV4_VERSION) {
13712 		if (ipst->ips_ip_strict_dst_multihoming)
13713 			strict_check = B_TRUE;
13714 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13715 		    ill->ill_ipif, ALL_ZONES, NULL,
13716 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13717 	} else {
13718 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13719 		if (ipst->ips_ipv6_strict_dst_multihoming)
13720 			strict_check = B_TRUE;
13721 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13722 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13723 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13724 	}
13725 	/*
13726 	 * If the same ire that was returned in ip_input() is found then this
13727 	 * is an indication that usesrc groups are in use. The packet
13728 	 * arrived on a different ill in the group than the one associated with
13729 	 * the destination address.  If a different ire was found then the same
13730 	 * IP address must be hosted on multiple ills. This is possible with
13731 	 * unnumbered point2point interfaces. We switch to use this new ire in
13732 	 * order to have accurate interface statistics.
13733 	 */
13734 	if (new_ire != NULL) {
13735 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13736 			ire_refrele(ire);
13737 			ire = new_ire;
13738 		} else {
13739 			ire_refrele(new_ire);
13740 		}
13741 		return (ire);
13742 	} else if ((ire->ire_rfq == NULL) &&
13743 	    (ire->ire_ipversion == IPV4_VERSION)) {
13744 		/*
13745 		 * The best match could have been the original ire which
13746 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13747 		 * the strict multihoming checks are irrelevant as we consider
13748 		 * local addresses hosted on lo0 to be interface agnostic. We
13749 		 * only expect a null ire_rfq on IREs which are associated with
13750 		 * lo0 hence we can return now.
13751 		 */
13752 		return (ire);
13753 	}
13754 
13755 	/*
13756 	 * Chase pointers once and store locally.
13757 	 */
13758 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13759 	    (ill_t *)(ire->ire_rfq->q_ptr);
13760 	ifindex = ill->ill_usesrc_ifindex;
13761 
13762 	/*
13763 	 * Check if it's a legal address on the 'usesrc' interface.
13764 	 */
13765 	if ((ifindex != 0) && (ire_ill != NULL) &&
13766 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13767 		return (ire);
13768 	}
13769 
13770 	/*
13771 	 * If the ip*_strict_dst_multihoming switch is on then we can
13772 	 * only accept this packet if the interface is marked as routing.
13773 	 */
13774 	if (!(strict_check))
13775 		return (ire);
13776 
13777 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13778 	    ILLF_ROUTER) != 0) {
13779 		return (ire);
13780 	}
13781 
13782 	ire_refrele(ire);
13783 	return (NULL);
13784 }
13785 
13786 /*
13787  *
13788  * This is the fast forward path. If we are here, we dont need to
13789  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13790  * needed to find the nexthop in this case is much simpler
13791  */
13792 ire_t *
13793 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13794 {
13795 	ipha_t	*ipha;
13796 	ire_t	*src_ire;
13797 	ill_t	*stq_ill;
13798 	uint_t	hlen;
13799 	uint_t	pkt_len;
13800 	uint32_t sum;
13801 	queue_t	*dev_q;
13802 	ip_stack_t *ipst = ill->ill_ipst;
13803 	mblk_t *fpmp;
13804 	enum	ire_forward_action ret_action;
13805 
13806 	ipha = (ipha_t *)mp->b_rptr;
13807 
13808 	if (ire != NULL &&
13809 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13810 	    ire->ire_zoneid != ALL_ZONES) {
13811 		/*
13812 		 * Should only use IREs that are visible to the global
13813 		 * zone for forwarding.
13814 		 */
13815 		ire_refrele(ire);
13816 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13817 		/*
13818 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13819 		 * transient cases. In such case, just drop the packet
13820 		 */
13821 		if (ire != NULL && ire->ire_type != IRE_CACHE)
13822 			goto indiscard;
13823 	}
13824 
13825 	/*
13826 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13827 	 * The loopback address check for both src and dst has already
13828 	 * been checked in ip_input
13829 	 */
13830 
13831 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13832 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13833 		goto drop;
13834 	}
13835 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13836 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13837 
13838 	if (src_ire != NULL) {
13839 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13840 		ire_refrele(src_ire);
13841 		goto drop;
13842 	}
13843 
13844 	/* No ire cache of nexthop. So first create one  */
13845 	if (ire == NULL) {
13846 
13847 		ire = ire_forward_simple(dst, &ret_action, ipst);
13848 
13849 		/*
13850 		 * We only come to ip_fast_forward if ip_cgtp_filter
13851 		 * is not set. So ire_forward() should not return with
13852 		 * Forward_check_multirt as the next action.
13853 		 */
13854 		ASSERT(ret_action != Forward_check_multirt);
13855 		if (ire == NULL) {
13856 			/* An attempt was made to forward the packet */
13857 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13858 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13859 			mp->b_prev = mp->b_next = 0;
13860 			/* send icmp unreachable */
13861 			/* Sent by forwarding path, and router is global zone */
13862 			if (ret_action == Forward_ret_icmp_err) {
13863 				if (ip_source_routed(ipha, ipst)) {
13864 					icmp_unreachable(ill->ill_wq, mp,
13865 					    ICMP_SOURCE_ROUTE_FAILED,
13866 					    GLOBAL_ZONEID, ipst);
13867 				} else {
13868 					icmp_unreachable(ill->ill_wq, mp,
13869 					    ICMP_HOST_UNREACHABLE,
13870 					    GLOBAL_ZONEID, ipst);
13871 				}
13872 			} else {
13873 				freemsg(mp);
13874 			}
13875 			return (NULL);
13876 		}
13877 	}
13878 
13879 	/*
13880 	 * Forwarding fastpath exception case:
13881 	 * If any of the following are true, we take the slowpath:
13882 	 *	o forwarding is not enabled
13883 	 *	o incoming and outgoing interface are the same, or in the same
13884 	 *	  IPMP group.
13885 	 *	o corresponding ire is in incomplete state
13886 	 *	o packet needs fragmentation
13887 	 *	o ARP cache is not resolved
13888 	 *
13889 	 * The codeflow from here on is thus:
13890 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13891 	 */
13892 	pkt_len = ntohs(ipha->ipha_length);
13893 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13894 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13895 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13896 	    (ire->ire_nce == NULL) ||
13897 	    (pkt_len > ire->ire_max_frag) ||
13898 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13899 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13900 	    ipha->ipha_ttl <= 1) {
13901 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13902 		    ipha, ill, B_FALSE, B_TRUE);
13903 		return (ire);
13904 	}
13905 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13906 
13907 	DTRACE_PROBE4(ip4__forwarding__start,
13908 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13909 
13910 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13911 	    ipst->ips_ipv4firewall_forwarding,
13912 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13913 
13914 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13915 
13916 	if (mp == NULL)
13917 		goto drop;
13918 
13919 	mp->b_datap->db_struioun.cksum.flags = 0;
13920 	/* Adjust the checksum to reflect the ttl decrement. */
13921 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13922 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13923 	ipha->ipha_ttl--;
13924 
13925 	/*
13926 	 * Write the link layer header.  We can do this safely here,
13927 	 * because we have already tested to make sure that the IP
13928 	 * policy is not set, and that we have a fast path destination
13929 	 * header.
13930 	 */
13931 	mp->b_rptr -= hlen;
13932 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13933 
13934 	UPDATE_IB_PKT_COUNT(ire);
13935 	ire->ire_last_used_time = lbolt;
13936 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13937 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13938 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13939 
13940 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13941 		dev_q = ire->ire_stq->q_next;
13942 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13943 			goto indiscard;
13944 	}
13945 
13946 	DTRACE_PROBE4(ip4__physical__out__start,
13947 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13948 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13949 	    ipst->ips_ipv4firewall_physical_out,
13950 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13951 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13952 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13953 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13954 	    ip6_t *, NULL, int, 0);
13955 
13956 	if (mp != NULL) {
13957 		if (ipst->ips_ip4_observe.he_interested) {
13958 			zoneid_t szone;
13959 
13960 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13961 			    ipst, ALL_ZONES);
13962 			/*
13963 			 * The IP observability hook expects b_rptr to be
13964 			 * where the IP header starts, so advance past the
13965 			 * link layer header.
13966 			 */
13967 			mp->b_rptr += hlen;
13968 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
13969 			    ALL_ZONES, ill, ipst);
13970 			mp->b_rptr -= hlen;
13971 		}
13972 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
13973 	}
13974 	return (ire);
13975 
13976 indiscard:
13977 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13978 drop:
13979 	if (mp != NULL)
13980 		freemsg(mp);
13981 	return (ire);
13982 
13983 }
13984 
13985 /*
13986  * This function is called in the forwarding slowpath, when
13987  * either the ire lacks the link-layer address, or the packet needs
13988  * further processing(eg. fragmentation), before transmission.
13989  */
13990 
13991 static void
13992 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13993     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
13994 {
13995 	queue_t		*dev_q;
13996 	ire_t		*src_ire;
13997 	ip_stack_t	*ipst = ill->ill_ipst;
13998 	boolean_t	same_illgrp = B_FALSE;
13999 
14000 	ASSERT(ire->ire_stq != NULL);
14001 
14002 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14003 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14004 
14005 	/*
14006 	 * If the caller of this function is ip_fast_forward() skip the
14007 	 * next three checks as it does not apply.
14008 	 */
14009 	if (from_ip_fast_forward)
14010 		goto skip;
14011 
14012 	if (ll_multicast != 0) {
14013 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14014 		goto drop_pkt;
14015 	}
14016 
14017 	/*
14018 	 * check if ipha_src is a broadcast address. Note that this
14019 	 * check is redundant when we get here from ip_fast_forward()
14020 	 * which has already done this check. However, since we can
14021 	 * also get here from ip_rput_process_broadcast() or, for
14022 	 * for the slow path through ip_fast_forward(), we perform
14023 	 * the check again for code-reusability
14024 	 */
14025 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14026 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14027 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14028 		if (src_ire != NULL)
14029 			ire_refrele(src_ire);
14030 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14031 		ip2dbg(("ip_rput_process_forward: Received packet with"
14032 		    " bad src/dst address on %s\n", ill->ill_name));
14033 		goto drop_pkt;
14034 	}
14035 
14036 	/*
14037 	 * Check if we want to forward this one at this time.
14038 	 * We allow source routed packets on a host provided that
14039 	 * they go out the same ill or illgrp as they came in on.
14040 	 *
14041 	 * XXX To be quicker, we may wish to not chase pointers to
14042 	 * get the ILLF_ROUTER flag and instead store the
14043 	 * forwarding policy in the ire.  An unfortunate
14044 	 * side-effect of that would be requiring an ire flush
14045 	 * whenever the ILLF_ROUTER flag changes.
14046 	 */
14047 skip:
14048 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14049 
14050 	if (((ill->ill_flags &
14051 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14052 	    !(ip_source_routed(ipha, ipst) &&
14053 	    (ire->ire_rfq == q || same_illgrp))) {
14054 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14055 		if (ip_source_routed(ipha, ipst)) {
14056 			q = WR(q);
14057 			/*
14058 			 * Clear the indication that this may have
14059 			 * hardware checksum as we are not using it.
14060 			 */
14061 			DB_CKSUMFLAGS(mp) = 0;
14062 			/* Sent by forwarding path, and router is global zone */
14063 			icmp_unreachable(q, mp,
14064 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14065 			return;
14066 		}
14067 		goto drop_pkt;
14068 	}
14069 
14070 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14071 
14072 	/* Packet is being forwarded. Turning off hwcksum flag. */
14073 	DB_CKSUMFLAGS(mp) = 0;
14074 	if (ipst->ips_ip_g_send_redirects) {
14075 		/*
14076 		 * Check whether the incoming interface and outgoing
14077 		 * interface is part of the same group. If so,
14078 		 * send redirects.
14079 		 *
14080 		 * Check the source address to see if it originated
14081 		 * on the same logical subnet it is going back out on.
14082 		 * If so, we should be able to send it a redirect.
14083 		 * Avoid sending a redirect if the destination
14084 		 * is directly connected (i.e., ipha_dst is the same
14085 		 * as ire_gateway_addr or the ire_addr of the
14086 		 * nexthop IRE_CACHE ), or if the packet was source
14087 		 * routed out this interface.
14088 		 */
14089 		ipaddr_t src, nhop;
14090 		mblk_t	*mp1;
14091 		ire_t	*nhop_ire = NULL;
14092 
14093 		/*
14094 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14095 		 * If so, send redirects.
14096 		 */
14097 		if ((ire->ire_rfq == q || same_illgrp) &&
14098 		    !ip_source_routed(ipha, ipst)) {
14099 
14100 			nhop = (ire->ire_gateway_addr != 0 ?
14101 			    ire->ire_gateway_addr : ire->ire_addr);
14102 
14103 			if (ipha->ipha_dst == nhop) {
14104 				/*
14105 				 * We avoid sending a redirect if the
14106 				 * destination is directly connected
14107 				 * because it is possible that multiple
14108 				 * IP subnets may have been configured on
14109 				 * the link, and the source may not
14110 				 * be on the same subnet as ip destination,
14111 				 * even though they are on the same
14112 				 * physical link.
14113 				 */
14114 				goto sendit;
14115 			}
14116 
14117 			src = ipha->ipha_src;
14118 
14119 			/*
14120 			 * We look up the interface ire for the nexthop,
14121 			 * to see if ipha_src is in the same subnet
14122 			 * as the nexthop.
14123 			 *
14124 			 * Note that, if, in the future, IRE_CACHE entries
14125 			 * are obsoleted,  this lookup will not be needed,
14126 			 * as the ire passed to this function will be the
14127 			 * same as the nhop_ire computed below.
14128 			 */
14129 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14130 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14131 			    0, NULL, MATCH_IRE_TYPE, ipst);
14132 
14133 			if (nhop_ire != NULL) {
14134 				if ((src & nhop_ire->ire_mask) ==
14135 				    (nhop & nhop_ire->ire_mask)) {
14136 					/*
14137 					 * The source is directly connected.
14138 					 * Just copy the ip header (which is
14139 					 * in the first mblk)
14140 					 */
14141 					mp1 = copyb(mp);
14142 					if (mp1 != NULL) {
14143 						icmp_send_redirect(WR(q), mp1,
14144 						    nhop, ipst);
14145 					}
14146 				}
14147 				ire_refrele(nhop_ire);
14148 			}
14149 		}
14150 	}
14151 sendit:
14152 	dev_q = ire->ire_stq->q_next;
14153 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14154 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14155 		freemsg(mp);
14156 		return;
14157 	}
14158 
14159 	ip_rput_forward(ire, ipha, mp, ill);
14160 	return;
14161 
14162 drop_pkt:
14163 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14164 	freemsg(mp);
14165 }
14166 
14167 ire_t *
14168 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14169     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14170 {
14171 	queue_t		*q;
14172 	uint16_t	hcksumflags;
14173 	ip_stack_t	*ipst = ill->ill_ipst;
14174 
14175 	q = *qp;
14176 
14177 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14178 
14179 	/*
14180 	 * Clear the indication that this may have hardware
14181 	 * checksum as we are not using it for forwarding.
14182 	 */
14183 	hcksumflags = DB_CKSUMFLAGS(mp);
14184 	DB_CKSUMFLAGS(mp) = 0;
14185 
14186 	/*
14187 	 * Directed broadcast forwarding: if the packet came in over a
14188 	 * different interface then it is routed out over we can forward it.
14189 	 */
14190 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14191 		ire_refrele(ire);
14192 		freemsg(mp);
14193 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14194 		return (NULL);
14195 	}
14196 	/*
14197 	 * For multicast we have set dst to be INADDR_BROADCAST
14198 	 * for delivering to all STREAMS.
14199 	 */
14200 	if (!CLASSD(ipha->ipha_dst)) {
14201 		ire_t *new_ire;
14202 		ipif_t *ipif;
14203 
14204 		ipif = ipif_get_next_ipif(NULL, ill);
14205 		if (ipif == NULL) {
14206 discard:		ire_refrele(ire);
14207 			freemsg(mp);
14208 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14209 			return (NULL);
14210 		}
14211 		new_ire = ire_ctable_lookup(dst, 0, 0,
14212 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14213 		ipif_refrele(ipif);
14214 
14215 		if (new_ire != NULL) {
14216 			/*
14217 			 * If the matching IRE_BROADCAST is part of an IPMP
14218 			 * group, then drop the packet unless our ill has been
14219 			 * nominated to receive for the group.
14220 			 */
14221 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14222 			    new_ire->ire_rfq != q) {
14223 				ire_refrele(new_ire);
14224 				goto discard;
14225 			}
14226 
14227 			/*
14228 			 * In the special case of multirouted broadcast
14229 			 * packets, we unconditionally need to "gateway"
14230 			 * them to the appropriate interface here.
14231 			 * In the normal case, this cannot happen, because
14232 			 * there is no broadcast IRE tagged with the
14233 			 * RTF_MULTIRT flag.
14234 			 */
14235 			if (new_ire->ire_flags & RTF_MULTIRT) {
14236 				ire_refrele(new_ire);
14237 				if (ire->ire_rfq != NULL) {
14238 					q = ire->ire_rfq;
14239 					*qp = q;
14240 				}
14241 			} else {
14242 				ire_refrele(ire);
14243 				ire = new_ire;
14244 			}
14245 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14246 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14247 				/*
14248 				 * Free the message if
14249 				 * ip_g_forward_directed_bcast is turned
14250 				 * off for non-local broadcast.
14251 				 */
14252 				ire_refrele(ire);
14253 				freemsg(mp);
14254 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14255 				return (NULL);
14256 			}
14257 		} else {
14258 			/*
14259 			 * This CGTP packet successfully passed the
14260 			 * CGTP filter, but the related CGTP
14261 			 * broadcast IRE has not been found,
14262 			 * meaning that the redundant ipif is
14263 			 * probably down. However, if we discarded
14264 			 * this packet, its duplicate would be
14265 			 * filtered out by the CGTP filter so none
14266 			 * of them would get through. So we keep
14267 			 * going with this one.
14268 			 */
14269 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14270 			if (ire->ire_rfq != NULL) {
14271 				q = ire->ire_rfq;
14272 				*qp = q;
14273 			}
14274 		}
14275 	}
14276 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14277 		/*
14278 		 * Verify that there are not more then one
14279 		 * IRE_BROADCAST with this broadcast address which
14280 		 * has ire_stq set.
14281 		 * TODO: simplify, loop over all IRE's
14282 		 */
14283 		ire_t	*ire1;
14284 		int	num_stq = 0;
14285 		mblk_t	*mp1;
14286 
14287 		/* Find the first one with ire_stq set */
14288 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14289 		for (ire1 = ire; ire1 &&
14290 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14291 		    ire1 = ire1->ire_next)
14292 			;
14293 		if (ire1) {
14294 			ire_refrele(ire);
14295 			ire = ire1;
14296 			IRE_REFHOLD(ire);
14297 		}
14298 
14299 		/* Check if there are additional ones with stq set */
14300 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14301 			if (ire->ire_addr != ire1->ire_addr)
14302 				break;
14303 			if (ire1->ire_stq) {
14304 				num_stq++;
14305 				break;
14306 			}
14307 		}
14308 		rw_exit(&ire->ire_bucket->irb_lock);
14309 		if (num_stq == 1 && ire->ire_stq != NULL) {
14310 			ip1dbg(("ip_rput_process_broadcast: directed "
14311 			    "broadcast to 0x%x\n",
14312 			    ntohl(ire->ire_addr)));
14313 			mp1 = copymsg(mp);
14314 			if (mp1) {
14315 				switch (ipha->ipha_protocol) {
14316 				case IPPROTO_UDP:
14317 					ip_udp_input(q, mp1, ipha, ire, ill);
14318 					break;
14319 				default:
14320 					ip_proto_input(q, mp1, ipha, ire, ill,
14321 					    0);
14322 					break;
14323 				}
14324 			}
14325 			/*
14326 			 * Adjust ttl to 2 (1+1 - the forward engine
14327 			 * will decrement it by one.
14328 			 */
14329 			if (ip_csum_hdr(ipha)) {
14330 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14331 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14332 				freemsg(mp);
14333 				ire_refrele(ire);
14334 				return (NULL);
14335 			}
14336 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14337 			ipha->ipha_hdr_checksum = 0;
14338 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14339 			ip_rput_process_forward(q, mp, ire, ipha,
14340 			    ill, ll_multicast, B_FALSE);
14341 			ire_refrele(ire);
14342 			return (NULL);
14343 		}
14344 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14345 		    ntohl(ire->ire_addr)));
14346 	}
14347 
14348 	/* Restore any hardware checksum flags */
14349 	DB_CKSUMFLAGS(mp) = hcksumflags;
14350 	return (ire);
14351 }
14352 
14353 /* ARGSUSED */
14354 static boolean_t
14355 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14356     int *ll_multicast, ipaddr_t *dstp)
14357 {
14358 	ip_stack_t	*ipst = ill->ill_ipst;
14359 
14360 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14361 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14362 	    ntohs(ipha->ipha_length));
14363 
14364 	/*
14365 	 * So that we don't end up with dups, only one ill in an IPMP group is
14366 	 * nominated to receive multicast traffic.
14367 	 */
14368 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14369 		goto drop_pkt;
14370 
14371 	/*
14372 	 * Forward packets only if we have joined the allmulti
14373 	 * group on this interface.
14374 	 */
14375 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14376 		int retval;
14377 
14378 		/*
14379 		 * Clear the indication that this may have hardware
14380 		 * checksum as we are not using it.
14381 		 */
14382 		DB_CKSUMFLAGS(mp) = 0;
14383 		retval = ip_mforward(ill, ipha, mp);
14384 		/* ip_mforward updates mib variables if needed */
14385 		/* clear b_prev - used by ip_mroute_decap */
14386 		mp->b_prev = NULL;
14387 
14388 		switch (retval) {
14389 		case 0:
14390 			/*
14391 			 * pkt is okay and arrived on phyint.
14392 			 *
14393 			 * If we are running as a multicast router
14394 			 * we need to see all IGMP and/or PIM packets.
14395 			 */
14396 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14397 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14398 				goto done;
14399 			}
14400 			break;
14401 		case -1:
14402 			/* pkt is mal-formed, toss it */
14403 			goto drop_pkt;
14404 		case 1:
14405 			/* pkt is okay and arrived on a tunnel */
14406 			/*
14407 			 * If we are running a multicast router
14408 			 *  we need to see all igmp packets.
14409 			 */
14410 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14411 				*dstp = INADDR_BROADCAST;
14412 				*ll_multicast = 1;
14413 				return (B_FALSE);
14414 			}
14415 
14416 			goto drop_pkt;
14417 		}
14418 	}
14419 
14420 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14421 		/*
14422 		 * This might just be caused by the fact that
14423 		 * multiple IP Multicast addresses map to the same
14424 		 * link layer multicast - no need to increment counter!
14425 		 */
14426 		freemsg(mp);
14427 		return (B_TRUE);
14428 	}
14429 done:
14430 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14431 	/*
14432 	 * This assumes the we deliver to all streams for multicast
14433 	 * and broadcast packets.
14434 	 */
14435 	*dstp = INADDR_BROADCAST;
14436 	*ll_multicast = 1;
14437 	return (B_FALSE);
14438 drop_pkt:
14439 	ip2dbg(("ip_rput: drop pkt\n"));
14440 	freemsg(mp);
14441 	return (B_TRUE);
14442 }
14443 
14444 /*
14445  * This function is used to both return an indication of whether or not
14446  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14447  * and in doing so, determine whether or not it is broadcast vs multicast.
14448  * For it to be a broadcast packet, we must have the appropriate mblk_t
14449  * hanging off the ill_t.  If this is either not present or doesn't match
14450  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14451  * to be multicast.  Thus NICs that have no broadcast address (or no
14452  * capability for one, such as point to point links) cannot return as
14453  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14454  * the return values simplifies the current use of the return value of this
14455  * function, which is to pass through the multicast/broadcast characteristic
14456  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14457  * changing the return value to some other symbol demands the appropriate
14458  * "translation" when hpe_flags is set prior to calling hook_run() for
14459  * packet events.
14460  */
14461 int
14462 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14463 {
14464 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14465 	mblk_t *bmp;
14466 
14467 	if (ind->dl_group_address) {
14468 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14469 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14470 		    MBLKL(mb) &&
14471 		    (bmp = ill->ill_bcast_mp) != NULL) {
14472 			dl_unitdata_req_t *dlur;
14473 			uint8_t *bphys_addr;
14474 
14475 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14476 			if (ill->ill_sap_length < 0)
14477 				bphys_addr = (uchar_t *)dlur +
14478 				    dlur->dl_dest_addr_offset;
14479 			else
14480 				bphys_addr = (uchar_t *)dlur +
14481 				    dlur->dl_dest_addr_offset +
14482 				    ill->ill_sap_length;
14483 
14484 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14485 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14486 				return (HPE_BROADCAST);
14487 			}
14488 			return (HPE_MULTICAST);
14489 		}
14490 		return (HPE_MULTICAST);
14491 	}
14492 	return (0);
14493 }
14494 
14495 static boolean_t
14496 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14497     int *ll_multicast, mblk_t **mpp)
14498 {
14499 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14500 	boolean_t must_copy = B_FALSE;
14501 	struct iocblk   *iocp;
14502 	ipha_t		*ipha;
14503 	ip_stack_t	*ipst = ill->ill_ipst;
14504 
14505 #define	rptr    ((uchar_t *)ipha)
14506 
14507 	first_mp = *first_mpp;
14508 	mp = *mpp;
14509 
14510 	ASSERT(first_mp == mp);
14511 
14512 	/*
14513 	 * if db_ref > 1 then copymsg and free original. Packet may be
14514 	 * changed and do not want other entity who has a reference to this
14515 	 * message to trip over the changes. This is a blind change because
14516 	 * trying to catch all places that might change packet is too
14517 	 * difficult (since it may be a module above this one)
14518 	 *
14519 	 * This corresponds to the non-fast path case. We walk down the full
14520 	 * chain in this case, and check the db_ref count of all the dblks,
14521 	 * and do a copymsg if required. It is possible that the db_ref counts
14522 	 * of the data blocks in the mblk chain can be different.
14523 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14524 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14525 	 * 'snoop' is running.
14526 	 */
14527 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14528 		if (mp1->b_datap->db_ref > 1) {
14529 			must_copy = B_TRUE;
14530 			break;
14531 		}
14532 	}
14533 
14534 	if (must_copy) {
14535 		mp1 = copymsg(mp);
14536 		if (mp1 == NULL) {
14537 			for (mp1 = mp; mp1 != NULL;
14538 			    mp1 = mp1->b_cont) {
14539 				mp1->b_next = NULL;
14540 				mp1->b_prev = NULL;
14541 			}
14542 			freemsg(mp);
14543 			if (ill != NULL) {
14544 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14545 			} else {
14546 				BUMP_MIB(&ipst->ips_ip_mib,
14547 				    ipIfStatsInDiscards);
14548 			}
14549 			return (B_TRUE);
14550 		}
14551 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14552 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14553 			/* Copy b_prev - used by ip_mroute_decap */
14554 			to_mp->b_prev = from_mp->b_prev;
14555 			from_mp->b_prev = NULL;
14556 		}
14557 		*first_mpp = first_mp = mp1;
14558 		freemsg(mp);
14559 		mp = mp1;
14560 		*mpp = mp1;
14561 	}
14562 
14563 	ipha = (ipha_t *)mp->b_rptr;
14564 
14565 	/*
14566 	 * previous code has a case for M_DATA.
14567 	 * We want to check how that happens.
14568 	 */
14569 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14570 	switch (first_mp->b_datap->db_type) {
14571 	case M_PROTO:
14572 	case M_PCPROTO:
14573 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14574 		    DL_UNITDATA_IND) {
14575 			/* Go handle anything other than data elsewhere. */
14576 			ip_rput_dlpi(q, mp);
14577 			return (B_TRUE);
14578 		}
14579 
14580 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14581 		/* Ditch the DLPI header. */
14582 		mp1 = mp->b_cont;
14583 		ASSERT(first_mp == mp);
14584 		*first_mpp = mp1;
14585 		freeb(mp);
14586 		*mpp = mp1;
14587 		return (B_FALSE);
14588 	case M_IOCACK:
14589 		ip1dbg(("got iocack "));
14590 		iocp = (struct iocblk *)mp->b_rptr;
14591 		switch (iocp->ioc_cmd) {
14592 		case DL_IOC_HDR_INFO:
14593 			ill = (ill_t *)q->q_ptr;
14594 			ill_fastpath_ack(ill, mp);
14595 			return (B_TRUE);
14596 		default:
14597 			putnext(q, mp);
14598 			return (B_TRUE);
14599 		}
14600 		/* FALLTHRU */
14601 	case M_ERROR:
14602 	case M_HANGUP:
14603 		/*
14604 		 * Since this is on the ill stream we unconditionally
14605 		 * bump up the refcount
14606 		 */
14607 		ill_refhold(ill);
14608 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14609 		return (B_TRUE);
14610 	case M_CTL:
14611 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14612 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14613 		    IPHADA_M_CTL)) {
14614 			/*
14615 			 * It's an IPsec accelerated packet.
14616 			 * Make sure that the ill from which we received the
14617 			 * packet has enabled IPsec hardware acceleration.
14618 			 */
14619 			if (!(ill->ill_capabilities &
14620 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14621 				/* IPsec kstats: bean counter */
14622 				freemsg(mp);
14623 				return (B_TRUE);
14624 			}
14625 
14626 			/*
14627 			 * Make mp point to the mblk following the M_CTL,
14628 			 * then process according to type of mp.
14629 			 * After this processing, first_mp will point to
14630 			 * the data-attributes and mp to the pkt following
14631 			 * the M_CTL.
14632 			 */
14633 			mp = first_mp->b_cont;
14634 			if (mp == NULL) {
14635 				freemsg(first_mp);
14636 				return (B_TRUE);
14637 			}
14638 			/*
14639 			 * A Hardware Accelerated packet can only be M_DATA
14640 			 * ESP or AH packet.
14641 			 */
14642 			if (mp->b_datap->db_type != M_DATA) {
14643 				/* non-M_DATA IPsec accelerated packet */
14644 				IPSECHW_DEBUG(IPSECHW_PKT,
14645 				    ("non-M_DATA IPsec accelerated pkt\n"));
14646 				freemsg(first_mp);
14647 				return (B_TRUE);
14648 			}
14649 			ipha = (ipha_t *)mp->b_rptr;
14650 			if (ipha->ipha_protocol != IPPROTO_AH &&
14651 			    ipha->ipha_protocol != IPPROTO_ESP) {
14652 				IPSECHW_DEBUG(IPSECHW_PKT,
14653 				    ("non-M_DATA IPsec accelerated pkt\n"));
14654 				freemsg(first_mp);
14655 				return (B_TRUE);
14656 			}
14657 			*mpp = mp;
14658 			return (B_FALSE);
14659 		}
14660 		putnext(q, mp);
14661 		return (B_TRUE);
14662 	case M_IOCNAK:
14663 		ip1dbg(("got iocnak "));
14664 		iocp = (struct iocblk *)mp->b_rptr;
14665 		switch (iocp->ioc_cmd) {
14666 		case DL_IOC_HDR_INFO:
14667 			ip_rput_other(NULL, q, mp, NULL);
14668 			return (B_TRUE);
14669 		default:
14670 			break;
14671 		}
14672 		/* FALLTHRU */
14673 	default:
14674 		putnext(q, mp);
14675 		return (B_TRUE);
14676 	}
14677 }
14678 
14679 /* Read side put procedure.  Packets coming from the wire arrive here. */
14680 void
14681 ip_rput(queue_t *q, mblk_t *mp)
14682 {
14683 	ill_t	*ill;
14684 	union DL_primitives *dl;
14685 
14686 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14687 
14688 	ill = (ill_t *)q->q_ptr;
14689 
14690 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14691 		/*
14692 		 * If things are opening or closing, only accept high-priority
14693 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14694 		 * created; on close, things hanging off the ill may have been
14695 		 * freed already.)
14696 		 */
14697 		dl = (union DL_primitives *)mp->b_rptr;
14698 		if (DB_TYPE(mp) != M_PCPROTO ||
14699 		    dl->dl_primitive == DL_UNITDATA_IND) {
14700 			inet_freemsg(mp);
14701 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14702 			    "ip_rput_end: q %p (%S)", q, "uninit");
14703 			return;
14704 		}
14705 	}
14706 
14707 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14708 	    "ip_rput_end: q %p (%S)", q, "end");
14709 
14710 	ip_input(ill, NULL, mp, NULL);
14711 }
14712 
14713 static mblk_t *
14714 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14715 {
14716 	mblk_t *mp1;
14717 	boolean_t adjusted = B_FALSE;
14718 	ip_stack_t *ipst = ill->ill_ipst;
14719 
14720 	IP_STAT(ipst, ip_db_ref);
14721 	/*
14722 	 * The IP_RECVSLLA option depends on having the
14723 	 * link layer header. First check that:
14724 	 * a> the underlying device is of type ether,
14725 	 * since this option is currently supported only
14726 	 * over ethernet.
14727 	 * b> there is enough room to copy over the link
14728 	 * layer header.
14729 	 *
14730 	 * Once the checks are done, adjust rptr so that
14731 	 * the link layer header will be copied via
14732 	 * copymsg. Note that, IFT_ETHER may be returned
14733 	 * by some non-ethernet drivers but in this case
14734 	 * the second check will fail.
14735 	 */
14736 	if (ill->ill_type == IFT_ETHER &&
14737 	    (mp->b_rptr - mp->b_datap->db_base) >=
14738 	    sizeof (struct ether_header)) {
14739 		mp->b_rptr -= sizeof (struct ether_header);
14740 		adjusted = B_TRUE;
14741 	}
14742 	mp1 = copymsg(mp);
14743 
14744 	if (mp1 == NULL) {
14745 		mp->b_next = NULL;
14746 		/* clear b_prev - used by ip_mroute_decap */
14747 		mp->b_prev = NULL;
14748 		freemsg(mp);
14749 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14750 		return (NULL);
14751 	}
14752 
14753 	if (adjusted) {
14754 		/*
14755 		 * Copy is done. Restore the pointer in
14756 		 * the _new_ mblk
14757 		 */
14758 		mp1->b_rptr += sizeof (struct ether_header);
14759 	}
14760 
14761 	/* Copy b_prev - used by ip_mroute_decap */
14762 	mp1->b_prev = mp->b_prev;
14763 	mp->b_prev = NULL;
14764 
14765 	/* preserve the hardware checksum flags and data, if present */
14766 	if (DB_CKSUMFLAGS(mp) != 0) {
14767 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14768 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14769 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14770 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14771 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14772 	}
14773 
14774 	freemsg(mp);
14775 	return (mp1);
14776 }
14777 
14778 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14779 	if (tail != NULL)					\
14780 		tail->b_next = mp;				\
14781 	else							\
14782 		head = mp;					\
14783 	tail = mp;						\
14784 	cnt++;							\
14785 }
14786 
14787 /*
14788  * Direct read side procedure capable of dealing with chains. GLDv3 based
14789  * drivers call this function directly with mblk chains while STREAMS
14790  * read side procedure ip_rput() calls this for single packet with ip_ring
14791  * set to NULL to process one packet at a time.
14792  *
14793  * The ill will always be valid if this function is called directly from
14794  * the driver.
14795  *
14796  * If ip_input() is called from GLDv3:
14797  *
14798  *   - This must be a non-VLAN IP stream.
14799  *   - 'mp' is either an untagged or a special priority-tagged packet.
14800  *   - Any VLAN tag that was in the MAC header has been stripped.
14801  *
14802  * If the IP header in packet is not 32-bit aligned, every message in the
14803  * chain will be aligned before further operations. This is required on SPARC
14804  * platform.
14805  */
14806 /* ARGSUSED */
14807 void
14808 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14809     struct mac_header_info_s *mhip)
14810 {
14811 	ipaddr_t		dst = NULL;
14812 	ipaddr_t		prev_dst;
14813 	ire_t			*ire = NULL;
14814 	ipha_t			*ipha;
14815 	uint_t			pkt_len;
14816 	ssize_t			len;
14817 	uint_t			opt_len;
14818 	int			ll_multicast;
14819 	int			cgtp_flt_pkt;
14820 	queue_t			*q = ill->ill_rq;
14821 	squeue_t		*curr_sqp = NULL;
14822 	mblk_t 			*head = NULL;
14823 	mblk_t			*tail = NULL;
14824 	mblk_t			*first_mp;
14825 	int			cnt = 0;
14826 	ip_stack_t		*ipst = ill->ill_ipst;
14827 	mblk_t			*mp;
14828 	mblk_t			*dmp;
14829 	uint8_t			tag;
14830 
14831 	ASSERT(mp_chain != NULL);
14832 	ASSERT(ill != NULL);
14833 
14834 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14835 
14836 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14837 
14838 #define	rptr	((uchar_t *)ipha)
14839 
14840 	while (mp_chain != NULL) {
14841 		mp = mp_chain;
14842 		mp_chain = mp_chain->b_next;
14843 		mp->b_next = NULL;
14844 		ll_multicast = 0;
14845 
14846 		/*
14847 		 * We do ire caching from one iteration to
14848 		 * another. In the event the packet chain contains
14849 		 * all packets from the same dst, this caching saves
14850 		 * an ire_cache_lookup for each of the succeeding
14851 		 * packets in a packet chain.
14852 		 */
14853 		prev_dst = dst;
14854 
14855 		/*
14856 		 * if db_ref > 1 then copymsg and free original. Packet
14857 		 * may be changed and we do not want the other entity
14858 		 * who has a reference to this message to trip over the
14859 		 * changes. This is a blind change because trying to
14860 		 * catch all places that might change the packet is too
14861 		 * difficult.
14862 		 *
14863 		 * This corresponds to the fast path case, where we have
14864 		 * a chain of M_DATA mblks.  We check the db_ref count
14865 		 * of only the 1st data block in the mblk chain. There
14866 		 * doesn't seem to be a reason why a device driver would
14867 		 * send up data with varying db_ref counts in the mblk
14868 		 * chain. In any case the Fast path is a private
14869 		 * interface, and our drivers don't do such a thing.
14870 		 * Given the above assumption, there is no need to walk
14871 		 * down the entire mblk chain (which could have a
14872 		 * potential performance problem)
14873 		 *
14874 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14875 		 * to here because of exclusive ip stacks and vnics.
14876 		 * Packets transmitted from exclusive stack over vnic
14877 		 * can have db_ref > 1 and when it gets looped back to
14878 		 * another vnic in a different zone, you have ip_input()
14879 		 * getting dblks with db_ref > 1. So if someone
14880 		 * complains of TCP performance under this scenario,
14881 		 * take a serious look here on the impact of copymsg().
14882 		 */
14883 
14884 		if (DB_REF(mp) > 1) {
14885 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14886 				continue;
14887 		}
14888 
14889 		/*
14890 		 * Check and align the IP header.
14891 		 */
14892 		first_mp = mp;
14893 		if (DB_TYPE(mp) == M_DATA) {
14894 			dmp = mp;
14895 		} else if (DB_TYPE(mp) == M_PROTO &&
14896 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14897 			dmp = mp->b_cont;
14898 		} else {
14899 			dmp = NULL;
14900 		}
14901 		if (dmp != NULL) {
14902 			/*
14903 			 * IP header ptr not aligned?
14904 			 * OR IP header not complete in first mblk
14905 			 */
14906 			if (!OK_32PTR(dmp->b_rptr) ||
14907 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14908 				if (!ip_check_and_align_header(q, dmp, ipst))
14909 					continue;
14910 			}
14911 		}
14912 
14913 		/*
14914 		 * ip_input fast path
14915 		 */
14916 
14917 		/* mblk type is not M_DATA */
14918 		if (DB_TYPE(mp) != M_DATA) {
14919 			if (ip_rput_process_notdata(q, &first_mp, ill,
14920 			    &ll_multicast, &mp))
14921 				continue;
14922 
14923 			/*
14924 			 * The only way we can get here is if we had a
14925 			 * packet that was either a DL_UNITDATA_IND or
14926 			 * an M_CTL for an IPsec accelerated packet.
14927 			 *
14928 			 * In either case, the first_mp will point to
14929 			 * the leading M_PROTO or M_CTL.
14930 			 */
14931 			ASSERT(first_mp != NULL);
14932 		} else if (mhip != NULL) {
14933 			/*
14934 			 * ll_multicast is set here so that it is ready
14935 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14936 			 * manipulates ll_multicast in the same fashion when
14937 			 * called from ip_rput_process_notdata.
14938 			 */
14939 			switch (mhip->mhi_dsttype) {
14940 			case MAC_ADDRTYPE_MULTICAST :
14941 				ll_multicast = HPE_MULTICAST;
14942 				break;
14943 			case MAC_ADDRTYPE_BROADCAST :
14944 				ll_multicast = HPE_BROADCAST;
14945 				break;
14946 			default :
14947 				break;
14948 			}
14949 		}
14950 
14951 		/* Only M_DATA can come here and it is always aligned */
14952 		ASSERT(DB_TYPE(mp) == M_DATA);
14953 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14954 
14955 		ipha = (ipha_t *)mp->b_rptr;
14956 		len = mp->b_wptr - rptr;
14957 		pkt_len = ntohs(ipha->ipha_length);
14958 
14959 		/*
14960 		 * We must count all incoming packets, even if they end
14961 		 * up being dropped later on.
14962 		 */
14963 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14964 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14965 
14966 		/* multiple mblk or too short */
14967 		len -= pkt_len;
14968 		if (len != 0) {
14969 			/*
14970 			 * Make sure we have data length consistent
14971 			 * with the IP header.
14972 			 */
14973 			if (mp->b_cont == NULL) {
14974 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14975 					BUMP_MIB(ill->ill_ip_mib,
14976 					    ipIfStatsInHdrErrors);
14977 					ip2dbg(("ip_input: drop pkt\n"));
14978 					freemsg(mp);
14979 					continue;
14980 				}
14981 				mp->b_wptr = rptr + pkt_len;
14982 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14983 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14984 					BUMP_MIB(ill->ill_ip_mib,
14985 					    ipIfStatsInHdrErrors);
14986 					ip2dbg(("ip_input: drop pkt\n"));
14987 					freemsg(mp);
14988 					continue;
14989 				}
14990 				(void) adjmsg(mp, -len);
14991 				/*
14992 				 * adjmsg may have freed an mblk from the chain,
14993 				 * hence invalidate any hw checksum here. This
14994 				 * will force IP to calculate the checksum in
14995 				 * sw, but only for this packet.
14996 				 */
14997 				DB_CKSUMFLAGS(mp) = 0;
14998 				IP_STAT(ipst, ip_multimblk3);
14999 			}
15000 		}
15001 
15002 		/* Obtain the dst of the current packet */
15003 		dst = ipha->ipha_dst;
15004 
15005 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15006 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15007 		    ipha, ip6_t *, NULL, int, 0);
15008 
15009 		/*
15010 		 * The following test for loopback is faster than
15011 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15012 		 * operations.
15013 		 * Note that these addresses are always in network byte order
15014 		 */
15015 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15016 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15017 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15018 			freemsg(mp);
15019 			continue;
15020 		}
15021 
15022 		/*
15023 		 * The event for packets being received from a 'physical'
15024 		 * interface is placed after validation of the source and/or
15025 		 * destination address as being local so that packets can be
15026 		 * redirected to loopback addresses using ipnat.
15027 		 */
15028 		DTRACE_PROBE4(ip4__physical__in__start,
15029 		    ill_t *, ill, ill_t *, NULL,
15030 		    ipha_t *, ipha, mblk_t *, first_mp);
15031 
15032 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15033 		    ipst->ips_ipv4firewall_physical_in,
15034 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15035 
15036 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15037 
15038 		if (first_mp == NULL) {
15039 			continue;
15040 		}
15041 		dst = ipha->ipha_dst;
15042 		/*
15043 		 * Attach any necessary label information to
15044 		 * this packet
15045 		 */
15046 		if (is_system_labeled() &&
15047 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15048 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15049 			freemsg(mp);
15050 			continue;
15051 		}
15052 
15053 		if (ipst->ips_ip4_observe.he_interested) {
15054 			zoneid_t dzone;
15055 
15056 			/*
15057 			 * On the inbound path the src zone will be unknown as
15058 			 * this packet has come from the wire.
15059 			 */
15060 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15061 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15062 			    ill, ipst);
15063 		}
15064 
15065 		/*
15066 		 * Reuse the cached ire only if the ipha_dst of the previous
15067 		 * packet is the same as the current packet AND it is not
15068 		 * INADDR_ANY.
15069 		 */
15070 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15071 		    (ire != NULL)) {
15072 			ire_refrele(ire);
15073 			ire = NULL;
15074 		}
15075 
15076 		opt_len = ipha->ipha_version_and_hdr_length -
15077 		    IP_SIMPLE_HDR_VERSION;
15078 
15079 		/*
15080 		 * Check to see if we can take the fastpath.
15081 		 * That is possible if the following conditions are met
15082 		 *	o Tsol disabled
15083 		 *	o CGTP disabled
15084 		 *	o ipp_action_count is 0
15085 		 *	o no options in the packet
15086 		 *	o not a RSVP packet
15087 		 * 	o not a multicast packet
15088 		 *	o ill not in IP_DHCPINIT_IF mode
15089 		 */
15090 		if (!is_system_labeled() &&
15091 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15092 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15093 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15094 			if (ire == NULL)
15095 				ire = ire_cache_lookup_simple(dst, ipst);
15096 			/*
15097 			 * Unless forwarding is enabled, dont call
15098 			 * ip_fast_forward(). Incoming packet is for forwarding
15099 			 */
15100 			if ((ill->ill_flags & ILLF_ROUTER) &&
15101 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15102 				ire = ip_fast_forward(ire, dst, ill, mp);
15103 				continue;
15104 			}
15105 			/* incoming packet is for local consumption */
15106 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15107 				goto local;
15108 		}
15109 
15110 		/*
15111 		 * Disable ire caching for anything more complex
15112 		 * than the simple fast path case we checked for above.
15113 		 */
15114 		if (ire != NULL) {
15115 			ire_refrele(ire);
15116 			ire = NULL;
15117 		}
15118 
15119 		/*
15120 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15121 		 * server to unicast DHCP packets to a DHCP client using the
15122 		 * IP address it is offering to the client.  This can be
15123 		 * disabled through the "broadcast bit", but not all DHCP
15124 		 * servers honor that bit.  Therefore, to interoperate with as
15125 		 * many DHCP servers as possible, the DHCP client allows the
15126 		 * server to unicast, but we treat those packets as broadcast
15127 		 * here.  Note that we don't rewrite the packet itself since
15128 		 * (a) that would mess up the checksums and (b) the DHCP
15129 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15130 		 * hand it the packet regardless.
15131 		 */
15132 		if (ill->ill_dhcpinit != 0 &&
15133 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15134 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15135 			udpha_t *udpha;
15136 
15137 			/*
15138 			 * Reload ipha since pullupmsg() can change b_rptr.
15139 			 */
15140 			ipha = (ipha_t *)mp->b_rptr;
15141 			udpha = (udpha_t *)&ipha[1];
15142 
15143 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15144 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15145 				    mblk_t *, mp);
15146 				dst = INADDR_BROADCAST;
15147 			}
15148 		}
15149 
15150 		/* Full-blown slow path */
15151 		if (opt_len != 0) {
15152 			if (len != 0)
15153 				IP_STAT(ipst, ip_multimblk4);
15154 			else
15155 				IP_STAT(ipst, ip_ipoptions);
15156 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15157 			    &dst, ipst))
15158 				continue;
15159 		}
15160 
15161 		/*
15162 		 * Invoke the CGTP (multirouting) filtering module to process
15163 		 * the incoming packet. Packets identified as duplicates
15164 		 * must be discarded. Filtering is active only if the
15165 		 * the ip_cgtp_filter ndd variable is non-zero.
15166 		 */
15167 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15168 		if (ipst->ips_ip_cgtp_filter &&
15169 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15170 			netstackid_t stackid;
15171 
15172 			stackid = ipst->ips_netstack->netstack_stackid;
15173 			cgtp_flt_pkt =
15174 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15175 			    ill->ill_phyint->phyint_ifindex, mp);
15176 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15177 				freemsg(first_mp);
15178 				continue;
15179 			}
15180 		}
15181 
15182 		/*
15183 		 * If rsvpd is running, let RSVP daemon handle its processing
15184 		 * and forwarding of RSVP multicast/unicast packets.
15185 		 * If rsvpd is not running but mrouted is running, RSVP
15186 		 * multicast packets are forwarded as multicast traffic
15187 		 * and RSVP unicast packets are forwarded by unicast router.
15188 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15189 		 * packets are not forwarded, but the unicast packets are
15190 		 * forwarded like unicast traffic.
15191 		 */
15192 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15193 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15194 		    NULL) {
15195 			/* RSVP packet and rsvpd running. Treat as ours */
15196 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15197 			/*
15198 			 * This assumes that we deliver to all streams for
15199 			 * multicast and broadcast packets.
15200 			 * We have to force ll_multicast to 1 to handle the
15201 			 * M_DATA messages passed in from ip_mroute_decap.
15202 			 */
15203 			dst = INADDR_BROADCAST;
15204 			ll_multicast = 1;
15205 		} else if (CLASSD(dst)) {
15206 			/* packet is multicast */
15207 			mp->b_next = NULL;
15208 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15209 			    &ll_multicast, &dst))
15210 				continue;
15211 		}
15212 
15213 		if (ire == NULL) {
15214 			ire = ire_cache_lookup(dst, ALL_ZONES,
15215 			    msg_getlabel(mp), ipst);
15216 		}
15217 
15218 		if (ire != NULL && ire->ire_stq != NULL &&
15219 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15220 		    ire->ire_zoneid != ALL_ZONES) {
15221 			/*
15222 			 * Should only use IREs that are visible from the
15223 			 * global zone for forwarding.
15224 			 */
15225 			ire_refrele(ire);
15226 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15227 			    msg_getlabel(mp), ipst);
15228 		}
15229 
15230 		if (ire == NULL) {
15231 			/*
15232 			 * No IRE for this destination, so it can't be for us.
15233 			 * Unless we are forwarding, drop the packet.
15234 			 * We have to let source routed packets through
15235 			 * since we don't yet know if they are 'ping -l'
15236 			 * packets i.e. if they will go out over the
15237 			 * same interface as they came in on.
15238 			 */
15239 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15240 			if (ire == NULL)
15241 				continue;
15242 		}
15243 
15244 		/*
15245 		 * Broadcast IRE may indicate either broadcast or
15246 		 * multicast packet
15247 		 */
15248 		if (ire->ire_type == IRE_BROADCAST) {
15249 			/*
15250 			 * Skip broadcast checks if packet is UDP multicast;
15251 			 * we'd rather not enter ip_rput_process_broadcast()
15252 			 * unless the packet is broadcast for real, since
15253 			 * that routine is a no-op for multicast.
15254 			 */
15255 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15256 			    !CLASSD(ipha->ipha_dst)) {
15257 				ire = ip_rput_process_broadcast(&q, mp,
15258 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15259 				    ll_multicast);
15260 				if (ire == NULL)
15261 					continue;
15262 			}
15263 		} else if (ire->ire_stq != NULL) {
15264 			/* fowarding? */
15265 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15266 			    ll_multicast, B_FALSE);
15267 			/* ip_rput_process_forward consumed the packet */
15268 			continue;
15269 		}
15270 
15271 local:
15272 		/*
15273 		 * If the queue in the ire is different to the ingress queue
15274 		 * then we need to check to see if we can accept the packet.
15275 		 * Note that for multicast packets and broadcast packets sent
15276 		 * to a broadcast address which is shared between multiple
15277 		 * interfaces we should not do this since we just got a random
15278 		 * broadcast ire.
15279 		 */
15280 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15281 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15282 			if (ire == NULL) {
15283 				/* Drop packet */
15284 				BUMP_MIB(ill->ill_ip_mib,
15285 				    ipIfStatsForwProhibits);
15286 				freemsg(mp);
15287 				continue;
15288 			}
15289 			if (ire->ire_rfq != NULL)
15290 				q = ire->ire_rfq;
15291 		}
15292 
15293 		switch (ipha->ipha_protocol) {
15294 		case IPPROTO_TCP:
15295 			ASSERT(first_mp == mp);
15296 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15297 			    mp, 0, q, ip_ring)) != NULL) {
15298 				if (curr_sqp == NULL) {
15299 					curr_sqp = GET_SQUEUE(mp);
15300 					ASSERT(cnt == 0);
15301 					cnt++;
15302 					head = tail = mp;
15303 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15304 					ASSERT(tail != NULL);
15305 					cnt++;
15306 					tail->b_next = mp;
15307 					tail = mp;
15308 				} else {
15309 					/*
15310 					 * A different squeue. Send the
15311 					 * chain for the previous squeue on
15312 					 * its way. This shouldn't happen
15313 					 * often unless interrupt binding
15314 					 * changes.
15315 					 */
15316 					IP_STAT(ipst, ip_input_multi_squeue);
15317 					SQUEUE_ENTER(curr_sqp, head,
15318 					    tail, cnt, SQ_PROCESS, tag);
15319 					curr_sqp = GET_SQUEUE(mp);
15320 					head = mp;
15321 					tail = mp;
15322 					cnt = 1;
15323 				}
15324 			}
15325 			continue;
15326 		case IPPROTO_UDP:
15327 			ASSERT(first_mp == mp);
15328 			ip_udp_input(q, mp, ipha, ire, ill);
15329 			continue;
15330 		case IPPROTO_SCTP:
15331 			ASSERT(first_mp == mp);
15332 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15333 			    q, dst);
15334 			/* ire has been released by ip_sctp_input */
15335 			ire = NULL;
15336 			continue;
15337 		case IPPROTO_ENCAP:
15338 		case IPPROTO_IPV6:
15339 			ASSERT(first_mp == mp);
15340 			if (ip_iptun_input(NULL, mp, ipha, ill, ire, ipst))
15341 				break;
15342 			/*
15343 			 * If there was no IP tunnel data-link bound to
15344 			 * receive this packet, then we fall through to
15345 			 * allow potential raw sockets bound to either of
15346 			 * these protocols to pick it up.
15347 			 */
15348 		default:
15349 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15350 			continue;
15351 		}
15352 	}
15353 
15354 	if (ire != NULL)
15355 		ire_refrele(ire);
15356 
15357 	if (head != NULL)
15358 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15359 
15360 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15361 	    "ip_input_end: q %p (%S)", q, "end");
15362 #undef  rptr
15363 }
15364 
15365 /*
15366  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15367  * a chain of packets in the poll mode. The packets have gone through the
15368  * data link processing but not IP processing. For performance and latency
15369  * reasons, the squeue wants to process the chain in line instead of feeding
15370  * it back via ip_input path.
15371  *
15372  * So this is a light weight function which checks to see if the packets
15373  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15374  * but we still do the paranoid check) meant for local machine and we don't
15375  * have labels etc enabled. Packets that meet the criterion are returned to
15376  * the squeue and processed inline while the rest go via ip_input path.
15377  */
15378 /*ARGSUSED*/
15379 mblk_t *
15380 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15381     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15382 {
15383 	mblk_t 		*mp;
15384 	ipaddr_t	dst = NULL;
15385 	ipaddr_t	prev_dst;
15386 	ire_t		*ire = NULL;
15387 	ipha_t		*ipha;
15388 	uint_t		pkt_len;
15389 	ssize_t		len;
15390 	uint_t		opt_len;
15391 	queue_t		*q = ill->ill_rq;
15392 	squeue_t	*curr_sqp;
15393 	mblk_t 		*ahead = NULL;	/* Accepted head */
15394 	mblk_t		*atail = NULL;	/* Accepted tail */
15395 	uint_t		acnt = 0;	/* Accepted count */
15396 	mblk_t		*utail = NULL;	/* Unaccepted head */
15397 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15398 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15399 	ip_stack_t	*ipst = ill->ill_ipst;
15400 
15401 	*cnt = 0;
15402 
15403 	ASSERT(ill != NULL);
15404 	ASSERT(ip_ring != NULL);
15405 
15406 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15407 
15408 #define	rptr	((uchar_t *)ipha)
15409 
15410 	while (mp_chain != NULL) {
15411 		mp = mp_chain;
15412 		mp_chain = mp_chain->b_next;
15413 		mp->b_next = NULL;
15414 
15415 		/*
15416 		 * We do ire caching from one iteration to
15417 		 * another. In the event the packet chain contains
15418 		 * all packets from the same dst, this caching saves
15419 		 * an ire_cache_lookup for each of the succeeding
15420 		 * packets in a packet chain.
15421 		 */
15422 		prev_dst = dst;
15423 
15424 		ipha = (ipha_t *)mp->b_rptr;
15425 		len = mp->b_wptr - rptr;
15426 
15427 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15428 
15429 		/*
15430 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15431 		 * or doesn't have min len, reject.
15432 		 */
15433 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15434 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15435 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15436 			continue;
15437 		}
15438 
15439 		pkt_len = ntohs(ipha->ipha_length);
15440 		if (len != pkt_len) {
15441 			if (len > pkt_len) {
15442 				mp->b_wptr = rptr + pkt_len;
15443 			} else {
15444 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15445 				continue;
15446 			}
15447 		}
15448 
15449 		opt_len = ipha->ipha_version_and_hdr_length -
15450 		    IP_SIMPLE_HDR_VERSION;
15451 		dst = ipha->ipha_dst;
15452 
15453 		/* IP version bad or there are IP options */
15454 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15455 		    mp, &ipha, &dst, ipst)))
15456 			continue;
15457 
15458 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15459 		    (ipst->ips_ip_cgtp_filter &&
15460 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15461 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15462 			continue;
15463 		}
15464 
15465 		/*
15466 		 * Reuse the cached ire only if the ipha_dst of the previous
15467 		 * packet is the same as the current packet AND it is not
15468 		 * INADDR_ANY.
15469 		 */
15470 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15471 		    (ire != NULL)) {
15472 			ire_refrele(ire);
15473 			ire = NULL;
15474 		}
15475 
15476 		if (ire == NULL)
15477 			ire = ire_cache_lookup_simple(dst, ipst);
15478 
15479 		/*
15480 		 * Unless forwarding is enabled, dont call
15481 		 * ip_fast_forward(). Incoming packet is for forwarding
15482 		 */
15483 		if ((ill->ill_flags & ILLF_ROUTER) &&
15484 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15485 
15486 			DTRACE_PROBE4(ip4__physical__in__start,
15487 			    ill_t *, ill, ill_t *, NULL,
15488 			    ipha_t *, ipha, mblk_t *, mp);
15489 
15490 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15491 			    ipst->ips_ipv4firewall_physical_in,
15492 			    ill, NULL, ipha, mp, mp, 0, ipst);
15493 
15494 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15495 
15496 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15497 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15498 			    pkt_len);
15499 
15500 			if (mp != NULL)
15501 				ire = ip_fast_forward(ire, dst, ill, mp);
15502 			continue;
15503 		}
15504 
15505 		/* incoming packet is for local consumption */
15506 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15507 			goto local_accept;
15508 
15509 		/*
15510 		 * Disable ire caching for anything more complex
15511 		 * than the simple fast path case we checked for above.
15512 		 */
15513 		if (ire != NULL) {
15514 			ire_refrele(ire);
15515 			ire = NULL;
15516 		}
15517 
15518 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15519 		    ipst);
15520 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15521 		    ire->ire_stq != NULL) {
15522 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15523 			if (ire != NULL) {
15524 				ire_refrele(ire);
15525 				ire = NULL;
15526 			}
15527 			continue;
15528 		}
15529 
15530 local_accept:
15531 
15532 		if (ire->ire_rfq != q) {
15533 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15534 			if (ire != NULL) {
15535 				ire_refrele(ire);
15536 				ire = NULL;
15537 			}
15538 			continue;
15539 		}
15540 
15541 		/*
15542 		 * The event for packets being received from a 'physical'
15543 		 * interface is placed after validation of the source and/or
15544 		 * destination address as being local so that packets can be
15545 		 * redirected to loopback addresses using ipnat.
15546 		 */
15547 		DTRACE_PROBE4(ip4__physical__in__start,
15548 		    ill_t *, ill, ill_t *, NULL,
15549 		    ipha_t *, ipha, mblk_t *, mp);
15550 
15551 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15552 		    ipst->ips_ipv4firewall_physical_in,
15553 		    ill, NULL, ipha, mp, mp, 0, ipst);
15554 
15555 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15556 
15557 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15558 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15559 
15560 		if (mp != NULL &&
15561 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15562 		    0, q, ip_ring)) != NULL) {
15563 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15564 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15565 			} else {
15566 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15567 				    SQ_FILL, SQTAG_IP_INPUT);
15568 			}
15569 		}
15570 	}
15571 
15572 	if (ire != NULL)
15573 		ire_refrele(ire);
15574 
15575 	if (uhead != NULL)
15576 		ip_input(ill, ip_ring, uhead, NULL);
15577 
15578 	if (ahead != NULL) {
15579 		*last = atail;
15580 		*cnt = acnt;
15581 		return (ahead);
15582 	}
15583 
15584 	return (NULL);
15585 #undef  rptr
15586 }
15587 
15588 static void
15589 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15590     t_uscalar_t err)
15591 {
15592 	if (dl_err == DL_SYSERR) {
15593 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15594 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15595 		    ill->ill_name, dl_primstr(prim), err);
15596 		return;
15597 	}
15598 
15599 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15600 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15601 	    dl_errstr(dl_err));
15602 }
15603 
15604 /*
15605  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15606  * than DL_UNITDATA_IND messages. If we need to process this message
15607  * exclusively, we call qwriter_ip, in which case we also need to call
15608  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15609  */
15610 void
15611 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15612 {
15613 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15614 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15615 	ill_t		*ill = q->q_ptr;
15616 	t_uscalar_t	prim = dloa->dl_primitive;
15617 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15618 
15619 	ip1dbg(("ip_rput_dlpi"));
15620 
15621 	/*
15622 	 * If we received an ACK but didn't send a request for it, then it
15623 	 * can't be part of any pending operation; discard up-front.
15624 	 */
15625 	switch (prim) {
15626 	case DL_ERROR_ACK:
15627 		reqprim = dlea->dl_error_primitive;
15628 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15629 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15630 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15631 		    dlea->dl_unix_errno));
15632 		break;
15633 	case DL_OK_ACK:
15634 		reqprim = dloa->dl_correct_primitive;
15635 		break;
15636 	case DL_INFO_ACK:
15637 		reqprim = DL_INFO_REQ;
15638 		break;
15639 	case DL_BIND_ACK:
15640 		reqprim = DL_BIND_REQ;
15641 		break;
15642 	case DL_PHYS_ADDR_ACK:
15643 		reqprim = DL_PHYS_ADDR_REQ;
15644 		break;
15645 	case DL_NOTIFY_ACK:
15646 		reqprim = DL_NOTIFY_REQ;
15647 		break;
15648 	case DL_CONTROL_ACK:
15649 		reqprim = DL_CONTROL_REQ;
15650 		break;
15651 	case DL_CAPABILITY_ACK:
15652 		reqprim = DL_CAPABILITY_REQ;
15653 		break;
15654 	}
15655 
15656 	if (prim != DL_NOTIFY_IND) {
15657 		if (reqprim == DL_PRIM_INVAL ||
15658 		    !ill_dlpi_pending(ill, reqprim)) {
15659 			/* Not a DLPI message we support or expected */
15660 			freemsg(mp);
15661 			return;
15662 		}
15663 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15664 		    dl_primstr(reqprim)));
15665 	}
15666 
15667 	switch (reqprim) {
15668 	case DL_UNBIND_REQ:
15669 		/*
15670 		 * NOTE: we mark the unbind as complete even if we got a
15671 		 * DL_ERROR_ACK, since there's not much else we can do.
15672 		 */
15673 		mutex_enter(&ill->ill_lock);
15674 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15675 		cv_signal(&ill->ill_cv);
15676 		mutex_exit(&ill->ill_lock);
15677 		break;
15678 
15679 	case DL_ENABMULTI_REQ:
15680 		if (prim == DL_OK_ACK) {
15681 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15682 				ill->ill_dlpi_multicast_state = IDS_OK;
15683 		}
15684 		break;
15685 	}
15686 
15687 	/*
15688 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15689 	 * need to become writer to continue to process it.  Because an
15690 	 * exclusive operation doesn't complete until replies to all queued
15691 	 * DLPI messages have been received, we know we're in the middle of an
15692 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15693 	 *
15694 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15695 	 * Since this is on the ill stream we unconditionally bump up the
15696 	 * refcount without doing ILL_CAN_LOOKUP().
15697 	 */
15698 	ill_refhold(ill);
15699 	if (prim == DL_NOTIFY_IND)
15700 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15701 	else
15702 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15703 }
15704 
15705 /*
15706  * Handling of DLPI messages that require exclusive access to the ipsq.
15707  *
15708  * Need to do ill_pending_mp_release on ioctl completion, which could
15709  * happen here. (along with mi_copy_done)
15710  */
15711 /* ARGSUSED */
15712 static void
15713 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15714 {
15715 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15716 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15717 	int		err = 0;
15718 	ill_t		*ill;
15719 	ipif_t		*ipif = NULL;
15720 	mblk_t		*mp1 = NULL;
15721 	conn_t		*connp = NULL;
15722 	t_uscalar_t	paddrreq;
15723 	mblk_t		*mp_hw;
15724 	boolean_t	success;
15725 	boolean_t	ioctl_aborted = B_FALSE;
15726 	boolean_t	log = B_TRUE;
15727 	ip_stack_t		*ipst;
15728 
15729 	ip1dbg(("ip_rput_dlpi_writer .."));
15730 	ill = (ill_t *)q->q_ptr;
15731 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15732 	ASSERT(IAM_WRITER_ILL(ill));
15733 
15734 	ipst = ill->ill_ipst;
15735 
15736 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15737 	/*
15738 	 * The current ioctl could have been aborted by the user and a new
15739 	 * ioctl to bring up another ill could have started. We could still
15740 	 * get a response from the driver later.
15741 	 */
15742 	if (ipif != NULL && ipif->ipif_ill != ill)
15743 		ioctl_aborted = B_TRUE;
15744 
15745 	switch (dloa->dl_primitive) {
15746 	case DL_ERROR_ACK:
15747 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15748 		    dl_primstr(dlea->dl_error_primitive)));
15749 
15750 		switch (dlea->dl_error_primitive) {
15751 		case DL_DISABMULTI_REQ:
15752 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15753 			break;
15754 		case DL_PROMISCON_REQ:
15755 		case DL_PROMISCOFF_REQ:
15756 		case DL_UNBIND_REQ:
15757 		case DL_ATTACH_REQ:
15758 		case DL_INFO_REQ:
15759 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15760 			break;
15761 		case DL_NOTIFY_REQ:
15762 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15763 			log = B_FALSE;
15764 			break;
15765 		case DL_PHYS_ADDR_REQ:
15766 			/*
15767 			 * For IPv6 only, there are two additional
15768 			 * phys_addr_req's sent to the driver to get the
15769 			 * IPv6 token and lla. This allows IP to acquire
15770 			 * the hardware address format for a given interface
15771 			 * without having built in knowledge of the hardware
15772 			 * address. ill_phys_addr_pend keeps track of the last
15773 			 * DL_PAR sent so we know which response we are
15774 			 * dealing with. ill_dlpi_done will update
15775 			 * ill_phys_addr_pend when it sends the next req.
15776 			 * We don't complete the IOCTL until all three DL_PARs
15777 			 * have been attempted, so set *_len to 0 and break.
15778 			 */
15779 			paddrreq = ill->ill_phys_addr_pend;
15780 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15781 			if (paddrreq == DL_IPV6_TOKEN) {
15782 				ill->ill_token_length = 0;
15783 				log = B_FALSE;
15784 				break;
15785 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15786 				ill->ill_nd_lla_len = 0;
15787 				log = B_FALSE;
15788 				break;
15789 			}
15790 			/*
15791 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15792 			 * We presumably have an IOCTL hanging out waiting
15793 			 * for completion. Find it and complete the IOCTL
15794 			 * with the error noted.
15795 			 * However, ill_dl_phys was called on an ill queue
15796 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15797 			 * set. But the ioctl is known to be pending on ill_wq.
15798 			 */
15799 			if (!ill->ill_ifname_pending)
15800 				break;
15801 			ill->ill_ifname_pending = 0;
15802 			if (!ioctl_aborted)
15803 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15804 			if (mp1 != NULL) {
15805 				/*
15806 				 * This operation (SIOCSLIFNAME) must have
15807 				 * happened on the ill. Assert there is no conn
15808 				 */
15809 				ASSERT(connp == NULL);
15810 				q = ill->ill_wq;
15811 			}
15812 			break;
15813 		case DL_BIND_REQ:
15814 			ill_dlpi_done(ill, DL_BIND_REQ);
15815 			if (ill->ill_ifname_pending)
15816 				break;
15817 			/*
15818 			 * Something went wrong with the bind.  We presumably
15819 			 * have an IOCTL hanging out waiting for completion.
15820 			 * Find it, take down the interface that was coming
15821 			 * up, and complete the IOCTL with the error noted.
15822 			 */
15823 			if (!ioctl_aborted)
15824 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15825 			if (mp1 != NULL) {
15826 				/*
15827 				 * This might be a result of a DL_NOTE_REPLUMB
15828 				 * notification. In that case, connp is NULL.
15829 				 */
15830 				if (connp != NULL)
15831 					q = CONNP_TO_WQ(connp);
15832 
15833 				(void) ipif_down(ipif, NULL, NULL);
15834 				/* error is set below the switch */
15835 			}
15836 			break;
15837 		case DL_ENABMULTI_REQ:
15838 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15839 
15840 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15841 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15842 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15843 				ipif_t *ipif;
15844 
15845 				printf("ip: joining multicasts failed (%d)"
15846 				    " on %s - will use link layer "
15847 				    "broadcasts for multicast\n",
15848 				    dlea->dl_errno, ill->ill_name);
15849 
15850 				/*
15851 				 * Set up the multicast mapping alone.
15852 				 * writer, so ok to access ill->ill_ipif
15853 				 * without any lock.
15854 				 */
15855 				ipif = ill->ill_ipif;
15856 				mutex_enter(&ill->ill_phyint->phyint_lock);
15857 				ill->ill_phyint->phyint_flags |=
15858 				    PHYI_MULTI_BCAST;
15859 				mutex_exit(&ill->ill_phyint->phyint_lock);
15860 
15861 				if (!ill->ill_isv6) {
15862 					(void) ipif_arp_setup_multicast(ipif,
15863 					    NULL);
15864 				} else {
15865 					(void) ipif_ndp_setup_multicast(ipif,
15866 					    NULL);
15867 				}
15868 			}
15869 			freemsg(mp);	/* Don't want to pass this up */
15870 			return;
15871 		case DL_CONTROL_REQ:
15872 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15873 			    "DL_CONTROL_REQ\n"));
15874 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15875 			freemsg(mp);
15876 			return;
15877 		case DL_CAPABILITY_REQ:
15878 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15879 			    "DL_CAPABILITY REQ\n"));
15880 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15881 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15882 			ill_capability_done(ill);
15883 			freemsg(mp);
15884 			return;
15885 		}
15886 		/*
15887 		 * Note the error for IOCTL completion (mp1 is set when
15888 		 * ready to complete ioctl). If ill_ifname_pending_err is
15889 		 * set, an error occured during plumbing (ill_ifname_pending),
15890 		 * so we want to report that error.
15891 		 *
15892 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15893 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15894 		 * expected to get errack'd if the driver doesn't support
15895 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15896 		 * if these error conditions are encountered.
15897 		 */
15898 		if (mp1 != NULL) {
15899 			if (ill->ill_ifname_pending_err != 0)  {
15900 				err = ill->ill_ifname_pending_err;
15901 				ill->ill_ifname_pending_err = 0;
15902 			} else {
15903 				err = dlea->dl_unix_errno ?
15904 				    dlea->dl_unix_errno : ENXIO;
15905 			}
15906 		/*
15907 		 * If we're plumbing an interface and an error hasn't already
15908 		 * been saved, set ill_ifname_pending_err to the error passed
15909 		 * up. Ignore the error if log is B_FALSE (see comment above).
15910 		 */
15911 		} else if (log && ill->ill_ifname_pending &&
15912 		    ill->ill_ifname_pending_err == 0) {
15913 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15914 			    dlea->dl_unix_errno : ENXIO;
15915 		}
15916 
15917 		if (log)
15918 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15919 			    dlea->dl_errno, dlea->dl_unix_errno);
15920 		break;
15921 	case DL_CAPABILITY_ACK:
15922 		ill_capability_ack(ill, mp);
15923 		/*
15924 		 * The message has been handed off to ill_capability_ack
15925 		 * and must not be freed below
15926 		 */
15927 		mp = NULL;
15928 		break;
15929 
15930 	case DL_CONTROL_ACK:
15931 		/* We treat all of these as "fire and forget" */
15932 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15933 		break;
15934 	case DL_INFO_ACK:
15935 		/* Call a routine to handle this one. */
15936 		ill_dlpi_done(ill, DL_INFO_REQ);
15937 		ip_ll_subnet_defaults(ill, mp);
15938 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15939 		return;
15940 	case DL_BIND_ACK:
15941 		/*
15942 		 * We should have an IOCTL waiting on this unless
15943 		 * sent by ill_dl_phys, in which case just return
15944 		 */
15945 		ill_dlpi_done(ill, DL_BIND_REQ);
15946 		if (ill->ill_ifname_pending)
15947 			break;
15948 
15949 		if (!ioctl_aborted)
15950 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15951 		if (mp1 == NULL)
15952 			break;
15953 		/*
15954 		 * mp1 was added by ill_dl_up(). if that is a result of
15955 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
15956 		 */
15957 		if (connp != NULL)
15958 			q = CONNP_TO_WQ(connp);
15959 
15960 		/*
15961 		 * We are exclusive. So nothing can change even after
15962 		 * we get the pending mp. If need be we can put it back
15963 		 * and restart, as in calling ipif_arp_up()  below.
15964 		 */
15965 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15966 
15967 		mutex_enter(&ill->ill_lock);
15968 		ill->ill_dl_up = 1;
15969 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15970 		mutex_exit(&ill->ill_lock);
15971 
15972 		/*
15973 		 * Now bring up the resolver; when that is complete, we'll
15974 		 * create IREs.  Note that we intentionally mirror what
15975 		 * ipif_up() would have done, because we got here by way of
15976 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15977 		 */
15978 		if (ill->ill_isv6) {
15979 			if (ill->ill_flags & ILLF_XRESOLV) {
15980 				if (connp != NULL)
15981 					mutex_enter(&connp->conn_lock);
15982 				mutex_enter(&ill->ill_lock);
15983 				success = ipsq_pending_mp_add(connp, ipif, q,
15984 				    mp1, 0);
15985 				mutex_exit(&ill->ill_lock);
15986 				if (connp != NULL)
15987 					mutex_exit(&connp->conn_lock);
15988 				if (success) {
15989 					err = ipif_resolver_up(ipif,
15990 					    Res_act_initial);
15991 					if (err == EINPROGRESS) {
15992 						freemsg(mp);
15993 						return;
15994 					}
15995 					ASSERT(err != 0);
15996 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
15997 					ASSERT(mp1 != NULL);
15998 				} else {
15999 					/* conn has started closing */
16000 					err = EINTR;
16001 				}
16002 			} else { /* Non XRESOLV interface */
16003 				(void) ipif_resolver_up(ipif, Res_act_initial);
16004 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16005 					err = ipif_up_done_v6(ipif);
16006 			}
16007 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16008 			/*
16009 			 * ARP and other v4 external resolvers.
16010 			 * Leave the pending mblk intact so that
16011 			 * the ioctl completes in ip_rput().
16012 			 */
16013 			if (connp != NULL)
16014 				mutex_enter(&connp->conn_lock);
16015 			mutex_enter(&ill->ill_lock);
16016 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16017 			mutex_exit(&ill->ill_lock);
16018 			if (connp != NULL)
16019 				mutex_exit(&connp->conn_lock);
16020 			if (success) {
16021 				err = ipif_resolver_up(ipif, Res_act_initial);
16022 				if (err == EINPROGRESS) {
16023 					freemsg(mp);
16024 					return;
16025 				}
16026 				ASSERT(err != 0);
16027 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16028 			} else {
16029 				/* The conn has started closing */
16030 				err = EINTR;
16031 			}
16032 		} else {
16033 			/*
16034 			 * This one is complete. Reply to pending ioctl.
16035 			 */
16036 			(void) ipif_resolver_up(ipif, Res_act_initial);
16037 			err = ipif_up_done(ipif);
16038 		}
16039 
16040 		if ((err == 0) && (ill->ill_up_ipifs)) {
16041 			err = ill_up_ipifs(ill, q, mp1);
16042 			if (err == EINPROGRESS) {
16043 				freemsg(mp);
16044 				return;
16045 			}
16046 		}
16047 
16048 		/*
16049 		 * If we have a moved ipif to bring up, and everything has
16050 		 * succeeded to this point, bring it up on the IPMP ill.
16051 		 * Otherwise, leave it down -- the admin can try to bring it
16052 		 * up by hand if need be.
16053 		 */
16054 		if (ill->ill_move_ipif != NULL) {
16055 			if (err != 0) {
16056 				ill->ill_move_ipif = NULL;
16057 			} else {
16058 				ipif = ill->ill_move_ipif;
16059 				ill->ill_move_ipif = NULL;
16060 				err = ipif_up(ipif, q, mp1);
16061 				if (err == EINPROGRESS) {
16062 					freemsg(mp);
16063 					return;
16064 				}
16065 			}
16066 		}
16067 		break;
16068 
16069 	case DL_NOTIFY_IND: {
16070 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16071 		ire_t *ire;
16072 		uint_t orig_mtu;
16073 		boolean_t need_ire_walk_v4 = B_FALSE;
16074 		boolean_t need_ire_walk_v6 = B_FALSE;
16075 
16076 		switch (notify->dl_notification) {
16077 		case DL_NOTE_PHYS_ADDR:
16078 			err = ill_set_phys_addr(ill, mp);
16079 			break;
16080 
16081 		case DL_NOTE_REPLUMB:
16082 			/*
16083 			 * Directly return after calling ill_replumb().
16084 			 * Note that we should not free mp as it is reused
16085 			 * in the ill_replumb() function.
16086 			 */
16087 			err = ill_replumb(ill, mp);
16088 			return;
16089 
16090 		case DL_NOTE_FASTPATH_FLUSH:
16091 			ill_fastpath_flush(ill);
16092 			break;
16093 
16094 		case DL_NOTE_SDU_SIZE:
16095 			/*
16096 			 * Change the MTU size of the interface, of all
16097 			 * attached ipif's, and of all relevant ire's.  The
16098 			 * new value's a uint32_t at notify->dl_data.
16099 			 * Mtu change Vs. new ire creation - protocol below.
16100 			 *
16101 			 * a Mark the ipif as IPIF_CHANGING.
16102 			 * b Set the new mtu in the ipif.
16103 			 * c Change the ire_max_frag on all affected ires
16104 			 * d Unmark the IPIF_CHANGING
16105 			 *
16106 			 * To see how the protocol works, assume an interface
16107 			 * route is also being added simultaneously by
16108 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16109 			 * the ire. If the ire is created before step a,
16110 			 * it will be cleaned up by step c. If the ire is
16111 			 * created after step d, it will see the new value of
16112 			 * ipif_mtu. Any attempt to create the ire between
16113 			 * steps a to d will fail because of the IPIF_CHANGING
16114 			 * flag. Note that ire_create() is passed a pointer to
16115 			 * the ipif_mtu, and not the value. During ire_add
16116 			 * under the bucket lock, the ire_max_frag of the
16117 			 * new ire being created is set from the ipif/ire from
16118 			 * which it is being derived.
16119 			 */
16120 			mutex_enter(&ill->ill_lock);
16121 
16122 			orig_mtu = ill->ill_max_mtu;
16123 			ill->ill_max_frag = (uint_t)notify->dl_data;
16124 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16125 
16126 			/*
16127 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16128 			 * clamp ill_max_mtu at it.
16129 			 */
16130 			if (ill->ill_user_mtu != 0 &&
16131 			    ill->ill_user_mtu < ill->ill_max_mtu)
16132 				ill->ill_max_mtu = ill->ill_user_mtu;
16133 
16134 			/*
16135 			 * If the MTU is unchanged, we're done.
16136 			 */
16137 			if (orig_mtu == ill->ill_max_mtu) {
16138 				mutex_exit(&ill->ill_lock);
16139 				break;
16140 			}
16141 
16142 			if (ill->ill_isv6) {
16143 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16144 					ill->ill_max_mtu = IPV6_MIN_MTU;
16145 			} else {
16146 				if (ill->ill_max_mtu < IP_MIN_MTU)
16147 					ill->ill_max_mtu = IP_MIN_MTU;
16148 			}
16149 			for (ipif = ill->ill_ipif; ipif != NULL;
16150 			    ipif = ipif->ipif_next) {
16151 				/*
16152 				 * Don't override the mtu if the user
16153 				 * has explicitly set it.
16154 				 */
16155 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16156 					continue;
16157 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16158 				if (ipif->ipif_isv6)
16159 					ire = ipif_to_ire_v6(ipif);
16160 				else
16161 					ire = ipif_to_ire(ipif);
16162 				if (ire != NULL) {
16163 					ire->ire_max_frag = ipif->ipif_mtu;
16164 					ire_refrele(ire);
16165 				}
16166 				if (ipif->ipif_flags & IPIF_UP) {
16167 					if (ill->ill_isv6)
16168 						need_ire_walk_v6 = B_TRUE;
16169 					else
16170 						need_ire_walk_v4 = B_TRUE;
16171 				}
16172 			}
16173 			mutex_exit(&ill->ill_lock);
16174 			if (need_ire_walk_v4)
16175 				ire_walk_v4(ill_mtu_change, (char *)ill,
16176 				    ALL_ZONES, ipst);
16177 			if (need_ire_walk_v6)
16178 				ire_walk_v6(ill_mtu_change, (char *)ill,
16179 				    ALL_ZONES, ipst);
16180 
16181 			/*
16182 			 * Refresh IPMP meta-interface MTU if necessary.
16183 			 */
16184 			if (IS_UNDER_IPMP(ill))
16185 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16186 			break;
16187 
16188 		case DL_NOTE_LINK_UP:
16189 		case DL_NOTE_LINK_DOWN: {
16190 			/*
16191 			 * We are writer. ill / phyint / ipsq assocs stable.
16192 			 * The RUNNING flag reflects the state of the link.
16193 			 */
16194 			phyint_t *phyint = ill->ill_phyint;
16195 			uint64_t new_phyint_flags;
16196 			boolean_t changed = B_FALSE;
16197 			boolean_t went_up;
16198 
16199 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16200 			mutex_enter(&phyint->phyint_lock);
16201 
16202 			new_phyint_flags = went_up ?
16203 			    phyint->phyint_flags | PHYI_RUNNING :
16204 			    phyint->phyint_flags & ~PHYI_RUNNING;
16205 
16206 			if (IS_IPMP(ill)) {
16207 				new_phyint_flags = went_up ?
16208 				    new_phyint_flags & ~PHYI_FAILED :
16209 				    new_phyint_flags | PHYI_FAILED;
16210 			}
16211 
16212 			if (new_phyint_flags != phyint->phyint_flags) {
16213 				phyint->phyint_flags = new_phyint_flags;
16214 				changed = B_TRUE;
16215 			}
16216 			mutex_exit(&phyint->phyint_lock);
16217 			/*
16218 			 * ill_restart_dad handles the DAD restart and routing
16219 			 * socket notification logic.
16220 			 */
16221 			if (changed) {
16222 				ill_restart_dad(phyint->phyint_illv4, went_up);
16223 				ill_restart_dad(phyint->phyint_illv6, went_up);
16224 			}
16225 			break;
16226 		}
16227 		case DL_NOTE_PROMISC_ON_PHYS: {
16228 			phyint_t *phyint = ill->ill_phyint;
16229 
16230 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16231 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16232 			mutex_enter(&phyint->phyint_lock);
16233 			phyint->phyint_flags |= PHYI_PROMISC;
16234 			mutex_exit(&phyint->phyint_lock);
16235 			break;
16236 		}
16237 		case DL_NOTE_PROMISC_OFF_PHYS: {
16238 			phyint_t *phyint = ill->ill_phyint;
16239 
16240 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16241 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16242 			mutex_enter(&phyint->phyint_lock);
16243 			phyint->phyint_flags &= ~PHYI_PROMISC;
16244 			mutex_exit(&phyint->phyint_lock);
16245 			break;
16246 		}
16247 		case DL_NOTE_CAPAB_RENEG:
16248 			/*
16249 			 * Something changed on the driver side.
16250 			 * It wants us to renegotiate the capabilities
16251 			 * on this ill. One possible cause is the aggregation
16252 			 * interface under us where a port got added or
16253 			 * went away.
16254 			 *
16255 			 * If the capability negotiation is already done
16256 			 * or is in progress, reset the capabilities and
16257 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16258 			 * so that when the ack comes back, we can start
16259 			 * the renegotiation process.
16260 			 *
16261 			 * Note that if ill_capab_reneg is already B_TRUE
16262 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16263 			 * the capability resetting request has been sent
16264 			 * and the renegotiation has not been started yet;
16265 			 * nothing needs to be done in this case.
16266 			 */
16267 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16268 			ill_capability_reset(ill, B_TRUE);
16269 			ipsq_current_finish(ipsq);
16270 			break;
16271 		default:
16272 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16273 			    "type 0x%x for DL_NOTIFY_IND\n",
16274 			    notify->dl_notification));
16275 			break;
16276 		}
16277 
16278 		/*
16279 		 * As this is an asynchronous operation, we
16280 		 * should not call ill_dlpi_done
16281 		 */
16282 		break;
16283 	}
16284 	case DL_NOTIFY_ACK: {
16285 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16286 
16287 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16288 			ill->ill_note_link = 1;
16289 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16290 		break;
16291 	}
16292 	case DL_PHYS_ADDR_ACK: {
16293 		/*
16294 		 * As part of plumbing the interface via SIOCSLIFNAME,
16295 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16296 		 * whose answers we receive here.  As each answer is received,
16297 		 * we call ill_dlpi_done() to dispatch the next request as
16298 		 * we're processing the current one.  Once all answers have
16299 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16300 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16301 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16302 		 * available, but we know the ioctl is pending on ill_wq.)
16303 		 */
16304 		uint_t	paddrlen, paddroff;
16305 		uint8_t	*addr;
16306 
16307 		paddrreq = ill->ill_phys_addr_pend;
16308 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16309 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16310 		addr = mp->b_rptr + paddroff;
16311 
16312 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16313 		if (paddrreq == DL_IPV6_TOKEN) {
16314 			/*
16315 			 * bcopy to low-order bits of ill_token
16316 			 *
16317 			 * XXX Temporary hack - currently, all known tokens
16318 			 * are 64 bits, so I'll cheat for the moment.
16319 			 */
16320 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
16321 			ill->ill_token_length = paddrlen;
16322 			break;
16323 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16324 			ASSERT(ill->ill_nd_lla_mp == NULL);
16325 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16326 			mp = NULL;
16327 			break;
16328 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
16329 			ASSERT(ill->ill_dest_addr_mp == NULL);
16330 			ill->ill_dest_addr_mp = mp;
16331 			ill->ill_dest_addr = addr;
16332 			mp = NULL;
16333 			if (ill->ill_isv6) {
16334 				ill_setdesttoken(ill);
16335 				ipif_setdestlinklocal(ill->ill_ipif);
16336 			}
16337 			break;
16338 		}
16339 
16340 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16341 		ASSERT(ill->ill_phys_addr_mp == NULL);
16342 		if (!ill->ill_ifname_pending)
16343 			break;
16344 		ill->ill_ifname_pending = 0;
16345 		if (!ioctl_aborted)
16346 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16347 		if (mp1 != NULL) {
16348 			ASSERT(connp == NULL);
16349 			q = ill->ill_wq;
16350 		}
16351 		/*
16352 		 * If any error acks received during the plumbing sequence,
16353 		 * ill_ifname_pending_err will be set. Break out and send up
16354 		 * the error to the pending ioctl.
16355 		 */
16356 		if (ill->ill_ifname_pending_err != 0) {
16357 			err = ill->ill_ifname_pending_err;
16358 			ill->ill_ifname_pending_err = 0;
16359 			break;
16360 		}
16361 
16362 		ill->ill_phys_addr_mp = mp;
16363 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
16364 		mp = NULL;
16365 
16366 		/*
16367 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
16368 		 * provider doesn't support physical addresses.  We check both
16369 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
16370 		 * not have physical addresses, but historically adversises a
16371 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
16372 		 * its DL_PHYS_ADDR_ACK.
16373 		 */
16374 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
16375 			ill->ill_phys_addr = NULL;
16376 		} else if (paddrlen != ill->ill_phys_addr_length) {
16377 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16378 			    paddrlen, ill->ill_phys_addr_length));
16379 			err = EINVAL;
16380 			break;
16381 		}
16382 
16383 		if (ill->ill_nd_lla_mp == NULL) {
16384 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16385 				err = ENOMEM;
16386 				break;
16387 			}
16388 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16389 		}
16390 
16391 		if (ill->ill_isv6) {
16392 			ill_setdefaulttoken(ill);
16393 			ipif_setlinklocal(ill->ill_ipif);
16394 		}
16395 		break;
16396 	}
16397 	case DL_OK_ACK:
16398 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16399 		    dl_primstr((int)dloa->dl_correct_primitive),
16400 		    dloa->dl_correct_primitive));
16401 		switch (dloa->dl_correct_primitive) {
16402 		case DL_ENABMULTI_REQ:
16403 		case DL_DISABMULTI_REQ:
16404 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16405 			break;
16406 		case DL_PROMISCON_REQ:
16407 		case DL_PROMISCOFF_REQ:
16408 		case DL_UNBIND_REQ:
16409 		case DL_ATTACH_REQ:
16410 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16411 			break;
16412 		}
16413 		break;
16414 	default:
16415 		break;
16416 	}
16417 
16418 	freemsg(mp);
16419 	if (mp1 == NULL)
16420 		return;
16421 
16422 	/*
16423 	 * The operation must complete without EINPROGRESS since
16424 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16425 	 * the operation will be stuck forever inside the IPSQ.
16426 	 */
16427 	ASSERT(err != EINPROGRESS);
16428 
16429 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16430 	case 0:
16431 		ipsq_current_finish(ipsq);
16432 		break;
16433 
16434 	case SIOCSLIFNAME:
16435 	case IF_UNITSEL: {
16436 		ill_t *ill_other = ILL_OTHER(ill);
16437 
16438 		/*
16439 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16440 		 * ill has a peer which is in an IPMP group, then place ill
16441 		 * into the same group.  One catch: although ifconfig plumbs
16442 		 * the appropriate IPMP meta-interface prior to plumbing this
16443 		 * ill, it is possible for multiple ifconfig applications to
16444 		 * race (or for another application to adjust plumbing), in
16445 		 * which case the IPMP meta-interface we need will be missing.
16446 		 * If so, kick the phyint out of the group.
16447 		 */
16448 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16449 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16450 			ipmp_illgrp_t	*illg;
16451 
16452 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16453 			if (illg == NULL)
16454 				ipmp_phyint_leave_grp(ill->ill_phyint);
16455 			else
16456 				ipmp_ill_join_illgrp(ill, illg);
16457 		}
16458 
16459 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16460 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16461 		else
16462 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16463 		break;
16464 	}
16465 	case SIOCLIFADDIF:
16466 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16467 		break;
16468 
16469 	default:
16470 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16471 		break;
16472 	}
16473 }
16474 
16475 /*
16476  * ip_rput_other is called by ip_rput to handle messages modifying the global
16477  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
16478  */
16479 /* ARGSUSED */
16480 void
16481 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16482 {
16483 	ill_t		*ill = q->q_ptr;
16484 	struct iocblk	*iocp;
16485 
16486 	ip1dbg(("ip_rput_other "));
16487 	if (ipsq != NULL) {
16488 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16489 		ASSERT(ipsq->ipsq_xop ==
16490 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16491 	}
16492 
16493 	switch (mp->b_datap->db_type) {
16494 	case M_ERROR:
16495 	case M_HANGUP:
16496 		/*
16497 		 * The device has a problem.  We force the ILL down.  It can
16498 		 * be brought up again manually using SIOCSIFFLAGS (via
16499 		 * ifconfig or equivalent).
16500 		 */
16501 		ASSERT(ipsq != NULL);
16502 		if (mp->b_rptr < mp->b_wptr)
16503 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16504 		if (ill->ill_error == 0)
16505 			ill->ill_error = ENXIO;
16506 		if (!ill_down_start(q, mp))
16507 			return;
16508 		ipif_all_down_tail(ipsq, q, mp, NULL);
16509 		break;
16510 	case M_IOCNAK: {
16511 		iocp = (struct iocblk *)mp->b_rptr;
16512 
16513 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
16514 		/*
16515 		 * If this was the first attempt, turn off the fastpath
16516 		 * probing.
16517 		 */
16518 		mutex_enter(&ill->ill_lock);
16519 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16520 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
16521 			mutex_exit(&ill->ill_lock);
16522 			ill_fastpath_nack(ill);
16523 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
16524 			    ill->ill_name));
16525 		} else {
16526 			mutex_exit(&ill->ill_lock);
16527 		}
16528 		freemsg(mp);
16529 		break;
16530 	}
16531 	default:
16532 		ASSERT(0);
16533 		break;
16534 	}
16535 }
16536 
16537 /*
16538  * NOTE : This function does not ire_refrele the ire argument passed in.
16539  *
16540  * IPQoS notes
16541  * IP policy is invoked twice for a forwarded packet, once on the read side
16542  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16543  * enabled. An additional parameter, in_ill, has been added for this purpose.
16544  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16545  * because ip_mroute drops this information.
16546  *
16547  */
16548 void
16549 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16550 {
16551 	uint32_t	old_pkt_len;
16552 	uint32_t	pkt_len;
16553 	queue_t	*q;
16554 	uint32_t	sum;
16555 #define	rptr	((uchar_t *)ipha)
16556 	uint32_t	max_frag;
16557 	uint32_t	ill_index;
16558 	ill_t		*out_ill;
16559 	mib2_ipIfStatsEntry_t *mibptr;
16560 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16561 
16562 	/* Get the ill_index of the incoming ILL */
16563 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16564 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16565 
16566 	/* Initiate Read side IPPF processing */
16567 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16568 		ip_process(IPP_FWD_IN, &mp, ill_index);
16569 		if (mp == NULL) {
16570 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16571 			    "during IPPF processing\n"));
16572 			return;
16573 		}
16574 	}
16575 
16576 	/* Adjust the checksum to reflect the ttl decrement. */
16577 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16578 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16579 
16580 	if (ipha->ipha_ttl-- <= 1) {
16581 		if (ip_csum_hdr(ipha)) {
16582 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16583 			goto drop_pkt;
16584 		}
16585 		/*
16586 		 * Note: ire_stq this will be NULL for multicast
16587 		 * datagrams using the long path through arp (the IRE
16588 		 * is not an IRE_CACHE). This should not cause
16589 		 * problems since we don't generate ICMP errors for
16590 		 * multicast packets.
16591 		 */
16592 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16593 		q = ire->ire_stq;
16594 		if (q != NULL) {
16595 			/* Sent by forwarding path, and router is global zone */
16596 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16597 			    GLOBAL_ZONEID, ipst);
16598 		} else
16599 			freemsg(mp);
16600 		return;
16601 	}
16602 
16603 	/*
16604 	 * Don't forward if the interface is down
16605 	 */
16606 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16607 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16608 		ip2dbg(("ip_rput_forward:interface is down\n"));
16609 		goto drop_pkt;
16610 	}
16611 
16612 	/* Get the ill_index of the outgoing ILL */
16613 	out_ill = ire_to_ill(ire);
16614 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16615 
16616 	DTRACE_PROBE4(ip4__forwarding__start,
16617 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16618 
16619 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16620 	    ipst->ips_ipv4firewall_forwarding,
16621 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16622 
16623 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16624 
16625 	if (mp == NULL)
16626 		return;
16627 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16628 
16629 	if (is_system_labeled()) {
16630 		mblk_t *mp1;
16631 
16632 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16633 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16634 			goto drop_pkt;
16635 		}
16636 		/* Size may have changed */
16637 		mp = mp1;
16638 		ipha = (ipha_t *)mp->b_rptr;
16639 		pkt_len = ntohs(ipha->ipha_length);
16640 	}
16641 
16642 	/* Check if there are options to update */
16643 	if (!IS_SIMPLE_IPH(ipha)) {
16644 		if (ip_csum_hdr(ipha)) {
16645 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16646 			goto drop_pkt;
16647 		}
16648 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16649 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16650 			return;
16651 		}
16652 
16653 		ipha->ipha_hdr_checksum = 0;
16654 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16655 	}
16656 	max_frag = ire->ire_max_frag;
16657 	if (pkt_len > max_frag) {
16658 		/*
16659 		 * It needs fragging on its way out.  We haven't
16660 		 * verified the header checksum yet.  Since we
16661 		 * are going to put a surely good checksum in the
16662 		 * outgoing header, we have to make sure that it
16663 		 * was good coming in.
16664 		 */
16665 		if (ip_csum_hdr(ipha)) {
16666 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16667 			goto drop_pkt;
16668 		}
16669 		/* Initiate Write side IPPF processing */
16670 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16671 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16672 			if (mp == NULL) {
16673 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16674 				    " during IPPF processing\n"));
16675 				return;
16676 			}
16677 		}
16678 		/*
16679 		 * Handle labeled packet resizing.
16680 		 *
16681 		 * If we have added a label, inform ip_wput_frag() of its
16682 		 * effect on the MTU for ICMP messages.
16683 		 */
16684 		if (pkt_len > old_pkt_len) {
16685 			uint32_t secopt_size;
16686 
16687 			secopt_size = pkt_len - old_pkt_len;
16688 			if (secopt_size < max_frag)
16689 				max_frag -= secopt_size;
16690 		}
16691 
16692 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16693 		    GLOBAL_ZONEID, ipst, NULL);
16694 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16695 		return;
16696 	}
16697 
16698 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16699 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16700 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16701 	    ipst->ips_ipv4firewall_physical_out,
16702 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16703 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16704 	if (mp == NULL)
16705 		return;
16706 
16707 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16708 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16709 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16710 	/* ip_xmit_v4 always consumes the packet */
16711 	return;
16712 
16713 drop_pkt:;
16714 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16715 	freemsg(mp);
16716 #undef	rptr
16717 }
16718 
16719 void
16720 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16721 {
16722 	ire_t	*ire;
16723 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16724 
16725 	ASSERT(!ipif->ipif_isv6);
16726 	/*
16727 	 * Find an IRE which matches the destination and the outgoing
16728 	 * queue in the cache table. All we need is an IRE_CACHE which
16729 	 * is pointing at ipif->ipif_ill.
16730 	 */
16731 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16732 		dst = ipif->ipif_pp_dst_addr;
16733 
16734 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16735 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16736 	if (ire == NULL) {
16737 		/*
16738 		 * Mark this packet to make it be delivered to
16739 		 * ip_rput_forward after the new ire has been
16740 		 * created.
16741 		 */
16742 		mp->b_prev = NULL;
16743 		mp->b_next = mp;
16744 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16745 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16746 	} else {
16747 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16748 		IRE_REFRELE(ire);
16749 	}
16750 }
16751 
16752 /* Update any source route, record route or timestamp options */
16753 static int
16754 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16755 {
16756 	ipoptp_t	opts;
16757 	uchar_t		*opt;
16758 	uint8_t		optval;
16759 	uint8_t		optlen;
16760 	ipaddr_t	dst;
16761 	uint32_t	ts;
16762 	ire_t		*dst_ire = NULL;
16763 	ire_t		*tmp_ire = NULL;
16764 	timestruc_t	now;
16765 
16766 	ip2dbg(("ip_rput_forward_options\n"));
16767 	dst = ipha->ipha_dst;
16768 	for (optval = ipoptp_first(&opts, ipha);
16769 	    optval != IPOPT_EOL;
16770 	    optval = ipoptp_next(&opts)) {
16771 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16772 		opt = opts.ipoptp_cur;
16773 		optlen = opts.ipoptp_len;
16774 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16775 		    optval, opts.ipoptp_len));
16776 		switch (optval) {
16777 			uint32_t off;
16778 		case IPOPT_SSRR:
16779 		case IPOPT_LSRR:
16780 			/* Check if adminstratively disabled */
16781 			if (!ipst->ips_ip_forward_src_routed) {
16782 				if (ire->ire_stq != NULL) {
16783 					/*
16784 					 * Sent by forwarding path, and router
16785 					 * is global zone
16786 					 */
16787 					icmp_unreachable(ire->ire_stq, mp,
16788 					    ICMP_SOURCE_ROUTE_FAILED,
16789 					    GLOBAL_ZONEID, ipst);
16790 				} else {
16791 					ip0dbg(("ip_rput_forward_options: "
16792 					    "unable to send unreach\n"));
16793 					freemsg(mp);
16794 				}
16795 				return (-1);
16796 			}
16797 
16798 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16799 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16800 			if (dst_ire == NULL) {
16801 				/*
16802 				 * Must be partial since ip_rput_options
16803 				 * checked for strict.
16804 				 */
16805 				break;
16806 			}
16807 			off = opt[IPOPT_OFFSET];
16808 			off--;
16809 		redo_srr:
16810 			if (optlen < IP_ADDR_LEN ||
16811 			    off > optlen - IP_ADDR_LEN) {
16812 				/* End of source route */
16813 				ip1dbg((
16814 				    "ip_rput_forward_options: end of SR\n"));
16815 				ire_refrele(dst_ire);
16816 				break;
16817 			}
16818 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16819 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16820 			    IP_ADDR_LEN);
16821 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16822 			    ntohl(dst)));
16823 
16824 			/*
16825 			 * Check if our address is present more than
16826 			 * once as consecutive hops in source route.
16827 			 */
16828 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16829 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16830 			if (tmp_ire != NULL) {
16831 				ire_refrele(tmp_ire);
16832 				off += IP_ADDR_LEN;
16833 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16834 				goto redo_srr;
16835 			}
16836 			ipha->ipha_dst = dst;
16837 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16838 			ire_refrele(dst_ire);
16839 			break;
16840 		case IPOPT_RR:
16841 			off = opt[IPOPT_OFFSET];
16842 			off--;
16843 			if (optlen < IP_ADDR_LEN ||
16844 			    off > optlen - IP_ADDR_LEN) {
16845 				/* No more room - ignore */
16846 				ip1dbg((
16847 				    "ip_rput_forward_options: end of RR\n"));
16848 				break;
16849 			}
16850 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16851 			    IP_ADDR_LEN);
16852 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16853 			break;
16854 		case IPOPT_TS:
16855 			/* Insert timestamp if there is room */
16856 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16857 			case IPOPT_TS_TSONLY:
16858 				off = IPOPT_TS_TIMELEN;
16859 				break;
16860 			case IPOPT_TS_PRESPEC:
16861 			case IPOPT_TS_PRESPEC_RFC791:
16862 				/* Verify that the address matched */
16863 				off = opt[IPOPT_OFFSET] - 1;
16864 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16865 				dst_ire = ire_ctable_lookup(dst, 0,
16866 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16867 				    MATCH_IRE_TYPE, ipst);
16868 				if (dst_ire == NULL) {
16869 					/* Not for us */
16870 					break;
16871 				}
16872 				ire_refrele(dst_ire);
16873 				/* FALLTHRU */
16874 			case IPOPT_TS_TSANDADDR:
16875 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16876 				break;
16877 			default:
16878 				/*
16879 				 * ip_*put_options should have already
16880 				 * dropped this packet.
16881 				 */
16882 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16883 				    "unknown IT - bug in ip_rput_options?\n");
16884 				return (0);	/* Keep "lint" happy */
16885 			}
16886 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16887 				/* Increase overflow counter */
16888 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16889 				opt[IPOPT_POS_OV_FLG] =
16890 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16891 				    (off << 4));
16892 				break;
16893 			}
16894 			off = opt[IPOPT_OFFSET] - 1;
16895 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16896 			case IPOPT_TS_PRESPEC:
16897 			case IPOPT_TS_PRESPEC_RFC791:
16898 			case IPOPT_TS_TSANDADDR:
16899 				bcopy(&ire->ire_src_addr,
16900 				    (char *)opt + off, IP_ADDR_LEN);
16901 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16902 				/* FALLTHRU */
16903 			case IPOPT_TS_TSONLY:
16904 				off = opt[IPOPT_OFFSET] - 1;
16905 				/* Compute # of milliseconds since midnight */
16906 				gethrestime(&now);
16907 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16908 				    now.tv_nsec / (NANOSEC / MILLISEC);
16909 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16910 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16911 				break;
16912 			}
16913 			break;
16914 		}
16915 	}
16916 	return (0);
16917 }
16918 
16919 /*
16920  * This is called after processing at least one of AH/ESP headers.
16921  *
16922  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16923  * the actual, physical interface on which the packet was received,
16924  * but, when ip_strict_dst_multihoming is set to 1, could be the
16925  * interface which had the ipha_dst configured when the packet went
16926  * through ip_rput. The ill_index corresponding to the recv_ill
16927  * is saved in ipsec_in_rill_index
16928  *
16929  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16930  * cannot assume "ire" points to valid data for any IPv6 cases.
16931  */
16932 void
16933 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16934 {
16935 	mblk_t *mp;
16936 	ipaddr_t dst;
16937 	in6_addr_t *v6dstp;
16938 	ipha_t *ipha;
16939 	ip6_t *ip6h;
16940 	ipsec_in_t *ii;
16941 	boolean_t ill_need_rele = B_FALSE;
16942 	boolean_t rill_need_rele = B_FALSE;
16943 	boolean_t ire_need_rele = B_FALSE;
16944 	netstack_t	*ns;
16945 	ip_stack_t	*ipst;
16946 
16947 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16948 	ASSERT(ii->ipsec_in_ill_index != 0);
16949 	ns = ii->ipsec_in_ns;
16950 	ASSERT(ii->ipsec_in_ns != NULL);
16951 	ipst = ns->netstack_ip;
16952 
16953 	mp = ipsec_mp->b_cont;
16954 	ASSERT(mp != NULL);
16955 
16956 	if (ill == NULL) {
16957 		ASSERT(recv_ill == NULL);
16958 		/*
16959 		 * We need to get the original queue on which ip_rput_local
16960 		 * or ip_rput_data_v6 was called.
16961 		 */
16962 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16963 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16964 		ill_need_rele = B_TRUE;
16965 
16966 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16967 			recv_ill = ill_lookup_on_ifindex(
16968 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16969 			    NULL, NULL, NULL, NULL, ipst);
16970 			rill_need_rele = B_TRUE;
16971 		} else {
16972 			recv_ill = ill;
16973 		}
16974 
16975 		if ((ill == NULL) || (recv_ill == NULL)) {
16976 			ip0dbg(("ip_fanout_proto_again: interface "
16977 			    "disappeared\n"));
16978 			if (ill != NULL)
16979 				ill_refrele(ill);
16980 			if (recv_ill != NULL)
16981 				ill_refrele(recv_ill);
16982 			freemsg(ipsec_mp);
16983 			return;
16984 		}
16985 	}
16986 
16987 	ASSERT(ill != NULL && recv_ill != NULL);
16988 
16989 	if (mp->b_datap->db_type == M_CTL) {
16990 		/*
16991 		 * AH/ESP is returning the ICMP message after
16992 		 * removing their headers. Fanout again till
16993 		 * it gets to the right protocol.
16994 		 */
16995 		if (ii->ipsec_in_v4) {
16996 			icmph_t *icmph;
16997 			int iph_hdr_length;
16998 			int hdr_length;
16999 
17000 			ipha = (ipha_t *)mp->b_rptr;
17001 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17002 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17003 			ipha = (ipha_t *)&icmph[1];
17004 			hdr_length = IPH_HDR_LENGTH(ipha);
17005 			/*
17006 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17007 			 * Reset the type to M_DATA.
17008 			 */
17009 			mp->b_datap->db_type = M_DATA;
17010 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17011 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17012 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17013 		} else {
17014 			icmp6_t *icmp6;
17015 			int hdr_length;
17016 
17017 			ip6h = (ip6_t *)mp->b_rptr;
17018 			/* Don't call hdr_length_v6() unless you have to. */
17019 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17020 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17021 			else
17022 				hdr_length = IPV6_HDR_LEN;
17023 
17024 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17025 			/*
17026 			 * icmp_inbound_error_fanout_v6 may need to do
17027 			 * pullupmsg.  Reset the type to M_DATA.
17028 			 */
17029 			mp->b_datap->db_type = M_DATA;
17030 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17031 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17032 			    ii->ipsec_in_zoneid);
17033 		}
17034 		if (ill_need_rele)
17035 			ill_refrele(ill);
17036 		if (rill_need_rele)
17037 			ill_refrele(recv_ill);
17038 		return;
17039 	}
17040 
17041 	if (ii->ipsec_in_v4) {
17042 		ipha = (ipha_t *)mp->b_rptr;
17043 		dst = ipha->ipha_dst;
17044 		if (CLASSD(dst)) {
17045 			/*
17046 			 * Multicast has to be delivered to all streams.
17047 			 */
17048 			dst = INADDR_BROADCAST;
17049 		}
17050 
17051 		if (ire == NULL) {
17052 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17053 			    msg_getlabel(mp), ipst);
17054 			if (ire == NULL) {
17055 				if (ill_need_rele)
17056 					ill_refrele(ill);
17057 				if (rill_need_rele)
17058 					ill_refrele(recv_ill);
17059 				ip1dbg(("ip_fanout_proto_again: "
17060 				    "IRE not found"));
17061 				freemsg(ipsec_mp);
17062 				return;
17063 			}
17064 			ire_need_rele = B_TRUE;
17065 		}
17066 
17067 		switch (ipha->ipha_protocol) {
17068 		case IPPROTO_UDP:
17069 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17070 			    recv_ill);
17071 			if (ire_need_rele)
17072 				ire_refrele(ire);
17073 			break;
17074 		case IPPROTO_TCP:
17075 			if (!ire_need_rele)
17076 				IRE_REFHOLD(ire);
17077 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17078 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17079 			IRE_REFRELE(ire);
17080 			if (mp != NULL) {
17081 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17082 				    mp, 1, SQ_PROCESS,
17083 				    SQTAG_IP_PROTO_AGAIN);
17084 			}
17085 			break;
17086 		case IPPROTO_SCTP:
17087 			if (!ire_need_rele)
17088 				IRE_REFHOLD(ire);
17089 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17090 			    ipsec_mp, 0, ill->ill_rq, dst);
17091 			break;
17092 		case IPPROTO_ENCAP:
17093 		case IPPROTO_IPV6:
17094 			if (ip_iptun_input(ipsec_mp, mp, ipha, ill, ire,
17095 			    ill->ill_ipst)) {
17096 				/*
17097 				 * If we made it here, we don't need to worry
17098 				 * about the raw-socket/protocol fanout.
17099 				 */
17100 				if (ire_need_rele)
17101 					ire_refrele(ire);
17102 				break;
17103 			}
17104 			/* else FALLTHRU */
17105 		default:
17106 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17107 			    recv_ill, 0);
17108 			if (ire_need_rele)
17109 				ire_refrele(ire);
17110 			break;
17111 		}
17112 	} else {
17113 		uint32_t rput_flags = 0;
17114 
17115 		ip6h = (ip6_t *)mp->b_rptr;
17116 		v6dstp = &ip6h->ip6_dst;
17117 		/*
17118 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17119 		 * address.
17120 		 *
17121 		 * Currently, we don't store that state in the IPSEC_IN
17122 		 * message, and we may need to.
17123 		 */
17124 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17125 		    IP6_IN_LLMCAST : 0);
17126 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17127 		    NULL, NULL);
17128 	}
17129 	if (ill_need_rele)
17130 		ill_refrele(ill);
17131 	if (rill_need_rele)
17132 		ill_refrele(recv_ill);
17133 }
17134 
17135 /*
17136  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17137  * returns 'true' if there are still fragments left on the queue, in
17138  * which case we restart the timer.
17139  */
17140 void
17141 ill_frag_timer(void *arg)
17142 {
17143 	ill_t	*ill = (ill_t *)arg;
17144 	boolean_t frag_pending;
17145 	ip_stack_t	*ipst = ill->ill_ipst;
17146 	time_t	timeout;
17147 
17148 	mutex_enter(&ill->ill_lock);
17149 	ASSERT(!ill->ill_fragtimer_executing);
17150 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17151 		ill->ill_frag_timer_id = 0;
17152 		mutex_exit(&ill->ill_lock);
17153 		return;
17154 	}
17155 	ill->ill_fragtimer_executing = 1;
17156 	mutex_exit(&ill->ill_lock);
17157 
17158 	if (ill->ill_isv6)
17159 		timeout = ipst->ips_ipv6_frag_timeout;
17160 	else
17161 		timeout = ipst->ips_ip_g_frag_timeout;
17162 
17163 	frag_pending = ill_frag_timeout(ill, timeout);
17164 
17165 	/*
17166 	 * Restart the timer, if we have fragments pending or if someone
17167 	 * wanted us to be scheduled again.
17168 	 */
17169 	mutex_enter(&ill->ill_lock);
17170 	ill->ill_fragtimer_executing = 0;
17171 	ill->ill_frag_timer_id = 0;
17172 	if (frag_pending || ill->ill_fragtimer_needrestart)
17173 		ill_frag_timer_start(ill);
17174 	mutex_exit(&ill->ill_lock);
17175 }
17176 
17177 void
17178 ill_frag_timer_start(ill_t *ill)
17179 {
17180 	ip_stack_t	*ipst = ill->ill_ipst;
17181 	clock_t	timeo_ms;
17182 
17183 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17184 
17185 	/* If the ill is closing or opening don't proceed */
17186 	if (ill->ill_state_flags & ILL_CONDEMNED)
17187 		return;
17188 
17189 	if (ill->ill_fragtimer_executing) {
17190 		/*
17191 		 * ill_frag_timer is currently executing. Just record the
17192 		 * the fact that we want the timer to be restarted.
17193 		 * ill_frag_timer will post a timeout before it returns,
17194 		 * ensuring it will be called again.
17195 		 */
17196 		ill->ill_fragtimer_needrestart = 1;
17197 		return;
17198 	}
17199 
17200 	if (ill->ill_frag_timer_id == 0) {
17201 		if (ill->ill_isv6)
17202 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17203 		else
17204 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17205 		/*
17206 		 * The timer is neither running nor is the timeout handler
17207 		 * executing. Post a timeout so that ill_frag_timer will be
17208 		 * called
17209 		 */
17210 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17211 		    MSEC_TO_TICK(timeo_ms >> 1));
17212 		ill->ill_fragtimer_needrestart = 0;
17213 	}
17214 }
17215 
17216 /*
17217  * This routine is needed for loopback when forwarding multicasts.
17218  *
17219  * IPQoS Notes:
17220  * IPPF processing is done in fanout routines.
17221  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17222  * processing for IPsec packets is done when it comes back in clear.
17223  * NOTE : The callers of this function need to do the ire_refrele for the
17224  *	  ire that is being passed in.
17225  */
17226 void
17227 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17228     ill_t *recv_ill, uint32_t esp_udp_ports)
17229 {
17230 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17231 	ill_t	*ill = (ill_t *)q->q_ptr;
17232 	uint32_t	sum;
17233 	uint32_t	u1;
17234 	uint32_t	u2;
17235 	int		hdr_length;
17236 	boolean_t	mctl_present;
17237 	mblk_t		*first_mp = mp;
17238 	mblk_t		*hada_mp = NULL;
17239 	ipha_t		*inner_ipha;
17240 	ip_stack_t	*ipst;
17241 
17242 	ASSERT(recv_ill != NULL);
17243 	ipst = recv_ill->ill_ipst;
17244 
17245 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17246 	    "ip_rput_locl_start: q %p", q);
17247 
17248 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17249 	ASSERT(ill != NULL);
17250 
17251 #define	rptr	((uchar_t *)ipha)
17252 #define	iphs	((uint16_t *)ipha)
17253 
17254 	/*
17255 	 * no UDP or TCP packet should come here anymore.
17256 	 */
17257 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17258 	    ipha->ipha_protocol != IPPROTO_UDP);
17259 
17260 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17261 	if (mctl_present &&
17262 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17263 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17264 
17265 		/*
17266 		 * It's an IPsec accelerated packet.
17267 		 * Keep a pointer to the data attributes around until
17268 		 * we allocate the ipsec_info_t.
17269 		 */
17270 		IPSECHW_DEBUG(IPSECHW_PKT,
17271 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17272 		hada_mp = first_mp;
17273 		hada_mp->b_cont = NULL;
17274 		/*
17275 		 * Since it is accelerated, it comes directly from
17276 		 * the ill and the data attributes is followed by
17277 		 * the packet data.
17278 		 */
17279 		ASSERT(mp->b_datap->db_type != M_CTL);
17280 		first_mp = mp;
17281 		mctl_present = B_FALSE;
17282 	}
17283 
17284 	/*
17285 	 * IF M_CTL is not present, then ipsec_in_is_secure
17286 	 * should return B_TRUE. There is a case where loopback
17287 	 * packets has an M_CTL in the front with all the
17288 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17289 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17290 	 * packets never comes here, it is safe to ASSERT the
17291 	 * following.
17292 	 */
17293 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17294 
17295 	/*
17296 	 * Also, we should never have an mctl_present if this is an
17297 	 * ESP-in-UDP packet.
17298 	 */
17299 	ASSERT(!mctl_present || !esp_in_udp_packet);
17300 
17301 	/* u1 is # words of IP options */
17302 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17303 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17304 
17305 	/*
17306 	 * Don't verify header checksum if we just removed UDP header or
17307 	 * packet is coming back from AH/ESP.
17308 	 */
17309 	if (!esp_in_udp_packet && !mctl_present) {
17310 		if (u1) {
17311 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17312 				if (hada_mp != NULL)
17313 					freemsg(hada_mp);
17314 				return;
17315 			}
17316 		} else {
17317 			/* Check the IP header checksum.  */
17318 #define	uph	((uint16_t *)ipha)
17319 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17320 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17321 #undef  uph
17322 			/* finish doing IP checksum */
17323 			sum = (sum & 0xFFFF) + (sum >> 16);
17324 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17325 			if (sum && sum != 0xFFFF) {
17326 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17327 				goto drop_pkt;
17328 			}
17329 		}
17330 	}
17331 
17332 	/*
17333 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17334 	 * might be called more than once for secure packets, count only
17335 	 * the first time.
17336 	 */
17337 	if (!mctl_present) {
17338 		UPDATE_IB_PKT_COUNT(ire);
17339 		ire->ire_last_used_time = lbolt;
17340 	}
17341 
17342 	/* Check for fragmentation offset. */
17343 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17344 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17345 	if (u1) {
17346 		/*
17347 		 * We re-assemble fragments before we do the AH/ESP
17348 		 * processing. Thus, M_CTL should not be present
17349 		 * while we are re-assembling.
17350 		 */
17351 		ASSERT(!mctl_present);
17352 		ASSERT(first_mp == mp);
17353 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17354 			return;
17355 
17356 		/*
17357 		 * Make sure that first_mp points back to mp as
17358 		 * the mp we came in with could have changed in
17359 		 * ip_rput_fragment().
17360 		 */
17361 		ipha = (ipha_t *)mp->b_rptr;
17362 		first_mp = mp;
17363 	}
17364 
17365 	/*
17366 	 * Clear hardware checksumming flag as it is currently only
17367 	 * used by TCP and UDP.
17368 	 */
17369 	DB_CKSUMFLAGS(mp) = 0;
17370 
17371 	/* Now we have a complete datagram, destined for this machine. */
17372 	u1 = IPH_HDR_LENGTH(ipha);
17373 	switch (ipha->ipha_protocol) {
17374 	case IPPROTO_ICMP: {
17375 		ire_t		*ire_zone;
17376 		ilm_t		*ilm;
17377 		mblk_t		*mp1;
17378 		zoneid_t	last_zoneid;
17379 		ilm_walker_t	ilw;
17380 
17381 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17382 			ASSERT(ire->ire_type == IRE_BROADCAST);
17383 
17384 			/*
17385 			 * In the multicast case, applications may have joined
17386 			 * the group from different zones, so we need to deliver
17387 			 * the packet to each of them. Loop through the
17388 			 * multicast memberships structures (ilm) on the receive
17389 			 * ill and send a copy of the packet up each matching
17390 			 * one. However, we don't do this for multicasts sent on
17391 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17392 			 * they must stay in the sender's zone.
17393 			 *
17394 			 * ilm_add_v6() ensures that ilms in the same zone are
17395 			 * contiguous in the ill_ilm list. We use this property
17396 			 * to avoid sending duplicates needed when two
17397 			 * applications in the same zone join the same group on
17398 			 * different logical interfaces: we ignore the ilm if
17399 			 * its zoneid is the same as the last matching one.
17400 			 * In addition, the sending of the packet for
17401 			 * ire_zoneid is delayed until all of the other ilms
17402 			 * have been exhausted.
17403 			 */
17404 			last_zoneid = -1;
17405 			ilm = ilm_walker_start(&ilw, recv_ill);
17406 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17407 				if (ipha->ipha_dst != ilm->ilm_addr ||
17408 				    ilm->ilm_zoneid == last_zoneid ||
17409 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17410 				    ilm->ilm_zoneid == ALL_ZONES ||
17411 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17412 					continue;
17413 				mp1 = ip_copymsg(first_mp);
17414 				if (mp1 == NULL)
17415 					continue;
17416 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17417 				    0, sum, mctl_present, B_TRUE,
17418 				    recv_ill, ilm->ilm_zoneid);
17419 				last_zoneid = ilm->ilm_zoneid;
17420 			}
17421 			ilm_walker_finish(&ilw);
17422 		} else if (ire->ire_type == IRE_BROADCAST) {
17423 			/*
17424 			 * In the broadcast case, there may be many zones
17425 			 * which need a copy of the packet delivered to them.
17426 			 * There is one IRE_BROADCAST per broadcast address
17427 			 * and per zone; we walk those using a helper function.
17428 			 * In addition, the sending of the packet for ire is
17429 			 * delayed until all of the other ires have been
17430 			 * processed.
17431 			 */
17432 			IRB_REFHOLD(ire->ire_bucket);
17433 			ire_zone = NULL;
17434 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17435 			    ire)) != NULL) {
17436 				mp1 = ip_copymsg(first_mp);
17437 				if (mp1 == NULL)
17438 					continue;
17439 
17440 				UPDATE_IB_PKT_COUNT(ire_zone);
17441 				ire_zone->ire_last_used_time = lbolt;
17442 				icmp_inbound(q, mp1, B_TRUE, ill,
17443 				    0, sum, mctl_present, B_TRUE,
17444 				    recv_ill, ire_zone->ire_zoneid);
17445 			}
17446 			IRB_REFRELE(ire->ire_bucket);
17447 		}
17448 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17449 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17450 		    ire->ire_zoneid);
17451 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17452 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17453 		return;
17454 	}
17455 	case IPPROTO_IGMP:
17456 		/*
17457 		 * If we are not willing to accept IGMP packets in clear,
17458 		 * then check with global policy.
17459 		 */
17460 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17461 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17462 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17463 			if (first_mp == NULL)
17464 				return;
17465 		}
17466 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17467 			freemsg(first_mp);
17468 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17469 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17470 			return;
17471 		}
17472 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17473 			/* Bad packet - discarded by igmp_input */
17474 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17475 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17476 			if (mctl_present)
17477 				freeb(first_mp);
17478 			return;
17479 		}
17480 		/*
17481 		 * igmp_input() may have returned the pulled up message.
17482 		 * So first_mp and ipha need to be reinitialized.
17483 		 */
17484 		ipha = (ipha_t *)mp->b_rptr;
17485 		if (mctl_present)
17486 			first_mp->b_cont = mp;
17487 		else
17488 			first_mp = mp;
17489 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17490 		    connf_head != NULL) {
17491 			/* No user-level listener for IGMP packets */
17492 			goto drop_pkt;
17493 		}
17494 		/* deliver to local raw users */
17495 		break;
17496 	case IPPROTO_PIM:
17497 		/*
17498 		 * If we are not willing to accept PIM packets in clear,
17499 		 * then check with global policy.
17500 		 */
17501 		if (ipst->ips_pim_accept_clear_messages == 0) {
17502 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17503 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17504 			if (first_mp == NULL)
17505 				return;
17506 		}
17507 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17508 			freemsg(first_mp);
17509 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17510 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17511 			return;
17512 		}
17513 		if (pim_input(q, mp, ill) != 0) {
17514 			/* Bad packet - discarded by pim_input */
17515 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17516 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17517 			if (mctl_present)
17518 				freeb(first_mp);
17519 			return;
17520 		}
17521 
17522 		/*
17523 		 * pim_input() may have pulled up the message so ipha needs to
17524 		 * be reinitialized.
17525 		 */
17526 		ipha = (ipha_t *)mp->b_rptr;
17527 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17528 		    connf_head != NULL) {
17529 			/* No user-level listener for PIM packets */
17530 			goto drop_pkt;
17531 		}
17532 		/* deliver to local raw users */
17533 		break;
17534 	case IPPROTO_ENCAP:
17535 		/*
17536 		 * Handle self-encapsulated packets (IP-in-IP where
17537 		 * the inner addresses == the outer addresses).
17538 		 */
17539 		hdr_length = IPH_HDR_LENGTH(ipha);
17540 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17541 		    mp->b_wptr) {
17542 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17543 			    sizeof (ipha_t) - mp->b_rptr)) {
17544 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17545 				freemsg(first_mp);
17546 				return;
17547 			}
17548 			ipha = (ipha_t *)mp->b_rptr;
17549 		}
17550 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17551 		/*
17552 		 * Check the sanity of the inner IP header.
17553 		 */
17554 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17555 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17556 			freemsg(first_mp);
17557 			return;
17558 		}
17559 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17560 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17561 			freemsg(first_mp);
17562 			return;
17563 		}
17564 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17565 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17566 			ipsec_in_t *ii;
17567 
17568 			/*
17569 			 * Self-encapsulated tunnel packet. Remove
17570 			 * the outer IP header and fanout again.
17571 			 * We also need to make sure that the inner
17572 			 * header is pulled up until options.
17573 			 */
17574 			mp->b_rptr = (uchar_t *)inner_ipha;
17575 			ipha = inner_ipha;
17576 			hdr_length = IPH_HDR_LENGTH(ipha);
17577 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17578 				if (!pullupmsg(mp, (uchar_t *)ipha +
17579 				    + hdr_length - mp->b_rptr)) {
17580 					freemsg(first_mp);
17581 					return;
17582 				}
17583 				ipha = (ipha_t *)mp->b_rptr;
17584 			}
17585 			if (hdr_length > sizeof (ipha_t)) {
17586 				/* We got options on the inner packet. */
17587 				ipaddr_t dst = ipha->ipha_dst;
17588 
17589 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17590 				    -1) {
17591 					/* Bad options! */
17592 					return;
17593 				}
17594 				if (dst != ipha->ipha_dst) {
17595 					/*
17596 					 * Someone put a source-route in
17597 					 * the inside header of a self-
17598 					 * encapsulated packet.  Drop it
17599 					 * with extreme prejudice and let
17600 					 * the sender know.
17601 					 */
17602 					icmp_unreachable(q, first_mp,
17603 					    ICMP_SOURCE_ROUTE_FAILED,
17604 					    recv_ill->ill_zoneid, ipst);
17605 					return;
17606 				}
17607 			}
17608 			if (!mctl_present) {
17609 				ASSERT(first_mp == mp);
17610 				/*
17611 				 * This means that somebody is sending
17612 				 * Self-encapsualted packets without AH/ESP.
17613 				 * If AH/ESP was present, we would have already
17614 				 * allocated the first_mp.
17615 				 *
17616 				 * Send this packet to find a tunnel endpoint.
17617 				 * if I can't find one, an ICMP
17618 				 * PROTOCOL_UNREACHABLE will get sent.
17619 				 */
17620 				goto fanout;
17621 			}
17622 			/*
17623 			 * We generally store the ill_index if we need to
17624 			 * do IPsec processing as we lose the ill queue when
17625 			 * we come back. But in this case, we never should
17626 			 * have to store the ill_index here as it should have
17627 			 * been stored previously when we processed the
17628 			 * AH/ESP header in this routine or for non-ipsec
17629 			 * cases, we still have the queue. But for some bad
17630 			 * packets from the wire, we can get to IPsec after
17631 			 * this and we better store the index for that case.
17632 			 */
17633 			ill = (ill_t *)q->q_ptr;
17634 			ii = (ipsec_in_t *)first_mp->b_rptr;
17635 			ii->ipsec_in_ill_index =
17636 			    ill->ill_phyint->phyint_ifindex;
17637 			ii->ipsec_in_rill_index =
17638 			    recv_ill->ill_phyint->phyint_ifindex;
17639 			if (ii->ipsec_in_decaps) {
17640 				/*
17641 				 * This packet is self-encapsulated multiple
17642 				 * times. We don't want to recurse infinitely.
17643 				 * To keep it simple, drop the packet.
17644 				 */
17645 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17646 				freemsg(first_mp);
17647 				return;
17648 			}
17649 			ii->ipsec_in_decaps = B_TRUE;
17650 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17651 			    ire);
17652 			return;
17653 		}
17654 		break;
17655 	case IPPROTO_AH:
17656 	case IPPROTO_ESP: {
17657 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17658 
17659 		/*
17660 		 * Fast path for AH/ESP. If this is the first time
17661 		 * we are sending a datagram to AH/ESP, allocate
17662 		 * a IPSEC_IN message and prepend it. Otherwise,
17663 		 * just fanout.
17664 		 */
17665 
17666 		int ipsec_rc;
17667 		ipsec_in_t *ii;
17668 		netstack_t *ns = ipst->ips_netstack;
17669 
17670 		IP_STAT(ipst, ipsec_proto_ahesp);
17671 		if (!mctl_present) {
17672 			ASSERT(first_mp == mp);
17673 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17674 			if (first_mp == NULL) {
17675 				ip1dbg(("ip_proto_input: IPSEC_IN "
17676 				    "allocation failure.\n"));
17677 				freemsg(hada_mp); /* okay ifnull */
17678 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17679 				freemsg(mp);
17680 				return;
17681 			}
17682 			/*
17683 			 * Store the ill_index so that when we come back
17684 			 * from IPsec we ride on the same queue.
17685 			 */
17686 			ill = (ill_t *)q->q_ptr;
17687 			ii = (ipsec_in_t *)first_mp->b_rptr;
17688 			ii->ipsec_in_ill_index =
17689 			    ill->ill_phyint->phyint_ifindex;
17690 			ii->ipsec_in_rill_index =
17691 			    recv_ill->ill_phyint->phyint_ifindex;
17692 			first_mp->b_cont = mp;
17693 			/*
17694 			 * Cache hardware acceleration info.
17695 			 */
17696 			if (hada_mp != NULL) {
17697 				IPSECHW_DEBUG(IPSECHW_PKT,
17698 				    ("ip_rput_local: caching data attr.\n"));
17699 				ii->ipsec_in_accelerated = B_TRUE;
17700 				ii->ipsec_in_da = hada_mp;
17701 				hada_mp = NULL;
17702 			}
17703 		} else {
17704 			ii = (ipsec_in_t *)first_mp->b_rptr;
17705 		}
17706 
17707 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17708 
17709 		if (!ipsec_loaded(ipss)) {
17710 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17711 			    ire->ire_zoneid, ipst);
17712 			return;
17713 		}
17714 
17715 		ns = ipst->ips_netstack;
17716 		/* select inbound SA and have IPsec process the pkt */
17717 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17718 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17719 			boolean_t esp_in_udp_sa;
17720 			if (esph == NULL)
17721 				return;
17722 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17723 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17724 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17725 			    IPSA_F_NATT) != 0);
17726 			/*
17727 			 * The following is a fancy, but quick, way of saying:
17728 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17729 			 *    OR
17730 			 * ESP SA and ESP-in-UDP packet --> drop
17731 			 */
17732 			if (esp_in_udp_sa != esp_in_udp_packet) {
17733 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17734 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17735 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17736 				    &ns->netstack_ipsec->ipsec_dropper);
17737 				return;
17738 			}
17739 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17740 			    first_mp, esph);
17741 		} else {
17742 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17743 			if (ah == NULL)
17744 				return;
17745 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17746 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17747 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17748 			    first_mp, ah);
17749 		}
17750 
17751 		switch (ipsec_rc) {
17752 		case IPSEC_STATUS_SUCCESS:
17753 			break;
17754 		case IPSEC_STATUS_FAILED:
17755 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17756 			/* FALLTHRU */
17757 		case IPSEC_STATUS_PENDING:
17758 			return;
17759 		}
17760 		/* we're done with IPsec processing, send it up */
17761 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17762 		return;
17763 	}
17764 	default:
17765 		break;
17766 	}
17767 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17768 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17769 		    ire->ire_zoneid));
17770 		goto drop_pkt;
17771 	}
17772 	/*
17773 	 * Handle protocols with which IP is less intimate.  There
17774 	 * can be more than one stream bound to a particular
17775 	 * protocol.  When this is the case, each one gets a copy
17776 	 * of any incoming packets.
17777 	 */
17778 fanout:
17779 	ip_fanout_proto(q, first_mp, ill, ipha,
17780 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17781 	    B_TRUE, recv_ill, ire->ire_zoneid);
17782 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17783 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17784 	return;
17785 
17786 drop_pkt:
17787 	freemsg(first_mp);
17788 	if (hada_mp != NULL)
17789 		freeb(hada_mp);
17790 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17791 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17792 #undef	rptr
17793 #undef  iphs
17794 
17795 }
17796 
17797 /*
17798  * Update any source route, record route or timestamp options.
17799  * Check that we are at end of strict source route.
17800  * The options have already been checked for sanity in ip_rput_options().
17801  */
17802 static boolean_t
17803 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17804     ip_stack_t *ipst)
17805 {
17806 	ipoptp_t	opts;
17807 	uchar_t		*opt;
17808 	uint8_t		optval;
17809 	uint8_t		optlen;
17810 	ipaddr_t	dst;
17811 	uint32_t	ts;
17812 	ire_t		*dst_ire;
17813 	timestruc_t	now;
17814 	zoneid_t	zoneid;
17815 	ill_t		*ill;
17816 
17817 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17818 
17819 	ip2dbg(("ip_rput_local_options\n"));
17820 
17821 	for (optval = ipoptp_first(&opts, ipha);
17822 	    optval != IPOPT_EOL;
17823 	    optval = ipoptp_next(&opts)) {
17824 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17825 		opt = opts.ipoptp_cur;
17826 		optlen = opts.ipoptp_len;
17827 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17828 		    optval, optlen));
17829 		switch (optval) {
17830 			uint32_t off;
17831 		case IPOPT_SSRR:
17832 		case IPOPT_LSRR:
17833 			off = opt[IPOPT_OFFSET];
17834 			off--;
17835 			if (optlen < IP_ADDR_LEN ||
17836 			    off > optlen - IP_ADDR_LEN) {
17837 				/* End of source route */
17838 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17839 				break;
17840 			}
17841 			/*
17842 			 * This will only happen if two consecutive entries
17843 			 * in the source route contains our address or if
17844 			 * it is a packet with a loose source route which
17845 			 * reaches us before consuming the whole source route
17846 			 */
17847 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17848 			if (optval == IPOPT_SSRR) {
17849 				goto bad_src_route;
17850 			}
17851 			/*
17852 			 * Hack: instead of dropping the packet truncate the
17853 			 * source route to what has been used by filling the
17854 			 * rest with IPOPT_NOP.
17855 			 */
17856 			opt[IPOPT_OLEN] = (uint8_t)off;
17857 			while (off < optlen) {
17858 				opt[off++] = IPOPT_NOP;
17859 			}
17860 			break;
17861 		case IPOPT_RR:
17862 			off = opt[IPOPT_OFFSET];
17863 			off--;
17864 			if (optlen < IP_ADDR_LEN ||
17865 			    off > optlen - IP_ADDR_LEN) {
17866 				/* No more room - ignore */
17867 				ip1dbg((
17868 				    "ip_rput_local_options: end of RR\n"));
17869 				break;
17870 			}
17871 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17872 			    IP_ADDR_LEN);
17873 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17874 			break;
17875 		case IPOPT_TS:
17876 			/* Insert timestamp if there is romm */
17877 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17878 			case IPOPT_TS_TSONLY:
17879 				off = IPOPT_TS_TIMELEN;
17880 				break;
17881 			case IPOPT_TS_PRESPEC:
17882 			case IPOPT_TS_PRESPEC_RFC791:
17883 				/* Verify that the address matched */
17884 				off = opt[IPOPT_OFFSET] - 1;
17885 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17886 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17887 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17888 				    ipst);
17889 				if (dst_ire == NULL) {
17890 					/* Not for us */
17891 					break;
17892 				}
17893 				ire_refrele(dst_ire);
17894 				/* FALLTHRU */
17895 			case IPOPT_TS_TSANDADDR:
17896 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17897 				break;
17898 			default:
17899 				/*
17900 				 * ip_*put_options should have already
17901 				 * dropped this packet.
17902 				 */
17903 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17904 				    "unknown IT - bug in ip_rput_options?\n");
17905 				return (B_TRUE);	/* Keep "lint" happy */
17906 			}
17907 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17908 				/* Increase overflow counter */
17909 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17910 				opt[IPOPT_POS_OV_FLG] =
17911 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17912 				    (off << 4));
17913 				break;
17914 			}
17915 			off = opt[IPOPT_OFFSET] - 1;
17916 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17917 			case IPOPT_TS_PRESPEC:
17918 			case IPOPT_TS_PRESPEC_RFC791:
17919 			case IPOPT_TS_TSANDADDR:
17920 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17921 				    IP_ADDR_LEN);
17922 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17923 				/* FALLTHRU */
17924 			case IPOPT_TS_TSONLY:
17925 				off = opt[IPOPT_OFFSET] - 1;
17926 				/* Compute # of milliseconds since midnight */
17927 				gethrestime(&now);
17928 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17929 				    now.tv_nsec / (NANOSEC / MILLISEC);
17930 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17931 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17932 				break;
17933 			}
17934 			break;
17935 		}
17936 	}
17937 	return (B_TRUE);
17938 
17939 bad_src_route:
17940 	q = WR(q);
17941 	if (q->q_next != NULL)
17942 		ill = q->q_ptr;
17943 	else
17944 		ill = NULL;
17945 
17946 	/* make sure we clear any indication of a hardware checksum */
17947 	DB_CKSUMFLAGS(mp) = 0;
17948 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17949 	if (zoneid == ALL_ZONES)
17950 		freemsg(mp);
17951 	else
17952 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17953 	return (B_FALSE);
17954 
17955 }
17956 
17957 /*
17958  * Process IP options in an inbound packet.  If an option affects the
17959  * effective destination address, return the next hop address via dstp.
17960  * Returns -1 if something fails in which case an ICMP error has been sent
17961  * and mp freed.
17962  */
17963 static int
17964 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17965     ip_stack_t *ipst)
17966 {
17967 	ipoptp_t	opts;
17968 	uchar_t		*opt;
17969 	uint8_t		optval;
17970 	uint8_t		optlen;
17971 	ipaddr_t	dst;
17972 	intptr_t	code = 0;
17973 	ire_t		*ire = NULL;
17974 	zoneid_t	zoneid;
17975 	ill_t		*ill;
17976 
17977 	ip2dbg(("ip_rput_options\n"));
17978 	dst = ipha->ipha_dst;
17979 	for (optval = ipoptp_first(&opts, ipha);
17980 	    optval != IPOPT_EOL;
17981 	    optval = ipoptp_next(&opts)) {
17982 		opt = opts.ipoptp_cur;
17983 		optlen = opts.ipoptp_len;
17984 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17985 		    optval, optlen));
17986 		/*
17987 		 * Note: we need to verify the checksum before we
17988 		 * modify anything thus this routine only extracts the next
17989 		 * hop dst from any source route.
17990 		 */
17991 		switch (optval) {
17992 			uint32_t off;
17993 		case IPOPT_SSRR:
17994 		case IPOPT_LSRR:
17995 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17996 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17997 			if (ire == NULL) {
17998 				if (optval == IPOPT_SSRR) {
17999 					ip1dbg(("ip_rput_options: not next"
18000 					    " strict source route 0x%x\n",
18001 					    ntohl(dst)));
18002 					code = (char *)&ipha->ipha_dst -
18003 					    (char *)ipha;
18004 					goto param_prob; /* RouterReq's */
18005 				}
18006 				ip2dbg(("ip_rput_options: "
18007 				    "not next source route 0x%x\n",
18008 				    ntohl(dst)));
18009 				break;
18010 			}
18011 			ire_refrele(ire);
18012 
18013 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18014 				ip1dbg((
18015 				    "ip_rput_options: bad option offset\n"));
18016 				code = (char *)&opt[IPOPT_OLEN] -
18017 				    (char *)ipha;
18018 				goto param_prob;
18019 			}
18020 			off = opt[IPOPT_OFFSET];
18021 			off--;
18022 		redo_srr:
18023 			if (optlen < IP_ADDR_LEN ||
18024 			    off > optlen - IP_ADDR_LEN) {
18025 				/* End of source route */
18026 				ip1dbg(("ip_rput_options: end of SR\n"));
18027 				break;
18028 			}
18029 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18030 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18031 			    ntohl(dst)));
18032 
18033 			/*
18034 			 * Check if our address is present more than
18035 			 * once as consecutive hops in source route.
18036 			 * XXX verify per-interface ip_forwarding
18037 			 * for source route?
18038 			 */
18039 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18040 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18041 
18042 			if (ire != NULL) {
18043 				ire_refrele(ire);
18044 				off += IP_ADDR_LEN;
18045 				goto redo_srr;
18046 			}
18047 
18048 			if (dst == htonl(INADDR_LOOPBACK)) {
18049 				ip1dbg(("ip_rput_options: loopback addr in "
18050 				    "source route!\n"));
18051 				goto bad_src_route;
18052 			}
18053 			/*
18054 			 * For strict: verify that dst is directly
18055 			 * reachable.
18056 			 */
18057 			if (optval == IPOPT_SSRR) {
18058 				ire = ire_ftable_lookup(dst, 0, 0,
18059 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18060 				    msg_getlabel(mp),
18061 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18062 				if (ire == NULL) {
18063 					ip1dbg(("ip_rput_options: SSRR not "
18064 					    "directly reachable: 0x%x\n",
18065 					    ntohl(dst)));
18066 					goto bad_src_route;
18067 				}
18068 				ire_refrele(ire);
18069 			}
18070 			/*
18071 			 * Defer update of the offset and the record route
18072 			 * until the packet is forwarded.
18073 			 */
18074 			break;
18075 		case IPOPT_RR:
18076 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18077 				ip1dbg((
18078 				    "ip_rput_options: bad option offset\n"));
18079 				code = (char *)&opt[IPOPT_OLEN] -
18080 				    (char *)ipha;
18081 				goto param_prob;
18082 			}
18083 			break;
18084 		case IPOPT_TS:
18085 			/*
18086 			 * Verify that length >= 5 and that there is either
18087 			 * room for another timestamp or that the overflow
18088 			 * counter is not maxed out.
18089 			 */
18090 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18091 			if (optlen < IPOPT_MINLEN_IT) {
18092 				goto param_prob;
18093 			}
18094 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18095 				ip1dbg((
18096 				    "ip_rput_options: bad option offset\n"));
18097 				code = (char *)&opt[IPOPT_OFFSET] -
18098 				    (char *)ipha;
18099 				goto param_prob;
18100 			}
18101 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18102 			case IPOPT_TS_TSONLY:
18103 				off = IPOPT_TS_TIMELEN;
18104 				break;
18105 			case IPOPT_TS_TSANDADDR:
18106 			case IPOPT_TS_PRESPEC:
18107 			case IPOPT_TS_PRESPEC_RFC791:
18108 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18109 				break;
18110 			default:
18111 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18112 				    (char *)ipha;
18113 				goto param_prob;
18114 			}
18115 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18116 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18117 				/*
18118 				 * No room and the overflow counter is 15
18119 				 * already.
18120 				 */
18121 				goto param_prob;
18122 			}
18123 			break;
18124 		}
18125 	}
18126 
18127 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18128 		*dstp = dst;
18129 		return (0);
18130 	}
18131 
18132 	ip1dbg(("ip_rput_options: error processing IP options."));
18133 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18134 
18135 param_prob:
18136 	q = WR(q);
18137 	if (q->q_next != NULL)
18138 		ill = q->q_ptr;
18139 	else
18140 		ill = NULL;
18141 
18142 	/* make sure we clear any indication of a hardware checksum */
18143 	DB_CKSUMFLAGS(mp) = 0;
18144 	/* Don't know whether this is for non-global or global/forwarding */
18145 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18146 	if (zoneid == ALL_ZONES)
18147 		freemsg(mp);
18148 	else
18149 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18150 	return (-1);
18151 
18152 bad_src_route:
18153 	q = WR(q);
18154 	if (q->q_next != NULL)
18155 		ill = q->q_ptr;
18156 	else
18157 		ill = NULL;
18158 
18159 	/* make sure we clear any indication of a hardware checksum */
18160 	DB_CKSUMFLAGS(mp) = 0;
18161 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18162 	if (zoneid == ALL_ZONES)
18163 		freemsg(mp);
18164 	else
18165 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18166 	return (-1);
18167 }
18168 
18169 /*
18170  * IP & ICMP info in >=14 msg's ...
18171  *  - ip fixed part (mib2_ip_t)
18172  *  - icmp fixed part (mib2_icmp_t)
18173  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18174  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18175  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18176  *  - ipRouteAttributeTable (ip 102)	labeled routes
18177  *  - ip multicast membership (ip_member_t)
18178  *  - ip multicast source filtering (ip_grpsrc_t)
18179  *  - igmp fixed part (struct igmpstat)
18180  *  - multicast routing stats (struct mrtstat)
18181  *  - multicast routing vifs (array of struct vifctl)
18182  *  - multicast routing routes (array of struct mfcctl)
18183  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18184  *					One per ill plus one generic
18185  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18186  *					One per ill plus one generic
18187  *  - ipv6RouteEntry			all IPv6 IREs
18188  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18189  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18190  *  - ipv6AddrEntry			all IPv6 ipifs
18191  *  - ipv6 multicast membership (ipv6_member_t)
18192  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18193  *
18194  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18195  *
18196  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18197  * already filled in by the caller.
18198  * Return value of 0 indicates that no messages were sent and caller
18199  * should free mpctl.
18200  */
18201 int
18202 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18203 {
18204 	ip_stack_t *ipst;
18205 	sctp_stack_t *sctps;
18206 
18207 	if (q->q_next != NULL) {
18208 		ipst = ILLQ_TO_IPST(q);
18209 	} else {
18210 		ipst = CONNQ_TO_IPST(q);
18211 	}
18212 	ASSERT(ipst != NULL);
18213 	sctps = ipst->ips_netstack->netstack_sctp;
18214 
18215 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18216 		return (0);
18217 	}
18218 
18219 	/*
18220 	 * For the purposes of the (broken) packet shell use
18221 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18222 	 * to make TCP and UDP appear first in the list of mib items.
18223 	 * TBD: We could expand this and use it in netstat so that
18224 	 * the kernel doesn't have to produce large tables (connections,
18225 	 * routes, etc) when netstat only wants the statistics or a particular
18226 	 * table.
18227 	 */
18228 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18229 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18230 			return (1);
18231 		}
18232 	}
18233 
18234 	if (level != MIB2_TCP) {
18235 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18236 			return (1);
18237 		}
18238 	}
18239 
18240 	if (level != MIB2_UDP) {
18241 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18242 			return (1);
18243 		}
18244 	}
18245 
18246 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18247 	    ipst)) == NULL) {
18248 		return (1);
18249 	}
18250 
18251 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18252 		return (1);
18253 	}
18254 
18255 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18256 		return (1);
18257 	}
18258 
18259 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18260 		return (1);
18261 	}
18262 
18263 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18264 		return (1);
18265 	}
18266 
18267 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18268 		return (1);
18269 	}
18270 
18271 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18272 		return (1);
18273 	}
18274 
18275 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18276 		return (1);
18277 	}
18278 
18279 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18280 		return (1);
18281 	}
18282 
18283 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18284 		return (1);
18285 	}
18286 
18287 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18288 		return (1);
18289 	}
18290 
18291 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18292 		return (1);
18293 	}
18294 
18295 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18296 		return (1);
18297 	}
18298 
18299 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18300 		return (1);
18301 	}
18302 
18303 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18304 	if (mpctl == NULL)
18305 		return (1);
18306 
18307 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18308 	if (mpctl == NULL)
18309 		return (1);
18310 
18311 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18312 		return (1);
18313 	}
18314 	freemsg(mpctl);
18315 	return (1);
18316 }
18317 
18318 /* Get global (legacy) IPv4 statistics */
18319 static mblk_t *
18320 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18321     ip_stack_t *ipst)
18322 {
18323 	mib2_ip_t		old_ip_mib;
18324 	struct opthdr		*optp;
18325 	mblk_t			*mp2ctl;
18326 
18327 	/*
18328 	 * make a copy of the original message
18329 	 */
18330 	mp2ctl = copymsg(mpctl);
18331 
18332 	/* fixed length IP structure... */
18333 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18334 	optp->level = MIB2_IP;
18335 	optp->name = 0;
18336 	SET_MIB(old_ip_mib.ipForwarding,
18337 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18338 	SET_MIB(old_ip_mib.ipDefaultTTL,
18339 	    (uint32_t)ipst->ips_ip_def_ttl);
18340 	SET_MIB(old_ip_mib.ipReasmTimeout,
18341 	    ipst->ips_ip_g_frag_timeout);
18342 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18343 	    sizeof (mib2_ipAddrEntry_t));
18344 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18345 	    sizeof (mib2_ipRouteEntry_t));
18346 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18347 	    sizeof (mib2_ipNetToMediaEntry_t));
18348 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18349 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18350 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18351 	    sizeof (mib2_ipAttributeEntry_t));
18352 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18353 
18354 	/*
18355 	 * Grab the statistics from the new IP MIB
18356 	 */
18357 	SET_MIB(old_ip_mib.ipInReceives,
18358 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18359 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18360 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18361 	SET_MIB(old_ip_mib.ipForwDatagrams,
18362 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18363 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18364 	    ipmib->ipIfStatsInUnknownProtos);
18365 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18366 	SET_MIB(old_ip_mib.ipInDelivers,
18367 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18368 	SET_MIB(old_ip_mib.ipOutRequests,
18369 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18370 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18371 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18372 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18373 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18374 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18375 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18376 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18377 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18378 
18379 	/* ipRoutingDiscards is not being used */
18380 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18381 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18382 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18383 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18384 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18385 	    ipmib->ipIfStatsReasmDuplicates);
18386 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18387 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18388 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18389 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18390 	SET_MIB(old_ip_mib.rawipInOverflows,
18391 	    ipmib->rawipIfStatsInOverflows);
18392 
18393 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18394 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18395 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18396 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18397 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18398 	    ipmib->ipIfStatsOutSwitchIPVersion);
18399 
18400 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18401 	    (int)sizeof (old_ip_mib))) {
18402 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18403 		    (uint_t)sizeof (old_ip_mib)));
18404 	}
18405 
18406 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18407 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18408 	    (int)optp->level, (int)optp->name, (int)optp->len));
18409 	qreply(q, mpctl);
18410 	return (mp2ctl);
18411 }
18412 
18413 /* Per interface IPv4 statistics */
18414 static mblk_t *
18415 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18416 {
18417 	struct opthdr		*optp;
18418 	mblk_t			*mp2ctl;
18419 	ill_t			*ill;
18420 	ill_walk_context_t	ctx;
18421 	mblk_t			*mp_tail = NULL;
18422 	mib2_ipIfStatsEntry_t	global_ip_mib;
18423 
18424 	/*
18425 	 * Make a copy of the original message
18426 	 */
18427 	mp2ctl = copymsg(mpctl);
18428 
18429 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18430 	optp->level = MIB2_IP;
18431 	optp->name = MIB2_IP_TRAFFIC_STATS;
18432 	/* Include "unknown interface" ip_mib */
18433 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18434 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18435 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18436 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18437 	    (ipst->ips_ip_g_forward ? 1 : 2));
18438 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18439 	    (uint32_t)ipst->ips_ip_def_ttl);
18440 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18441 	    sizeof (mib2_ipIfStatsEntry_t));
18442 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18443 	    sizeof (mib2_ipAddrEntry_t));
18444 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18445 	    sizeof (mib2_ipRouteEntry_t));
18446 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18447 	    sizeof (mib2_ipNetToMediaEntry_t));
18448 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18449 	    sizeof (ip_member_t));
18450 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18451 	    sizeof (ip_grpsrc_t));
18452 
18453 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18454 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18455 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18456 		    "failed to allocate %u bytes\n",
18457 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18458 	}
18459 
18460 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18461 
18462 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18463 	ill = ILL_START_WALK_V4(&ctx, ipst);
18464 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18465 		ill->ill_ip_mib->ipIfStatsIfIndex =
18466 		    ill->ill_phyint->phyint_ifindex;
18467 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18468 		    (ipst->ips_ip_g_forward ? 1 : 2));
18469 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18470 		    (uint32_t)ipst->ips_ip_def_ttl);
18471 
18472 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18473 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18474 		    (char *)ill->ill_ip_mib,
18475 		    (int)sizeof (*ill->ill_ip_mib))) {
18476 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18477 			    "failed to allocate %u bytes\n",
18478 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18479 		}
18480 	}
18481 	rw_exit(&ipst->ips_ill_g_lock);
18482 
18483 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18484 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18485 	    "level %d, name %d, len %d\n",
18486 	    (int)optp->level, (int)optp->name, (int)optp->len));
18487 	qreply(q, mpctl);
18488 
18489 	if (mp2ctl == NULL)
18490 		return (NULL);
18491 
18492 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18493 }
18494 
18495 /* Global IPv4 ICMP statistics */
18496 static mblk_t *
18497 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18498 {
18499 	struct opthdr		*optp;
18500 	mblk_t			*mp2ctl;
18501 
18502 	/*
18503 	 * Make a copy of the original message
18504 	 */
18505 	mp2ctl = copymsg(mpctl);
18506 
18507 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18508 	optp->level = MIB2_ICMP;
18509 	optp->name = 0;
18510 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18511 	    (int)sizeof (ipst->ips_icmp_mib))) {
18512 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18513 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18514 	}
18515 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18516 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18517 	    (int)optp->level, (int)optp->name, (int)optp->len));
18518 	qreply(q, mpctl);
18519 	return (mp2ctl);
18520 }
18521 
18522 /* Global IPv4 IGMP statistics */
18523 static mblk_t *
18524 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18525 {
18526 	struct opthdr		*optp;
18527 	mblk_t			*mp2ctl;
18528 
18529 	/*
18530 	 * make a copy of the original message
18531 	 */
18532 	mp2ctl = copymsg(mpctl);
18533 
18534 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18535 	optp->level = EXPER_IGMP;
18536 	optp->name = 0;
18537 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18538 	    (int)sizeof (ipst->ips_igmpstat))) {
18539 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18540 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18541 	}
18542 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18543 	ip3dbg(("ip_snmp_get_mib2_igmp: 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 /* Global IPv4 Multicast Routing statistics */
18550 static mblk_t *
18551 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18552 {
18553 	struct opthdr		*optp;
18554 	mblk_t			*mp2ctl;
18555 
18556 	/*
18557 	 * make a copy of the original message
18558 	 */
18559 	mp2ctl = copymsg(mpctl);
18560 
18561 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18562 	optp->level = EXPER_DVMRP;
18563 	optp->name = 0;
18564 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18565 		ip0dbg(("ip_mroute_stats: failed\n"));
18566 	}
18567 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18568 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18569 	    (int)optp->level, (int)optp->name, (int)optp->len));
18570 	qreply(q, mpctl);
18571 	return (mp2ctl);
18572 }
18573 
18574 /* IPv4 address information */
18575 static mblk_t *
18576 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18577 {
18578 	struct opthdr		*optp;
18579 	mblk_t			*mp2ctl;
18580 	mblk_t			*mp_tail = NULL;
18581 	ill_t			*ill;
18582 	ipif_t			*ipif;
18583 	uint_t			bitval;
18584 	mib2_ipAddrEntry_t	mae;
18585 	zoneid_t		zoneid;
18586 	ill_walk_context_t ctx;
18587 
18588 	/*
18589 	 * make a copy of the original message
18590 	 */
18591 	mp2ctl = copymsg(mpctl);
18592 
18593 	/* ipAddrEntryTable */
18594 
18595 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18596 	optp->level = MIB2_IP;
18597 	optp->name = MIB2_IP_ADDR;
18598 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18599 
18600 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18601 	ill = ILL_START_WALK_V4(&ctx, ipst);
18602 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18603 		for (ipif = ill->ill_ipif; ipif != NULL;
18604 		    ipif = ipif->ipif_next) {
18605 			if (ipif->ipif_zoneid != zoneid &&
18606 			    ipif->ipif_zoneid != ALL_ZONES)
18607 				continue;
18608 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18609 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18610 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18611 
18612 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18613 			    OCTET_LENGTH);
18614 			mae.ipAdEntIfIndex.o_length =
18615 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18616 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18617 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18618 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18619 			mae.ipAdEntInfo.ae_subnet_len =
18620 			    ip_mask_to_plen(ipif->ipif_net_mask);
18621 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18622 			for (bitval = 1;
18623 			    bitval &&
18624 			    !(bitval & ipif->ipif_brd_addr);
18625 			    bitval <<= 1)
18626 				noop;
18627 			mae.ipAdEntBcastAddr = bitval;
18628 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18629 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18630 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18631 			mae.ipAdEntInfo.ae_broadcast_addr =
18632 			    ipif->ipif_brd_addr;
18633 			mae.ipAdEntInfo.ae_pp_dst_addr =
18634 			    ipif->ipif_pp_dst_addr;
18635 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18636 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18637 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18638 
18639 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18640 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18641 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18642 				    "allocate %u bytes\n",
18643 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18644 			}
18645 		}
18646 	}
18647 	rw_exit(&ipst->ips_ill_g_lock);
18648 
18649 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18650 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18651 	    (int)optp->level, (int)optp->name, (int)optp->len));
18652 	qreply(q, mpctl);
18653 	return (mp2ctl);
18654 }
18655 
18656 /* IPv6 address information */
18657 static mblk_t *
18658 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18659 {
18660 	struct opthdr		*optp;
18661 	mblk_t			*mp2ctl;
18662 	mblk_t			*mp_tail = NULL;
18663 	ill_t			*ill;
18664 	ipif_t			*ipif;
18665 	mib2_ipv6AddrEntry_t	mae6;
18666 	zoneid_t		zoneid;
18667 	ill_walk_context_t	ctx;
18668 
18669 	/*
18670 	 * make a copy of the original message
18671 	 */
18672 	mp2ctl = copymsg(mpctl);
18673 
18674 	/* ipv6AddrEntryTable */
18675 
18676 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18677 	optp->level = MIB2_IP6;
18678 	optp->name = MIB2_IP6_ADDR;
18679 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18680 
18681 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18682 	ill = ILL_START_WALK_V6(&ctx, ipst);
18683 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18684 		for (ipif = ill->ill_ipif; ipif != NULL;
18685 		    ipif = ipif->ipif_next) {
18686 			if (ipif->ipif_zoneid != zoneid &&
18687 			    ipif->ipif_zoneid != ALL_ZONES)
18688 				continue;
18689 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18690 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18691 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18692 
18693 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18694 			    OCTET_LENGTH);
18695 			mae6.ipv6AddrIfIndex.o_length =
18696 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18697 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18698 			mae6.ipv6AddrPfxLength =
18699 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18700 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18701 			mae6.ipv6AddrInfo.ae_subnet_len =
18702 			    mae6.ipv6AddrPfxLength;
18703 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18704 
18705 			/* Type: stateless(1), stateful(2), unknown(3) */
18706 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18707 				mae6.ipv6AddrType = 1;
18708 			else
18709 				mae6.ipv6AddrType = 2;
18710 			/* Anycast: true(1), false(2) */
18711 			if (ipif->ipif_flags & IPIF_ANYCAST)
18712 				mae6.ipv6AddrAnycastFlag = 1;
18713 			else
18714 				mae6.ipv6AddrAnycastFlag = 2;
18715 
18716 			/*
18717 			 * Address status: preferred(1), deprecated(2),
18718 			 * invalid(3), inaccessible(4), unknown(5)
18719 			 */
18720 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18721 				mae6.ipv6AddrStatus = 3;
18722 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18723 				mae6.ipv6AddrStatus = 2;
18724 			else
18725 				mae6.ipv6AddrStatus = 1;
18726 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18727 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18728 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18729 			    ipif->ipif_v6pp_dst_addr;
18730 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18731 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18732 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18733 			mae6.ipv6AddrIdentifier = ill->ill_token;
18734 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18735 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18736 			mae6.ipv6AddrRetransmitTime =
18737 			    ill->ill_reachable_retrans_time;
18738 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18739 			    (char *)&mae6,
18740 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18741 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18742 				    "allocate %u bytes\n",
18743 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18744 			}
18745 		}
18746 	}
18747 	rw_exit(&ipst->ips_ill_g_lock);
18748 
18749 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18750 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18751 	    (int)optp->level, (int)optp->name, (int)optp->len));
18752 	qreply(q, mpctl);
18753 	return (mp2ctl);
18754 }
18755 
18756 /* IPv4 multicast group membership. */
18757 static mblk_t *
18758 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18759 {
18760 	struct opthdr		*optp;
18761 	mblk_t			*mp2ctl;
18762 	ill_t			*ill;
18763 	ipif_t			*ipif;
18764 	ilm_t			*ilm;
18765 	ip_member_t		ipm;
18766 	mblk_t			*mp_tail = NULL;
18767 	ill_walk_context_t	ctx;
18768 	zoneid_t		zoneid;
18769 	ilm_walker_t		ilw;
18770 
18771 	/*
18772 	 * make a copy of the original message
18773 	 */
18774 	mp2ctl = copymsg(mpctl);
18775 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18776 
18777 	/* ipGroupMember table */
18778 	optp = (struct opthdr *)&mpctl->b_rptr[
18779 	    sizeof (struct T_optmgmt_ack)];
18780 	optp->level = MIB2_IP;
18781 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18782 
18783 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18784 	ill = ILL_START_WALK_V4(&ctx, ipst);
18785 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18786 		if (IS_UNDER_IPMP(ill))
18787 			continue;
18788 
18789 		ilm = ilm_walker_start(&ilw, ill);
18790 		for (ipif = ill->ill_ipif; ipif != NULL;
18791 		    ipif = ipif->ipif_next) {
18792 			if (ipif->ipif_zoneid != zoneid &&
18793 			    ipif->ipif_zoneid != ALL_ZONES)
18794 				continue;	/* not this zone */
18795 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18796 			    OCTET_LENGTH);
18797 			ipm.ipGroupMemberIfIndex.o_length =
18798 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18799 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18800 				ASSERT(ilm->ilm_ipif != NULL);
18801 				ASSERT(ilm->ilm_ill == NULL);
18802 				if (ilm->ilm_ipif != ipif)
18803 					continue;
18804 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18805 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18806 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18807 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18808 				    (char *)&ipm, (int)sizeof (ipm))) {
18809 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18810 					    "failed to allocate %u bytes\n",
18811 					    (uint_t)sizeof (ipm)));
18812 				}
18813 			}
18814 		}
18815 		ilm_walker_finish(&ilw);
18816 	}
18817 	rw_exit(&ipst->ips_ill_g_lock);
18818 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18819 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18820 	    (int)optp->level, (int)optp->name, (int)optp->len));
18821 	qreply(q, mpctl);
18822 	return (mp2ctl);
18823 }
18824 
18825 /* IPv6 multicast group membership. */
18826 static mblk_t *
18827 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18828 {
18829 	struct opthdr		*optp;
18830 	mblk_t			*mp2ctl;
18831 	ill_t			*ill;
18832 	ilm_t			*ilm;
18833 	ipv6_member_t		ipm6;
18834 	mblk_t			*mp_tail = NULL;
18835 	ill_walk_context_t	ctx;
18836 	zoneid_t		zoneid;
18837 	ilm_walker_t		ilw;
18838 
18839 	/*
18840 	 * make a copy of the original message
18841 	 */
18842 	mp2ctl = copymsg(mpctl);
18843 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18844 
18845 	/* ip6GroupMember table */
18846 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18847 	optp->level = MIB2_IP6;
18848 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18849 
18850 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18851 	ill = ILL_START_WALK_V6(&ctx, ipst);
18852 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18853 		if (IS_UNDER_IPMP(ill))
18854 			continue;
18855 
18856 		ilm = ilm_walker_start(&ilw, ill);
18857 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18858 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18859 			ASSERT(ilm->ilm_ipif == NULL);
18860 			ASSERT(ilm->ilm_ill != NULL);
18861 			if (ilm->ilm_zoneid != zoneid)
18862 				continue;	/* not this zone */
18863 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18864 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18865 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18866 			if (!snmp_append_data2(mpctl->b_cont,
18867 			    &mp_tail,
18868 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18869 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18870 				    "failed to allocate %u bytes\n",
18871 				    (uint_t)sizeof (ipm6)));
18872 			}
18873 		}
18874 		ilm_walker_finish(&ilw);
18875 	}
18876 	rw_exit(&ipst->ips_ill_g_lock);
18877 
18878 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18879 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18880 	    (int)optp->level, (int)optp->name, (int)optp->len));
18881 	qreply(q, mpctl);
18882 	return (mp2ctl);
18883 }
18884 
18885 /* IP multicast filtered sources */
18886 static mblk_t *
18887 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18888 {
18889 	struct opthdr		*optp;
18890 	mblk_t			*mp2ctl;
18891 	ill_t			*ill;
18892 	ipif_t			*ipif;
18893 	ilm_t			*ilm;
18894 	ip_grpsrc_t		ips;
18895 	mblk_t			*mp_tail = NULL;
18896 	ill_walk_context_t	ctx;
18897 	zoneid_t		zoneid;
18898 	int			i;
18899 	slist_t			*sl;
18900 	ilm_walker_t		ilw;
18901 
18902 	/*
18903 	 * make a copy of the original message
18904 	 */
18905 	mp2ctl = copymsg(mpctl);
18906 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18907 
18908 	/* ipGroupSource table */
18909 	optp = (struct opthdr *)&mpctl->b_rptr[
18910 	    sizeof (struct T_optmgmt_ack)];
18911 	optp->level = MIB2_IP;
18912 	optp->name = EXPER_IP_GROUP_SOURCES;
18913 
18914 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18915 	ill = ILL_START_WALK_V4(&ctx, ipst);
18916 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18917 		if (IS_UNDER_IPMP(ill))
18918 			continue;
18919 
18920 		ilm = ilm_walker_start(&ilw, ill);
18921 		for (ipif = ill->ill_ipif; ipif != NULL;
18922 		    ipif = ipif->ipif_next) {
18923 			if (ipif->ipif_zoneid != zoneid)
18924 				continue;	/* not this zone */
18925 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18926 			    OCTET_LENGTH);
18927 			ips.ipGroupSourceIfIndex.o_length =
18928 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18929 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18930 				ASSERT(ilm->ilm_ipif != NULL);
18931 				ASSERT(ilm->ilm_ill == NULL);
18932 				sl = ilm->ilm_filter;
18933 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18934 					continue;
18935 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18936 				for (i = 0; i < sl->sl_numsrc; i++) {
18937 					if (!IN6_IS_ADDR_V4MAPPED(
18938 					    &sl->sl_addr[i]))
18939 						continue;
18940 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18941 					    ips.ipGroupSourceAddress);
18942 					if (snmp_append_data2(mpctl->b_cont,
18943 					    &mp_tail, (char *)&ips,
18944 					    (int)sizeof (ips)) == 0) {
18945 						ip1dbg(("ip_snmp_get_mib2_"
18946 						    "ip_group_src: failed to "
18947 						    "allocate %u bytes\n",
18948 						    (uint_t)sizeof (ips)));
18949 					}
18950 				}
18951 			}
18952 		}
18953 		ilm_walker_finish(&ilw);
18954 	}
18955 	rw_exit(&ipst->ips_ill_g_lock);
18956 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18957 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18958 	    (int)optp->level, (int)optp->name, (int)optp->len));
18959 	qreply(q, mpctl);
18960 	return (mp2ctl);
18961 }
18962 
18963 /* IPv6 multicast filtered sources. */
18964 static mblk_t *
18965 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18966 {
18967 	struct opthdr		*optp;
18968 	mblk_t			*mp2ctl;
18969 	ill_t			*ill;
18970 	ilm_t			*ilm;
18971 	ipv6_grpsrc_t		ips6;
18972 	mblk_t			*mp_tail = NULL;
18973 	ill_walk_context_t	ctx;
18974 	zoneid_t		zoneid;
18975 	int			i;
18976 	slist_t			*sl;
18977 	ilm_walker_t		ilw;
18978 
18979 	/*
18980 	 * make a copy of the original message
18981 	 */
18982 	mp2ctl = copymsg(mpctl);
18983 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18984 
18985 	/* ip6GroupMember table */
18986 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18987 	optp->level = MIB2_IP6;
18988 	optp->name = EXPER_IP6_GROUP_SOURCES;
18989 
18990 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18991 	ill = ILL_START_WALK_V6(&ctx, ipst);
18992 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18993 		if (IS_UNDER_IPMP(ill))
18994 			continue;
18995 
18996 		ilm = ilm_walker_start(&ilw, ill);
18997 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18998 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18999 			ASSERT(ilm->ilm_ipif == NULL);
19000 			ASSERT(ilm->ilm_ill != NULL);
19001 			sl = ilm->ilm_filter;
19002 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19003 				continue;
19004 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19005 			for (i = 0; i < sl->sl_numsrc; i++) {
19006 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19007 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19008 				    (char *)&ips6, (int)sizeof (ips6))) {
19009 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19010 					    "group_src: failed to allocate "
19011 					    "%u bytes\n",
19012 					    (uint_t)sizeof (ips6)));
19013 				}
19014 			}
19015 		}
19016 		ilm_walker_finish(&ilw);
19017 	}
19018 	rw_exit(&ipst->ips_ill_g_lock);
19019 
19020 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19021 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19022 	    (int)optp->level, (int)optp->name, (int)optp->len));
19023 	qreply(q, mpctl);
19024 	return (mp2ctl);
19025 }
19026 
19027 /* Multicast routing virtual interface table. */
19028 static mblk_t *
19029 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19030 {
19031 	struct opthdr		*optp;
19032 	mblk_t			*mp2ctl;
19033 
19034 	/*
19035 	 * make a copy of the original message
19036 	 */
19037 	mp2ctl = copymsg(mpctl);
19038 
19039 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19040 	optp->level = EXPER_DVMRP;
19041 	optp->name = EXPER_DVMRP_VIF;
19042 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19043 		ip0dbg(("ip_mroute_vif: failed\n"));
19044 	}
19045 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19046 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19047 	    (int)optp->level, (int)optp->name, (int)optp->len));
19048 	qreply(q, mpctl);
19049 	return (mp2ctl);
19050 }
19051 
19052 /* Multicast routing table. */
19053 static mblk_t *
19054 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19055 {
19056 	struct opthdr		*optp;
19057 	mblk_t			*mp2ctl;
19058 
19059 	/*
19060 	 * make a copy of the original message
19061 	 */
19062 	mp2ctl = copymsg(mpctl);
19063 
19064 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19065 	optp->level = EXPER_DVMRP;
19066 	optp->name = EXPER_DVMRP_MRT;
19067 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19068 		ip0dbg(("ip_mroute_mrt: failed\n"));
19069 	}
19070 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19071 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19072 	    (int)optp->level, (int)optp->name, (int)optp->len));
19073 	qreply(q, mpctl);
19074 	return (mp2ctl);
19075 }
19076 
19077 /*
19078  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19079  * in one IRE walk.
19080  */
19081 static mblk_t *
19082 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19083     ip_stack_t *ipst)
19084 {
19085 	struct opthdr	*optp;
19086 	mblk_t		*mp2ctl;	/* Returned */
19087 	mblk_t		*mp3ctl;	/* nettomedia */
19088 	mblk_t		*mp4ctl;	/* routeattrs */
19089 	iproutedata_t	ird;
19090 	zoneid_t	zoneid;
19091 
19092 	/*
19093 	 * make copies of the original message
19094 	 *	- mp2ctl is returned unchanged to the caller for his use
19095 	 *	- mpctl is sent upstream as ipRouteEntryTable
19096 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19097 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19098 	 */
19099 	mp2ctl = copymsg(mpctl);
19100 	mp3ctl = copymsg(mpctl);
19101 	mp4ctl = copymsg(mpctl);
19102 	if (mp3ctl == NULL || mp4ctl == NULL) {
19103 		freemsg(mp4ctl);
19104 		freemsg(mp3ctl);
19105 		freemsg(mp2ctl);
19106 		freemsg(mpctl);
19107 		return (NULL);
19108 	}
19109 
19110 	bzero(&ird, sizeof (ird));
19111 
19112 	ird.ird_route.lp_head = mpctl->b_cont;
19113 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19114 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19115 	/*
19116 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19117 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19118 	 * intended a temporary solution until a proper MIB API is provided
19119 	 * that provides complete filtering/caller-opt-in.
19120 	 */
19121 	if (level == EXPER_IP_AND_TESTHIDDEN)
19122 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19123 
19124 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19125 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19126 
19127 	/* ipRouteEntryTable in mpctl */
19128 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19129 	optp->level = MIB2_IP;
19130 	optp->name = MIB2_IP_ROUTE;
19131 	optp->len = msgdsize(ird.ird_route.lp_head);
19132 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19133 	    (int)optp->level, (int)optp->name, (int)optp->len));
19134 	qreply(q, mpctl);
19135 
19136 	/* ipNetToMediaEntryTable in mp3ctl */
19137 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19138 	optp->level = MIB2_IP;
19139 	optp->name = MIB2_IP_MEDIA;
19140 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19141 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19142 	    (int)optp->level, (int)optp->name, (int)optp->len));
19143 	qreply(q, mp3ctl);
19144 
19145 	/* ipRouteAttributeTable in mp4ctl */
19146 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19147 	optp->level = MIB2_IP;
19148 	optp->name = EXPER_IP_RTATTR;
19149 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19150 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19151 	    (int)optp->level, (int)optp->name, (int)optp->len));
19152 	if (optp->len == 0)
19153 		freemsg(mp4ctl);
19154 	else
19155 		qreply(q, mp4ctl);
19156 
19157 	return (mp2ctl);
19158 }
19159 
19160 /*
19161  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19162  * ipv6NetToMediaEntryTable in an NDP walk.
19163  */
19164 static mblk_t *
19165 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19166     ip_stack_t *ipst)
19167 {
19168 	struct opthdr	*optp;
19169 	mblk_t		*mp2ctl;	/* Returned */
19170 	mblk_t		*mp3ctl;	/* nettomedia */
19171 	mblk_t		*mp4ctl;	/* routeattrs */
19172 	iproutedata_t	ird;
19173 	zoneid_t	zoneid;
19174 
19175 	/*
19176 	 * make copies of the original message
19177 	 *	- mp2ctl is returned unchanged to the caller for his use
19178 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19179 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19180 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19181 	 */
19182 	mp2ctl = copymsg(mpctl);
19183 	mp3ctl = copymsg(mpctl);
19184 	mp4ctl = copymsg(mpctl);
19185 	if (mp3ctl == NULL || mp4ctl == NULL) {
19186 		freemsg(mp4ctl);
19187 		freemsg(mp3ctl);
19188 		freemsg(mp2ctl);
19189 		freemsg(mpctl);
19190 		return (NULL);
19191 	}
19192 
19193 	bzero(&ird, sizeof (ird));
19194 
19195 	ird.ird_route.lp_head = mpctl->b_cont;
19196 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19197 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19198 	/*
19199 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19200 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19201 	 * intended a temporary solution until a proper MIB API is provided
19202 	 * that provides complete filtering/caller-opt-in.
19203 	 */
19204 	if (level == EXPER_IP_AND_TESTHIDDEN)
19205 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19206 
19207 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19208 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19209 
19210 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19211 	optp->level = MIB2_IP6;
19212 	optp->name = MIB2_IP6_ROUTE;
19213 	optp->len = msgdsize(ird.ird_route.lp_head);
19214 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19215 	    (int)optp->level, (int)optp->name, (int)optp->len));
19216 	qreply(q, mpctl);
19217 
19218 	/* ipv6NetToMediaEntryTable in mp3ctl */
19219 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19220 
19221 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19222 	optp->level = MIB2_IP6;
19223 	optp->name = MIB2_IP6_MEDIA;
19224 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19225 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19226 	    (int)optp->level, (int)optp->name, (int)optp->len));
19227 	qreply(q, mp3ctl);
19228 
19229 	/* ipv6RouteAttributeTable in mp4ctl */
19230 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19231 	optp->level = MIB2_IP6;
19232 	optp->name = EXPER_IP_RTATTR;
19233 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19234 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19235 	    (int)optp->level, (int)optp->name, (int)optp->len));
19236 	if (optp->len == 0)
19237 		freemsg(mp4ctl);
19238 	else
19239 		qreply(q, mp4ctl);
19240 
19241 	return (mp2ctl);
19242 }
19243 
19244 /*
19245  * IPv6 mib: One per ill
19246  */
19247 static mblk_t *
19248 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19249 {
19250 	struct opthdr		*optp;
19251 	mblk_t			*mp2ctl;
19252 	ill_t			*ill;
19253 	ill_walk_context_t	ctx;
19254 	mblk_t			*mp_tail = NULL;
19255 
19256 	/*
19257 	 * Make a copy of the original message
19258 	 */
19259 	mp2ctl = copymsg(mpctl);
19260 
19261 	/* fixed length IPv6 structure ... */
19262 
19263 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19264 	optp->level = MIB2_IP6;
19265 	optp->name = 0;
19266 	/* Include "unknown interface" ip6_mib */
19267 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19268 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19269 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19270 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19271 	    ipst->ips_ipv6_forward ? 1 : 2);
19272 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19273 	    ipst->ips_ipv6_def_hops);
19274 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19275 	    sizeof (mib2_ipIfStatsEntry_t));
19276 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19277 	    sizeof (mib2_ipv6AddrEntry_t));
19278 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19279 	    sizeof (mib2_ipv6RouteEntry_t));
19280 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19281 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19282 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19283 	    sizeof (ipv6_member_t));
19284 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19285 	    sizeof (ipv6_grpsrc_t));
19286 
19287 	/*
19288 	 * Synchronize 64- and 32-bit counters
19289 	 */
19290 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19291 	    ipIfStatsHCInReceives);
19292 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19293 	    ipIfStatsHCInDelivers);
19294 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19295 	    ipIfStatsHCOutRequests);
19296 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19297 	    ipIfStatsHCOutForwDatagrams);
19298 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19299 	    ipIfStatsHCOutMcastPkts);
19300 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19301 	    ipIfStatsHCInMcastPkts);
19302 
19303 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19304 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19305 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19306 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19307 	}
19308 
19309 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19310 	ill = ILL_START_WALK_V6(&ctx, ipst);
19311 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19312 		ill->ill_ip_mib->ipIfStatsIfIndex =
19313 		    ill->ill_phyint->phyint_ifindex;
19314 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19315 		    ipst->ips_ipv6_forward ? 1 : 2);
19316 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19317 		    ill->ill_max_hops);
19318 
19319 		/*
19320 		 * Synchronize 64- and 32-bit counters
19321 		 */
19322 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19323 		    ipIfStatsHCInReceives);
19324 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19325 		    ipIfStatsHCInDelivers);
19326 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19327 		    ipIfStatsHCOutRequests);
19328 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19329 		    ipIfStatsHCOutForwDatagrams);
19330 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19331 		    ipIfStatsHCOutMcastPkts);
19332 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19333 		    ipIfStatsHCInMcastPkts);
19334 
19335 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19336 		    (char *)ill->ill_ip_mib,
19337 		    (int)sizeof (*ill->ill_ip_mib))) {
19338 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19339 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19340 		}
19341 	}
19342 	rw_exit(&ipst->ips_ill_g_lock);
19343 
19344 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19345 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19346 	    (int)optp->level, (int)optp->name, (int)optp->len));
19347 	qreply(q, mpctl);
19348 	return (mp2ctl);
19349 }
19350 
19351 /*
19352  * ICMPv6 mib: One per ill
19353  */
19354 static mblk_t *
19355 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19356 {
19357 	struct opthdr		*optp;
19358 	mblk_t			*mp2ctl;
19359 	ill_t			*ill;
19360 	ill_walk_context_t	ctx;
19361 	mblk_t			*mp_tail = NULL;
19362 	/*
19363 	 * Make a copy of the original message
19364 	 */
19365 	mp2ctl = copymsg(mpctl);
19366 
19367 	/* fixed length ICMPv6 structure ... */
19368 
19369 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19370 	optp->level = MIB2_ICMP6;
19371 	optp->name = 0;
19372 	/* Include "unknown interface" icmp6_mib */
19373 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19374 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19375 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19376 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19377 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19378 	    (char *)&ipst->ips_icmp6_mib,
19379 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19380 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19381 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19382 	}
19383 
19384 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19385 	ill = ILL_START_WALK_V6(&ctx, ipst);
19386 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19387 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19388 		    ill->ill_phyint->phyint_ifindex;
19389 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19390 		    (char *)ill->ill_icmp6_mib,
19391 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19392 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19393 			    "%u bytes\n",
19394 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19395 		}
19396 	}
19397 	rw_exit(&ipst->ips_ill_g_lock);
19398 
19399 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19400 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19401 	    (int)optp->level, (int)optp->name, (int)optp->len));
19402 	qreply(q, mpctl);
19403 	return (mp2ctl);
19404 }
19405 
19406 /*
19407  * ire_walk routine to create both ipRouteEntryTable and
19408  * ipRouteAttributeTable in one IRE walk
19409  */
19410 static void
19411 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19412 {
19413 	ill_t				*ill;
19414 	ipif_t				*ipif;
19415 	mib2_ipRouteEntry_t		*re;
19416 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19417 	ipaddr_t			gw_addr;
19418 	tsol_ire_gw_secattr_t		*attrp;
19419 	tsol_gc_t			*gc = NULL;
19420 	tsol_gcgrp_t			*gcgrp = NULL;
19421 	uint_t				sacnt = 0;
19422 	int				i;
19423 
19424 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19425 
19426 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19427 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19428 		return;
19429 	}
19430 
19431 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19432 		return;
19433 
19434 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19435 		mutex_enter(&attrp->igsa_lock);
19436 		if ((gc = attrp->igsa_gc) != NULL) {
19437 			gcgrp = gc->gc_grp;
19438 			ASSERT(gcgrp != NULL);
19439 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19440 			sacnt = 1;
19441 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19442 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19443 			gc = gcgrp->gcgrp_head;
19444 			sacnt = gcgrp->gcgrp_count;
19445 		}
19446 		mutex_exit(&attrp->igsa_lock);
19447 
19448 		/* do nothing if there's no gc to report */
19449 		if (gc == NULL) {
19450 			ASSERT(sacnt == 0);
19451 			if (gcgrp != NULL) {
19452 				/* we might as well drop the lock now */
19453 				rw_exit(&gcgrp->gcgrp_rwlock);
19454 				gcgrp = NULL;
19455 			}
19456 			attrp = NULL;
19457 		}
19458 
19459 		ASSERT(gc == NULL || (gcgrp != NULL &&
19460 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19461 	}
19462 	ASSERT(sacnt == 0 || gc != NULL);
19463 
19464 	if (sacnt != 0 &&
19465 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19466 		kmem_free(re, sizeof (*re));
19467 		rw_exit(&gcgrp->gcgrp_rwlock);
19468 		return;
19469 	}
19470 
19471 	/*
19472 	 * Return all IRE types for route table... let caller pick and choose
19473 	 */
19474 	re->ipRouteDest = ire->ire_addr;
19475 	ipif = ire->ire_ipif;
19476 	re->ipRouteIfIndex.o_length = 0;
19477 	if (ire->ire_type == IRE_CACHE) {
19478 		ill = (ill_t *)ire->ire_stq->q_ptr;
19479 		re->ipRouteIfIndex.o_length =
19480 		    ill->ill_name_length == 0 ? 0 :
19481 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19482 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19483 		    re->ipRouteIfIndex.o_length);
19484 	} else if (ipif != NULL) {
19485 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19486 		re->ipRouteIfIndex.o_length =
19487 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19488 	}
19489 	re->ipRouteMetric1 = -1;
19490 	re->ipRouteMetric2 = -1;
19491 	re->ipRouteMetric3 = -1;
19492 	re->ipRouteMetric4 = -1;
19493 
19494 	gw_addr = ire->ire_gateway_addr;
19495 
19496 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19497 		re->ipRouteNextHop = ire->ire_src_addr;
19498 	else
19499 		re->ipRouteNextHop = gw_addr;
19500 	/* indirect(4), direct(3), or invalid(2) */
19501 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19502 		re->ipRouteType = 2;
19503 	else
19504 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19505 	re->ipRouteProto = -1;
19506 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19507 	re->ipRouteMask = ire->ire_mask;
19508 	re->ipRouteMetric5 = -1;
19509 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19510 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19511 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19512 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19513 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19514 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19515 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19516 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19517 
19518 	if (ire->ire_flags & RTF_DYNAMIC) {
19519 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19520 	} else {
19521 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19522 	}
19523 
19524 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19525 	    (char *)re, (int)sizeof (*re))) {
19526 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19527 		    (uint_t)sizeof (*re)));
19528 	}
19529 
19530 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19531 		iaeptr->iae_routeidx = ird->ird_idx;
19532 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19533 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19534 	}
19535 
19536 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19537 	    (char *)iae, sacnt * sizeof (*iae))) {
19538 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19539 		    (unsigned)(sacnt * sizeof (*iae))));
19540 	}
19541 
19542 	/* bump route index for next pass */
19543 	ird->ird_idx++;
19544 
19545 	kmem_free(re, sizeof (*re));
19546 	if (sacnt != 0)
19547 		kmem_free(iae, sacnt * sizeof (*iae));
19548 
19549 	if (gcgrp != NULL)
19550 		rw_exit(&gcgrp->gcgrp_rwlock);
19551 }
19552 
19553 /*
19554  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19555  */
19556 static void
19557 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19558 {
19559 	ill_t				*ill;
19560 	ipif_t				*ipif;
19561 	mib2_ipv6RouteEntry_t		*re;
19562 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19563 	in6_addr_t			gw_addr_v6;
19564 	tsol_ire_gw_secattr_t		*attrp;
19565 	tsol_gc_t			*gc = NULL;
19566 	tsol_gcgrp_t			*gcgrp = NULL;
19567 	uint_t				sacnt = 0;
19568 	int				i;
19569 
19570 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19571 
19572 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19573 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19574 		return;
19575 	}
19576 
19577 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19578 		return;
19579 
19580 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19581 		mutex_enter(&attrp->igsa_lock);
19582 		if ((gc = attrp->igsa_gc) != NULL) {
19583 			gcgrp = gc->gc_grp;
19584 			ASSERT(gcgrp != NULL);
19585 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19586 			sacnt = 1;
19587 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19588 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19589 			gc = gcgrp->gcgrp_head;
19590 			sacnt = gcgrp->gcgrp_count;
19591 		}
19592 		mutex_exit(&attrp->igsa_lock);
19593 
19594 		/* do nothing if there's no gc to report */
19595 		if (gc == NULL) {
19596 			ASSERT(sacnt == 0);
19597 			if (gcgrp != NULL) {
19598 				/* we might as well drop the lock now */
19599 				rw_exit(&gcgrp->gcgrp_rwlock);
19600 				gcgrp = NULL;
19601 			}
19602 			attrp = NULL;
19603 		}
19604 
19605 		ASSERT(gc == NULL || (gcgrp != NULL &&
19606 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19607 	}
19608 	ASSERT(sacnt == 0 || gc != NULL);
19609 
19610 	if (sacnt != 0 &&
19611 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19612 		kmem_free(re, sizeof (*re));
19613 		rw_exit(&gcgrp->gcgrp_rwlock);
19614 		return;
19615 	}
19616 
19617 	/*
19618 	 * Return all IRE types for route table... let caller pick and choose
19619 	 */
19620 	re->ipv6RouteDest = ire->ire_addr_v6;
19621 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19622 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19623 	re->ipv6RouteIfIndex.o_length = 0;
19624 	ipif = ire->ire_ipif;
19625 	if (ire->ire_type == IRE_CACHE) {
19626 		ill = (ill_t *)ire->ire_stq->q_ptr;
19627 		re->ipv6RouteIfIndex.o_length =
19628 		    ill->ill_name_length == 0 ? 0 :
19629 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19630 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19631 		    re->ipv6RouteIfIndex.o_length);
19632 	} else if (ipif != NULL) {
19633 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19634 		re->ipv6RouteIfIndex.o_length =
19635 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19636 	}
19637 
19638 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19639 
19640 	mutex_enter(&ire->ire_lock);
19641 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19642 	mutex_exit(&ire->ire_lock);
19643 
19644 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19645 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19646 	else
19647 		re->ipv6RouteNextHop = gw_addr_v6;
19648 
19649 	/* remote(4), local(3), or discard(2) */
19650 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19651 		re->ipv6RouteType = 2;
19652 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19653 		re->ipv6RouteType = 3;
19654 	else
19655 		re->ipv6RouteType = 4;
19656 
19657 	re->ipv6RouteProtocol	= -1;
19658 	re->ipv6RoutePolicy	= 0;
19659 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19660 	re->ipv6RouteNextHopRDI	= 0;
19661 	re->ipv6RouteWeight	= 0;
19662 	re->ipv6RouteMetric	= 0;
19663 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19664 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19665 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19666 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19667 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19668 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19669 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19670 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19671 
19672 	if (ire->ire_flags & RTF_DYNAMIC) {
19673 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19674 	} else {
19675 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19676 	}
19677 
19678 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19679 	    (char *)re, (int)sizeof (*re))) {
19680 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19681 		    (uint_t)sizeof (*re)));
19682 	}
19683 
19684 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19685 		iaeptr->iae_routeidx = ird->ird_idx;
19686 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19687 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19688 	}
19689 
19690 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19691 	    (char *)iae, sacnt * sizeof (*iae))) {
19692 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19693 		    (unsigned)(sacnt * sizeof (*iae))));
19694 	}
19695 
19696 	/* bump route index for next pass */
19697 	ird->ird_idx++;
19698 
19699 	kmem_free(re, sizeof (*re));
19700 	if (sacnt != 0)
19701 		kmem_free(iae, sacnt * sizeof (*iae));
19702 
19703 	if (gcgrp != NULL)
19704 		rw_exit(&gcgrp->gcgrp_rwlock);
19705 }
19706 
19707 /*
19708  * ndp_walk routine to create ipv6NetToMediaEntryTable
19709  */
19710 static int
19711 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19712 {
19713 	ill_t				*ill;
19714 	mib2_ipv6NetToMediaEntry_t	ntme;
19715 	dl_unitdata_req_t		*dl;
19716 
19717 	ill = nce->nce_ill;
19718 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19719 		return (0);
19720 
19721 	/*
19722 	 * Neighbor cache entry attached to IRE with on-link
19723 	 * destination.
19724 	 */
19725 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19726 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19727 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19728 	    (nce->nce_res_mp != NULL)) {
19729 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19730 		ntme.ipv6NetToMediaPhysAddress.o_length =
19731 		    dl->dl_dest_addr_length;
19732 	} else {
19733 		ntme.ipv6NetToMediaPhysAddress.o_length =
19734 		    ill->ill_phys_addr_length;
19735 	}
19736 	if (nce->nce_res_mp != NULL) {
19737 		bcopy((char *)nce->nce_res_mp->b_rptr +
19738 		    NCE_LL_ADDR_OFFSET(ill),
19739 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19740 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19741 	} else {
19742 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19743 		    ill->ill_phys_addr_length);
19744 	}
19745 	/*
19746 	 * Note: Returns ND_* states. Should be:
19747 	 * reachable(1), stale(2), delay(3), probe(4),
19748 	 * invalid(5), unknown(6)
19749 	 */
19750 	ntme.ipv6NetToMediaState = nce->nce_state;
19751 	ntme.ipv6NetToMediaLastUpdated = 0;
19752 
19753 	/* other(1), dynamic(2), static(3), local(4) */
19754 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19755 		ntme.ipv6NetToMediaType = 4;
19756 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19757 		ntme.ipv6NetToMediaType = 1;
19758 	} else {
19759 		ntme.ipv6NetToMediaType = 2;
19760 	}
19761 
19762 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19763 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19764 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19765 		    (uint_t)sizeof (ntme)));
19766 	}
19767 	return (0);
19768 }
19769 
19770 /*
19771  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19772  */
19773 /* ARGSUSED */
19774 int
19775 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19776 {
19777 	switch (level) {
19778 	case MIB2_IP:
19779 	case MIB2_ICMP:
19780 		switch (name) {
19781 		default:
19782 			break;
19783 		}
19784 		return (1);
19785 	default:
19786 		return (1);
19787 	}
19788 }
19789 
19790 /*
19791  * When there exists both a 64- and 32-bit counter of a particular type
19792  * (i.e., InReceives), only the 64-bit counters are added.
19793  */
19794 void
19795 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19796 {
19797 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19798 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19799 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19800 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19801 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19802 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19803 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19804 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19805 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19806 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19807 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19808 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19809 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19810 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19811 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19812 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19813 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19814 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19815 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19816 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19817 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19818 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19819 	    o2->ipIfStatsInWrongIPVersion);
19820 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19821 	    o2->ipIfStatsInWrongIPVersion);
19822 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19823 	    o2->ipIfStatsOutSwitchIPVersion);
19824 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19825 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19826 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19827 	    o2->ipIfStatsHCInForwDatagrams);
19828 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19829 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19830 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19831 	    o2->ipIfStatsHCOutForwDatagrams);
19832 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19833 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19834 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19835 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19836 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19837 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19838 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19839 	    o2->ipIfStatsHCOutMcastOctets);
19840 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19841 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19842 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19843 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19844 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19845 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19846 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19847 }
19848 
19849 void
19850 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19851 {
19852 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19853 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19854 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19855 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19856 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19857 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19859 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19861 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19862 	    o2->ipv6IfIcmpInRouterSolicits);
19863 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19864 	    o2->ipv6IfIcmpInRouterAdvertisements);
19865 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19866 	    o2->ipv6IfIcmpInNeighborSolicits);
19867 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19868 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19869 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19870 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19871 	    o2->ipv6IfIcmpInGroupMembQueries);
19872 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19873 	    o2->ipv6IfIcmpInGroupMembResponses);
19874 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19875 	    o2->ipv6IfIcmpInGroupMembReductions);
19876 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19877 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19878 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19879 	    o2->ipv6IfIcmpOutDestUnreachs);
19880 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19881 	    o2->ipv6IfIcmpOutAdminProhibs);
19882 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19883 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19884 	    o2->ipv6IfIcmpOutParmProblems);
19885 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19886 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19887 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19888 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19889 	    o2->ipv6IfIcmpOutRouterSolicits);
19890 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19891 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19892 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19893 	    o2->ipv6IfIcmpOutNeighborSolicits);
19894 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19895 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19896 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19897 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19898 	    o2->ipv6IfIcmpOutGroupMembQueries);
19899 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19900 	    o2->ipv6IfIcmpOutGroupMembResponses);
19901 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19902 	    o2->ipv6IfIcmpOutGroupMembReductions);
19903 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19904 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19905 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19906 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19907 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19908 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19909 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19910 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19911 	    o2->ipv6IfIcmpInGroupMembTotal);
19912 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19913 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19914 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19915 	    o2->ipv6IfIcmpInGroupMembBadReports);
19916 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19917 	    o2->ipv6IfIcmpInGroupMembOurReports);
19918 }
19919 
19920 /*
19921  * Called before the options are updated to check if this packet will
19922  * be source routed from here.
19923  * This routine assumes that the options are well formed i.e. that they
19924  * have already been checked.
19925  */
19926 static boolean_t
19927 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19928 {
19929 	ipoptp_t	opts;
19930 	uchar_t		*opt;
19931 	uint8_t		optval;
19932 	uint8_t		optlen;
19933 	ipaddr_t	dst;
19934 	ire_t		*ire;
19935 
19936 	if (IS_SIMPLE_IPH(ipha)) {
19937 		ip2dbg(("not source routed\n"));
19938 		return (B_FALSE);
19939 	}
19940 	dst = ipha->ipha_dst;
19941 	for (optval = ipoptp_first(&opts, ipha);
19942 	    optval != IPOPT_EOL;
19943 	    optval = ipoptp_next(&opts)) {
19944 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19945 		opt = opts.ipoptp_cur;
19946 		optlen = opts.ipoptp_len;
19947 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19948 		    optval, optlen));
19949 		switch (optval) {
19950 			uint32_t off;
19951 		case IPOPT_SSRR:
19952 		case IPOPT_LSRR:
19953 			/*
19954 			 * If dst is one of our addresses and there are some
19955 			 * entries left in the source route return (true).
19956 			 */
19957 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19958 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19959 			if (ire == NULL) {
19960 				ip2dbg(("ip_source_routed: not next"
19961 				    " source route 0x%x\n",
19962 				    ntohl(dst)));
19963 				return (B_FALSE);
19964 			}
19965 			ire_refrele(ire);
19966 			off = opt[IPOPT_OFFSET];
19967 			off--;
19968 			if (optlen < IP_ADDR_LEN ||
19969 			    off > optlen - IP_ADDR_LEN) {
19970 				/* End of source route */
19971 				ip1dbg(("ip_source_routed: end of SR\n"));
19972 				return (B_FALSE);
19973 			}
19974 			return (B_TRUE);
19975 		}
19976 	}
19977 	ip2dbg(("not source routed\n"));
19978 	return (B_FALSE);
19979 }
19980 
19981 /*
19982  * Check if the packet contains any source route.
19983  */
19984 static boolean_t
19985 ip_source_route_included(ipha_t *ipha)
19986 {
19987 	ipoptp_t	opts;
19988 	uint8_t		optval;
19989 
19990 	if (IS_SIMPLE_IPH(ipha))
19991 		return (B_FALSE);
19992 	for (optval = ipoptp_first(&opts, ipha);
19993 	    optval != IPOPT_EOL;
19994 	    optval = ipoptp_next(&opts)) {
19995 		switch (optval) {
19996 		case IPOPT_SSRR:
19997 		case IPOPT_LSRR:
19998 			return (B_TRUE);
19999 		}
20000 	}
20001 	return (B_FALSE);
20002 }
20003 
20004 /*
20005  * Called when the IRE expiration timer fires.
20006  */
20007 void
20008 ip_trash_timer_expire(void *args)
20009 {
20010 	int			flush_flag = 0;
20011 	ire_expire_arg_t	iea;
20012 	ip_stack_t		*ipst = (ip_stack_t *)args;
20013 
20014 	iea.iea_ipst = ipst;	/* No netstack_hold */
20015 
20016 	/*
20017 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20018 	 * This lock makes sure that a new invocation of this function
20019 	 * that occurs due to an almost immediate timer firing will not
20020 	 * progress beyond this point until the current invocation is done
20021 	 */
20022 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20023 	ipst->ips_ip_ire_expire_id = 0;
20024 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20025 
20026 	/* Periodic timer */
20027 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20028 	    ipst->ips_ip_ire_arp_interval) {
20029 		/*
20030 		 * Remove all IRE_CACHE entries since they might
20031 		 * contain arp information.
20032 		 */
20033 		flush_flag |= FLUSH_ARP_TIME;
20034 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20035 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20036 	}
20037 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20038 	    ipst->ips_ip_ire_redir_interval) {
20039 		/* Remove all redirects */
20040 		flush_flag |= FLUSH_REDIRECT_TIME;
20041 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20042 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20043 	}
20044 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20045 	    ipst->ips_ip_ire_pathmtu_interval) {
20046 		/* Increase path mtu */
20047 		flush_flag |= FLUSH_MTU_TIME;
20048 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20049 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20050 	}
20051 
20052 	/*
20053 	 * Optimize for the case when there are no redirects in the
20054 	 * ftable, that is, no need to walk the ftable in that case.
20055 	 */
20056 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20057 		iea.iea_flush_flag = flush_flag;
20058 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20059 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20060 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20061 		    NULL, ALL_ZONES, ipst);
20062 	}
20063 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20064 	    ipst->ips_ip_redirect_cnt > 0) {
20065 		iea.iea_flush_flag = flush_flag;
20066 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20067 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20068 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20069 	}
20070 	if (flush_flag & FLUSH_MTU_TIME) {
20071 		/*
20072 		 * Walk all IPv6 IRE's and update them
20073 		 * Note that ARP and redirect timers are not
20074 		 * needed since NUD handles stale entries.
20075 		 */
20076 		flush_flag = FLUSH_MTU_TIME;
20077 		iea.iea_flush_flag = flush_flag;
20078 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20079 		    ALL_ZONES, ipst);
20080 	}
20081 
20082 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20083 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20084 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20085 
20086 	/*
20087 	 * Hold the lock to serialize timeout calls and prevent
20088 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20089 	 * for the timer to fire and a new invocation of this function
20090 	 * to start before the return value of timeout has been stored
20091 	 * in ip_ire_expire_id by the current invocation.
20092 	 */
20093 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20094 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20095 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20096 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20097 }
20098 
20099 /*
20100  * Called by the memory allocator subsystem directly, when the system
20101  * is running low on memory.
20102  */
20103 /* ARGSUSED */
20104 void
20105 ip_trash_ire_reclaim(void *args)
20106 {
20107 	netstack_handle_t nh;
20108 	netstack_t *ns;
20109 
20110 	netstack_next_init(&nh);
20111 	while ((ns = netstack_next(&nh)) != NULL) {
20112 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20113 		netstack_rele(ns);
20114 	}
20115 	netstack_next_fini(&nh);
20116 }
20117 
20118 static void
20119 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20120 {
20121 	ire_cache_count_t icc;
20122 	ire_cache_reclaim_t icr;
20123 	ncc_cache_count_t ncc;
20124 	nce_cache_reclaim_t ncr;
20125 	uint_t delete_cnt;
20126 	/*
20127 	 * Memory reclaim call back.
20128 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20129 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20130 	 * entries, determine what fraction to free for
20131 	 * each category of IRE_CACHE entries giving absolute priority
20132 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20133 	 * entry will be freed unless all offlink entries are freed).
20134 	 */
20135 	icc.icc_total = 0;
20136 	icc.icc_unused = 0;
20137 	icc.icc_offlink = 0;
20138 	icc.icc_pmtu = 0;
20139 	icc.icc_onlink = 0;
20140 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20141 
20142 	/*
20143 	 * Free NCEs for IPv6 like the onlink ires.
20144 	 */
20145 	ncc.ncc_total = 0;
20146 	ncc.ncc_host = 0;
20147 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20148 
20149 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20150 	    icc.icc_pmtu + icc.icc_onlink);
20151 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20152 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20153 	if (delete_cnt == 0)
20154 		return;
20155 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20156 	/* Always delete all unused offlink entries */
20157 	icr.icr_ipst = ipst;
20158 	icr.icr_unused = 1;
20159 	if (delete_cnt <= icc.icc_unused) {
20160 		/*
20161 		 * Only need to free unused entries.  In other words,
20162 		 * there are enough unused entries to free to meet our
20163 		 * target number of freed ire cache entries.
20164 		 */
20165 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20166 		ncr.ncr_host = 0;
20167 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20168 		/*
20169 		 * Only need to free unused entries, plus a fraction of offlink
20170 		 * entries.  It follows from the first if statement that
20171 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20172 		 */
20173 		delete_cnt -= icc.icc_unused;
20174 		/* Round up # deleted by truncating fraction */
20175 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20176 		icr.icr_pmtu = icr.icr_onlink = 0;
20177 		ncr.ncr_host = 0;
20178 	} else if (delete_cnt <=
20179 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20180 		/*
20181 		 * Free all unused and offlink entries, plus a fraction of
20182 		 * pmtu entries.  It follows from the previous if statement
20183 		 * that icc_pmtu is non-zero, and that
20184 		 * delete_cnt != icc_unused + icc_offlink.
20185 		 */
20186 		icr.icr_offlink = 1;
20187 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20188 		/* Round up # deleted by truncating fraction */
20189 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20190 		icr.icr_onlink = 0;
20191 		ncr.ncr_host = 0;
20192 	} else {
20193 		/*
20194 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20195 		 * of onlink entries.  If we're here, then we know that
20196 		 * icc_onlink is non-zero, and that
20197 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20198 		 */
20199 		icr.icr_offlink = icr.icr_pmtu = 1;
20200 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20201 		    icc.icc_pmtu;
20202 		/* Round up # deleted by truncating fraction */
20203 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20204 		/* Using the same delete fraction as for onlink IREs */
20205 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20206 	}
20207 #ifdef DEBUG
20208 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20209 	    "fractions %d/%d/%d/%d\n",
20210 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20211 	    icc.icc_unused, icc.icc_offlink,
20212 	    icc.icc_pmtu, icc.icc_onlink,
20213 	    icr.icr_unused, icr.icr_offlink,
20214 	    icr.icr_pmtu, icr.icr_onlink));
20215 #endif
20216 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20217 	if (ncr.ncr_host != 0)
20218 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20219 		    (uchar_t *)&ncr, ipst);
20220 #ifdef DEBUG
20221 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20222 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20223 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20224 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20225 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20226 	    icc.icc_pmtu, icc.icc_onlink));
20227 #endif
20228 }
20229 
20230 /*
20231  * ip_unbind is called when a copy of an unbind request is received from the
20232  * upper level protocol.  We remove this conn from any fanout hash list it is
20233  * on, and zero out the bind information.  No reply is expected up above.
20234  */
20235 void
20236 ip_unbind(conn_t *connp)
20237 {
20238 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20239 
20240 	if (is_system_labeled() && connp->conn_anon_port) {
20241 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20242 		    connp->conn_mlp_type, connp->conn_ulp,
20243 		    ntohs(connp->conn_lport), B_FALSE);
20244 		connp->conn_anon_port = 0;
20245 	}
20246 	connp->conn_mlp_type = mlptSingle;
20247 
20248 	ipcl_hash_remove(connp);
20249 }
20250 
20251 /*
20252  * Write side put procedure.  Outbound data, IOCTLs, responses from
20253  * resolvers, etc, come down through here.
20254  *
20255  * arg2 is always a queue_t *.
20256  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20257  * the zoneid.
20258  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20259  */
20260 void
20261 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20262 {
20263 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20264 }
20265 
20266 void
20267 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20268     ip_opt_info_t *infop)
20269 {
20270 	conn_t		*connp = NULL;
20271 	queue_t		*q = (queue_t *)arg2;
20272 	ipha_t		*ipha;
20273 #define	rptr	((uchar_t *)ipha)
20274 	ire_t		*ire = NULL;
20275 	ire_t		*sctp_ire = NULL;
20276 	uint32_t	v_hlen_tos_len;
20277 	ipaddr_t	dst;
20278 	mblk_t		*first_mp = NULL;
20279 	boolean_t	mctl_present;
20280 	ipsec_out_t	*io;
20281 	int		match_flags;
20282 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20283 	ipif_t		*dst_ipif;
20284 	boolean_t	multirt_need_resolve = B_FALSE;
20285 	mblk_t		*copy_mp = NULL;
20286 	int		err = 0;
20287 	zoneid_t	zoneid;
20288 	boolean_t	need_decref = B_FALSE;
20289 	boolean_t	ignore_dontroute = B_FALSE;
20290 	boolean_t	ignore_nexthop = B_FALSE;
20291 	boolean_t	ip_nexthop = B_FALSE;
20292 	ipaddr_t	nexthop_addr;
20293 	ip_stack_t	*ipst;
20294 
20295 #ifdef	_BIG_ENDIAN
20296 #define	V_HLEN	(v_hlen_tos_len >> 24)
20297 #else
20298 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20299 #endif
20300 
20301 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20302 	    "ip_wput_start: q %p", q);
20303 
20304 	/*
20305 	 * ip_wput fast path
20306 	 */
20307 
20308 	/* is packet from ARP ? */
20309 	if (q->q_next != NULL) {
20310 		zoneid = (zoneid_t)(uintptr_t)arg;
20311 		goto qnext;
20312 	}
20313 
20314 	connp = (conn_t *)arg;
20315 	ASSERT(connp != NULL);
20316 	zoneid = connp->conn_zoneid;
20317 	ipst = connp->conn_netstack->netstack_ip;
20318 	ASSERT(ipst != NULL);
20319 
20320 	/* is queue flow controlled? */
20321 	if ((q->q_first != NULL || connp->conn_draining) &&
20322 	    (caller == IP_WPUT)) {
20323 		ASSERT(!need_decref);
20324 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20325 		(void) putq(q, mp);
20326 		return;
20327 	}
20328 
20329 	/* Multidata transmit? */
20330 	if (DB_TYPE(mp) == M_MULTIDATA) {
20331 		/*
20332 		 * We should never get here, since all Multidata messages
20333 		 * originating from tcp should have been directed over to
20334 		 * tcp_multisend() in the first place.
20335 		 */
20336 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20337 		freemsg(mp);
20338 		return;
20339 	} else if (DB_TYPE(mp) != M_DATA)
20340 		goto notdata;
20341 
20342 	if (mp->b_flag & MSGHASREF) {
20343 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20344 		mp->b_flag &= ~MSGHASREF;
20345 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20346 		need_decref = B_TRUE;
20347 	}
20348 	ipha = (ipha_t *)mp->b_rptr;
20349 
20350 	/* is IP header non-aligned or mblk smaller than basic IP header */
20351 #ifndef SAFETY_BEFORE_SPEED
20352 	if (!OK_32PTR(rptr) ||
20353 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20354 		goto hdrtoosmall;
20355 #endif
20356 
20357 	ASSERT(OK_32PTR(ipha));
20358 
20359 	/*
20360 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20361 	 * wrong version, we'll catch it again in ip_output_v6.
20362 	 *
20363 	 * Note that this is *only* locally-generated output here, and never
20364 	 * forwarded data, and that we need to deal only with transports that
20365 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20366 	 * label.)
20367 	 */
20368 	if (is_system_labeled() &&
20369 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20370 	    !connp->conn_ulp_labeled) {
20371 		cred_t	*credp;
20372 		pid_t	pid;
20373 
20374 		credp = BEST_CRED(mp, connp, &pid);
20375 		err = tsol_check_label(credp, &mp,
20376 		    connp->conn_mac_exempt, ipst, pid);
20377 		ipha = (ipha_t *)mp->b_rptr;
20378 		if (err != 0) {
20379 			first_mp = mp;
20380 			if (err == EINVAL)
20381 				goto icmp_parameter_problem;
20382 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20383 			goto discard_pkt;
20384 		}
20385 	}
20386 
20387 	ASSERT(infop != NULL);
20388 
20389 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20390 		/*
20391 		 * IP_PKTINFO ancillary option is present.
20392 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20393 		 * allows using address of any zone as the source address.
20394 		 */
20395 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20396 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20397 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20398 		if (ire == NULL)
20399 			goto drop_pkt;
20400 		ire_refrele(ire);
20401 		ire = NULL;
20402 	}
20403 
20404 	/*
20405 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20406 	 */
20407 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20408 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20409 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20410 
20411 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20412 			goto drop_pkt;
20413 		/*
20414 		 * check that there is an ipif belonging
20415 		 * to our zone. IPCL_ZONEID is not used because
20416 		 * IP_ALLZONES option is valid only when the ill is
20417 		 * accessible from all zones i.e has a valid ipif in
20418 		 * all zones.
20419 		 */
20420 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20421 			goto drop_pkt;
20422 		}
20423 	}
20424 
20425 	/*
20426 	 * If there is a policy, try to attach an ipsec_out in
20427 	 * the front. At the end, first_mp either points to a
20428 	 * M_DATA message or IPSEC_OUT message linked to a
20429 	 * M_DATA message. We have to do it now as we might
20430 	 * lose the "conn" if we go through ip_newroute.
20431 	 */
20432 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20433 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20434 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20435 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20436 			if (need_decref)
20437 				CONN_DEC_REF(connp);
20438 			return;
20439 		} else {
20440 			ASSERT(mp->b_datap->db_type == M_CTL);
20441 			first_mp = mp;
20442 			mp = mp->b_cont;
20443 			mctl_present = B_TRUE;
20444 		}
20445 	} else {
20446 		first_mp = mp;
20447 		mctl_present = B_FALSE;
20448 	}
20449 
20450 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20451 
20452 	/* is wrong version or IP options present */
20453 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20454 		goto version_hdrlen_check;
20455 	dst = ipha->ipha_dst;
20456 
20457 	/* If IP_BOUND_IF has been set, use that ill. */
20458 	if (connp->conn_outgoing_ill != NULL) {
20459 		xmit_ill = conn_get_held_ill(connp,
20460 		    &connp->conn_outgoing_ill, &err);
20461 		if (err == ILL_LOOKUP_FAILED)
20462 			goto drop_pkt;
20463 
20464 		goto send_from_ill;
20465 	}
20466 
20467 	/* is packet multicast? */
20468 	if (CLASSD(dst))
20469 		goto multicast;
20470 
20471 	/*
20472 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20473 	 * takes precedence over conn_dontroute and conn_nexthop_set
20474 	 */
20475 	if (xmit_ill != NULL)
20476 		goto send_from_ill;
20477 
20478 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20479 		/*
20480 		 * If the destination is a broadcast, local, or loopback
20481 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20482 		 * standard path.
20483 		 */
20484 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20485 		if ((ire == NULL) || (ire->ire_type &
20486 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20487 			if (ire != NULL) {
20488 				ire_refrele(ire);
20489 				/* No more access to ire */
20490 				ire = NULL;
20491 			}
20492 			/*
20493 			 * bypass routing checks and go directly to interface.
20494 			 */
20495 			if (connp->conn_dontroute)
20496 				goto dontroute;
20497 
20498 			ASSERT(connp->conn_nexthop_set);
20499 			ip_nexthop = B_TRUE;
20500 			nexthop_addr = connp->conn_nexthop_v4;
20501 			goto send_from_ill;
20502 		}
20503 
20504 		/* Must be a broadcast, a loopback or a local ire */
20505 		ire_refrele(ire);
20506 		/* No more access to ire */
20507 		ire = NULL;
20508 	}
20509 
20510 	/*
20511 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20512 	 * this for the tcp global queue and listen end point
20513 	 * as it does not really have a real destination to
20514 	 * talk to.  This is also true for SCTP.
20515 	 */
20516 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20517 	    !connp->conn_fully_bound) {
20518 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20519 		if (ire == NULL)
20520 			goto noirefound;
20521 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20522 		    "ip_wput_end: q %p (%S)", q, "end");
20523 
20524 		/*
20525 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20526 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20527 		 */
20528 		if (ire->ire_flags & RTF_MULTIRT) {
20529 
20530 			/*
20531 			 * Force the TTL of multirouted packets if required.
20532 			 * The TTL of such packets is bounded by the
20533 			 * ip_multirt_ttl ndd variable.
20534 			 */
20535 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20536 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20537 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20538 				    "(was %d), dst 0x%08x\n",
20539 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20540 				    ntohl(ire->ire_addr)));
20541 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20542 			}
20543 			/*
20544 			 * We look at this point if there are pending
20545 			 * unresolved routes. ire_multirt_resolvable()
20546 			 * checks in O(n) that all IRE_OFFSUBNET ire
20547 			 * entries for the packet's destination and
20548 			 * flagged RTF_MULTIRT are currently resolved.
20549 			 * If some remain unresolved, we make a copy
20550 			 * of the current message. It will be used
20551 			 * to initiate additional route resolutions.
20552 			 */
20553 			multirt_need_resolve =
20554 			    ire_multirt_need_resolve(ire->ire_addr,
20555 			    msg_getlabel(first_mp), ipst);
20556 			ip2dbg(("ip_wput[TCP]: ire %p, "
20557 			    "multirt_need_resolve %d, first_mp %p\n",
20558 			    (void *)ire, multirt_need_resolve,
20559 			    (void *)first_mp));
20560 			if (multirt_need_resolve) {
20561 				copy_mp = copymsg(first_mp);
20562 				if (copy_mp != NULL) {
20563 					MULTIRT_DEBUG_TAG(copy_mp);
20564 				}
20565 			}
20566 		}
20567 
20568 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20569 
20570 		/*
20571 		 * Try to resolve another multiroute if
20572 		 * ire_multirt_need_resolve() deemed it necessary.
20573 		 */
20574 		if (copy_mp != NULL)
20575 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20576 		if (need_decref)
20577 			CONN_DEC_REF(connp);
20578 		return;
20579 	}
20580 
20581 	/*
20582 	 * Access to conn_ire_cache. (protected by conn_lock)
20583 	 *
20584 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20585 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20586 	 * send a packet or two with the IRE_CACHE that is going away.
20587 	 * Access to the ire requires an ire refhold on the ire prior to
20588 	 * its use since an interface unplumb thread may delete the cached
20589 	 * ire and release the refhold at any time.
20590 	 *
20591 	 * Caching an ire in the conn_ire_cache
20592 	 *
20593 	 * o Caching an ire pointer in the conn requires a strict check for
20594 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20595 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20596 	 * in the conn is done after making sure under the bucket lock that the
20597 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20598 	 * caching an ire after the unplumb thread has cleaned up the conn.
20599 	 * If the conn does not send a packet subsequently the unplumb thread
20600 	 * will be hanging waiting for the ire count to drop to zero.
20601 	 *
20602 	 * o We also need to atomically test for a null conn_ire_cache and
20603 	 * set the conn_ire_cache under the the protection of the conn_lock
20604 	 * to avoid races among concurrent threads trying to simultaneously
20605 	 * cache an ire in the conn_ire_cache.
20606 	 */
20607 	mutex_enter(&connp->conn_lock);
20608 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20609 
20610 	if (ire != NULL && ire->ire_addr == dst &&
20611 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20612 
20613 		IRE_REFHOLD(ire);
20614 		mutex_exit(&connp->conn_lock);
20615 
20616 	} else {
20617 		boolean_t cached = B_FALSE;
20618 		connp->conn_ire_cache = NULL;
20619 		mutex_exit(&connp->conn_lock);
20620 		/* Release the old ire */
20621 		if (ire != NULL && sctp_ire == NULL)
20622 			IRE_REFRELE_NOTR(ire);
20623 
20624 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20625 		if (ire == NULL)
20626 			goto noirefound;
20627 		IRE_REFHOLD_NOTR(ire);
20628 
20629 		mutex_enter(&connp->conn_lock);
20630 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20631 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20632 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20633 				if (connp->conn_ulp == IPPROTO_TCP)
20634 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20635 				connp->conn_ire_cache = ire;
20636 				cached = B_TRUE;
20637 			}
20638 			rw_exit(&ire->ire_bucket->irb_lock);
20639 		}
20640 		mutex_exit(&connp->conn_lock);
20641 
20642 		/*
20643 		 * We can continue to use the ire but since it was
20644 		 * not cached, we should drop the extra reference.
20645 		 */
20646 		if (!cached)
20647 			IRE_REFRELE_NOTR(ire);
20648 	}
20649 
20650 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20651 	    "ip_wput_end: q %p (%S)", q, "end");
20652 
20653 	/*
20654 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20655 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20656 	 */
20657 	if (ire->ire_flags & RTF_MULTIRT) {
20658 		/*
20659 		 * Force the TTL of multirouted packets if required.
20660 		 * The TTL of such packets is bounded by the
20661 		 * ip_multirt_ttl ndd variable.
20662 		 */
20663 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20664 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20665 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20666 			    "(was %d), dst 0x%08x\n",
20667 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20668 			    ntohl(ire->ire_addr)));
20669 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20670 		}
20671 
20672 		/*
20673 		 * At this point, we check to see if there are any pending
20674 		 * unresolved routes. ire_multirt_resolvable()
20675 		 * checks in O(n) that all IRE_OFFSUBNET ire
20676 		 * entries for the packet's destination and
20677 		 * flagged RTF_MULTIRT are currently resolved.
20678 		 * If some remain unresolved, we make a copy
20679 		 * of the current message. It will be used
20680 		 * to initiate additional route resolutions.
20681 		 */
20682 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20683 		    msg_getlabel(first_mp), ipst);
20684 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20685 		    "multirt_need_resolve %d, first_mp %p\n",
20686 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20687 		if (multirt_need_resolve) {
20688 			copy_mp = copymsg(first_mp);
20689 			if (copy_mp != NULL) {
20690 				MULTIRT_DEBUG_TAG(copy_mp);
20691 			}
20692 		}
20693 	}
20694 
20695 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20696 
20697 	/*
20698 	 * Try to resolve another multiroute if
20699 	 * ire_multirt_resolvable() deemed it necessary
20700 	 */
20701 	if (copy_mp != NULL)
20702 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20703 	if (need_decref)
20704 		CONN_DEC_REF(connp);
20705 	return;
20706 
20707 qnext:
20708 	/*
20709 	 * Upper Level Protocols pass down complete IP datagrams
20710 	 * as M_DATA messages.	Everything else is a sideshow.
20711 	 *
20712 	 * 1) We could be re-entering ip_wput because of ip_neworute
20713 	 *    in which case we could have a IPSEC_OUT message. We
20714 	 *    need to pass through ip_wput like other datagrams and
20715 	 *    hence cannot branch to ip_wput_nondata.
20716 	 *
20717 	 * 2) ARP, AH, ESP, and other clients who are on the module
20718 	 *    instance of IP stream, give us something to deal with.
20719 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20720 	 *
20721 	 * 3) ICMP replies also could come here.
20722 	 */
20723 	ipst = ILLQ_TO_IPST(q);
20724 
20725 	if (DB_TYPE(mp) != M_DATA) {
20726 notdata:
20727 		if (DB_TYPE(mp) == M_CTL) {
20728 			/*
20729 			 * M_CTL messages are used by ARP, AH and ESP to
20730 			 * communicate with IP. We deal with IPSEC_IN and
20731 			 * IPSEC_OUT here. ip_wput_nondata handles other
20732 			 * cases.
20733 			 */
20734 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20735 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20736 				first_mp = mp->b_cont;
20737 				first_mp->b_flag &= ~MSGHASREF;
20738 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20739 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20740 				CONN_DEC_REF(connp);
20741 				connp = NULL;
20742 			}
20743 			if (ii->ipsec_info_type == IPSEC_IN) {
20744 				/*
20745 				 * Either this message goes back to
20746 				 * IPsec for further processing or to
20747 				 * ULP after policy checks.
20748 				 */
20749 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20750 				return;
20751 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20752 				io = (ipsec_out_t *)ii;
20753 				if (io->ipsec_out_proc_begin) {
20754 					/*
20755 					 * IPsec processing has already started.
20756 					 * Complete it.
20757 					 * IPQoS notes: We don't care what is
20758 					 * in ipsec_out_ill_index since this
20759 					 * won't be processed for IPQoS policies
20760 					 * in ipsec_out_process.
20761 					 */
20762 					ipsec_out_process(q, mp, NULL,
20763 					    io->ipsec_out_ill_index);
20764 					return;
20765 				} else {
20766 					connp = (q->q_next != NULL) ?
20767 					    NULL : Q_TO_CONN(q);
20768 					first_mp = mp;
20769 					mp = mp->b_cont;
20770 					mctl_present = B_TRUE;
20771 				}
20772 				zoneid = io->ipsec_out_zoneid;
20773 				ASSERT(zoneid != ALL_ZONES);
20774 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20775 				/*
20776 				 * It's an IPsec control message requesting
20777 				 * an SADB update to be sent to the IPsec
20778 				 * hardware acceleration capable ills.
20779 				 */
20780 				ipsec_ctl_t *ipsec_ctl =
20781 				    (ipsec_ctl_t *)mp->b_rptr;
20782 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20783 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20784 				mblk_t *cmp = mp->b_cont;
20785 
20786 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20787 				ASSERT(cmp != NULL);
20788 
20789 				freeb(mp);
20790 				ill_ipsec_capab_send_all(satype, cmp, sa,
20791 				    ipst->ips_netstack);
20792 				return;
20793 			} else {
20794 				/*
20795 				 * This must be ARP or special TSOL signaling.
20796 				 */
20797 				ip_wput_nondata(NULL, q, mp, NULL);
20798 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20799 				    "ip_wput_end: q %p (%S)", q, "nondata");
20800 				return;
20801 			}
20802 		} else {
20803 			/*
20804 			 * This must be non-(ARP/AH/ESP) messages.
20805 			 */
20806 			ASSERT(!need_decref);
20807 			ip_wput_nondata(NULL, q, mp, NULL);
20808 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20809 			    "ip_wput_end: q %p (%S)", q, "nondata");
20810 			return;
20811 		}
20812 	} else {
20813 		first_mp = mp;
20814 		mctl_present = B_FALSE;
20815 	}
20816 
20817 	ASSERT(first_mp != NULL);
20818 
20819 	if (mctl_present) {
20820 		io = (ipsec_out_t *)first_mp->b_rptr;
20821 		if (io->ipsec_out_ip_nexthop) {
20822 			/*
20823 			 * We may have lost the conn context if we are
20824 			 * coming here from ip_newroute(). Copy the
20825 			 * nexthop information.
20826 			 */
20827 			ip_nexthop = B_TRUE;
20828 			nexthop_addr = io->ipsec_out_nexthop_addr;
20829 
20830 			ipha = (ipha_t *)mp->b_rptr;
20831 			dst = ipha->ipha_dst;
20832 			goto send_from_ill;
20833 		}
20834 	}
20835 
20836 	ASSERT(xmit_ill == NULL);
20837 
20838 	/* We have a complete IP datagram heading outbound. */
20839 	ipha = (ipha_t *)mp->b_rptr;
20840 
20841 #ifndef SPEED_BEFORE_SAFETY
20842 	/*
20843 	 * Make sure we have a full-word aligned message and that at least
20844 	 * a simple IP header is accessible in the first message.  If not,
20845 	 * try a pullup.  For labeled systems we need to always take this
20846 	 * path as M_CTLs are "notdata" but have trailing data to process.
20847 	 */
20848 	if (!OK_32PTR(rptr) ||
20849 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20850 hdrtoosmall:
20851 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20852 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20853 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20854 			if (first_mp == NULL)
20855 				first_mp = mp;
20856 			goto discard_pkt;
20857 		}
20858 
20859 		/* This function assumes that mp points to an IPv4 packet. */
20860 		if (is_system_labeled() &&
20861 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20862 		    (connp == NULL || !connp->conn_ulp_labeled)) {
20863 			cred_t	*credp;
20864 			pid_t	pid;
20865 
20866 			if (connp != NULL) {
20867 				credp = BEST_CRED(mp, connp, &pid);
20868 				err = tsol_check_label(credp, &mp,
20869 				    connp->conn_mac_exempt, ipst, pid);
20870 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
20871 				err = tsol_check_label(credp, &mp,
20872 				    B_FALSE, ipst, pid);
20873 			}
20874 			ipha = (ipha_t *)mp->b_rptr;
20875 			if (mctl_present)
20876 				first_mp->b_cont = mp;
20877 			else
20878 				first_mp = mp;
20879 			if (err != 0) {
20880 				if (err == EINVAL)
20881 					goto icmp_parameter_problem;
20882 				ip2dbg(("ip_wput: label check failed (%d)\n",
20883 				    err));
20884 				goto discard_pkt;
20885 			}
20886 		}
20887 
20888 		ipha = (ipha_t *)mp->b_rptr;
20889 		if (first_mp == NULL) {
20890 			ASSERT(xmit_ill == NULL);
20891 			/*
20892 			 * If we got here because of "goto hdrtoosmall"
20893 			 * We need to attach a IPSEC_OUT.
20894 			 */
20895 			if (connp->conn_out_enforce_policy) {
20896 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20897 				    NULL, ipha->ipha_protocol,
20898 				    ipst->ips_netstack)) == NULL)) {
20899 					BUMP_MIB(&ipst->ips_ip_mib,
20900 					    ipIfStatsOutDiscards);
20901 					if (need_decref)
20902 						CONN_DEC_REF(connp);
20903 					return;
20904 				} else {
20905 					ASSERT(mp->b_datap->db_type == M_CTL);
20906 					first_mp = mp;
20907 					mp = mp->b_cont;
20908 					mctl_present = B_TRUE;
20909 				}
20910 			} else {
20911 				first_mp = mp;
20912 				mctl_present = B_FALSE;
20913 			}
20914 		}
20915 	}
20916 #endif
20917 
20918 	/* Most of the code below is written for speed, not readability */
20919 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20920 
20921 	/*
20922 	 * If ip_newroute() fails, we're going to need a full
20923 	 * header for the icmp wraparound.
20924 	 */
20925 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20926 		uint_t	v_hlen;
20927 version_hdrlen_check:
20928 		ASSERT(first_mp != NULL);
20929 		v_hlen = V_HLEN;
20930 		/*
20931 		 * siphon off IPv6 packets coming down from transport
20932 		 * layer modules here.
20933 		 * Note: high-order bit carries NUD reachability confirmation
20934 		 */
20935 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20936 			/*
20937 			 * FIXME: assume that callers of ip_output* call
20938 			 * the right version?
20939 			 */
20940 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20941 			ASSERT(xmit_ill == NULL);
20942 			if (need_decref)
20943 				mp->b_flag |= MSGHASREF;
20944 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20945 			return;
20946 		}
20947 
20948 		if ((v_hlen >> 4) != IP_VERSION) {
20949 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20950 			    "ip_wput_end: q %p (%S)", q, "badvers");
20951 			goto discard_pkt;
20952 		}
20953 		/*
20954 		 * Is the header length at least 20 bytes?
20955 		 *
20956 		 * Are there enough bytes accessible in the header?  If
20957 		 * not, try a pullup.
20958 		 */
20959 		v_hlen &= 0xF;
20960 		v_hlen <<= 2;
20961 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20962 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20963 			    "ip_wput_end: q %p (%S)", q, "badlen");
20964 			goto discard_pkt;
20965 		}
20966 		if (v_hlen > (mp->b_wptr - rptr)) {
20967 			if (!pullupmsg(mp, v_hlen)) {
20968 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20969 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20970 				goto discard_pkt;
20971 			}
20972 			ipha = (ipha_t *)mp->b_rptr;
20973 		}
20974 		/*
20975 		 * Move first entry from any source route into ipha_dst and
20976 		 * verify the options
20977 		 */
20978 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20979 		    zoneid, ipst)) {
20980 			ASSERT(xmit_ill == NULL);
20981 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20982 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20983 			    "ip_wput_end: q %p (%S)", q, "badopts");
20984 			if (need_decref)
20985 				CONN_DEC_REF(connp);
20986 			return;
20987 		}
20988 	}
20989 	dst = ipha->ipha_dst;
20990 
20991 	/*
20992 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20993 	 * we have to run the packet through ip_newroute which will take
20994 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20995 	 * a resolver, or assigning a default gateway, etc.
20996 	 */
20997 	if (CLASSD(dst)) {
20998 		ipif_t	*ipif;
20999 		uint32_t setsrc = 0;
21000 
21001 multicast:
21002 		ASSERT(first_mp != NULL);
21003 		ip2dbg(("ip_wput: CLASSD\n"));
21004 		if (connp == NULL) {
21005 			/*
21006 			 * Use the first good ipif on the ill.
21007 			 * XXX Should this ever happen? (Appears
21008 			 * to show up with just ppp and no ethernet due
21009 			 * to in.rdisc.)
21010 			 * However, ire_send should be able to
21011 			 * call ip_wput_ire directly.
21012 			 *
21013 			 * XXX Also, this can happen for ICMP and other packets
21014 			 * with multicast source addresses.  Perhaps we should
21015 			 * fix things so that we drop the packet in question,
21016 			 * but for now, just run with it.
21017 			 */
21018 			ill_t *ill = (ill_t *)q->q_ptr;
21019 
21020 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21021 			if (ipif == NULL) {
21022 				if (need_decref)
21023 					CONN_DEC_REF(connp);
21024 				freemsg(first_mp);
21025 				return;
21026 			}
21027 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21028 			    ntohl(dst), ill->ill_name));
21029 		} else {
21030 			/*
21031 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21032 			 * and IP_MULTICAST_IF.  The block comment above this
21033 			 * function explains the locking mechanism used here.
21034 			 */
21035 			if (xmit_ill == NULL) {
21036 				xmit_ill = conn_get_held_ill(connp,
21037 				    &connp->conn_outgoing_ill, &err);
21038 				if (err == ILL_LOOKUP_FAILED) {
21039 					ip1dbg(("ip_wput: No ill for "
21040 					    "IP_BOUND_IF\n"));
21041 					BUMP_MIB(&ipst->ips_ip_mib,
21042 					    ipIfStatsOutNoRoutes);
21043 					goto drop_pkt;
21044 				}
21045 			}
21046 
21047 			if (xmit_ill == NULL) {
21048 				ipif = conn_get_held_ipif(connp,
21049 				    &connp->conn_multicast_ipif, &err);
21050 				if (err == IPIF_LOOKUP_FAILED) {
21051 					ip1dbg(("ip_wput: No ipif for "
21052 					    "multicast\n"));
21053 					BUMP_MIB(&ipst->ips_ip_mib,
21054 					    ipIfStatsOutNoRoutes);
21055 					goto drop_pkt;
21056 				}
21057 			}
21058 			if (xmit_ill != NULL) {
21059 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21060 				if (ipif == NULL) {
21061 					ip1dbg(("ip_wput: No ipif for "
21062 					    "xmit_ill\n"));
21063 					BUMP_MIB(&ipst->ips_ip_mib,
21064 					    ipIfStatsOutNoRoutes);
21065 					goto drop_pkt;
21066 				}
21067 			} else if (ipif == NULL || ipif->ipif_isv6) {
21068 				/*
21069 				 * We must do this ipif determination here
21070 				 * else we could pass through ip_newroute
21071 				 * and come back here without the conn context.
21072 				 *
21073 				 * Note: we do late binding i.e. we bind to
21074 				 * the interface when the first packet is sent.
21075 				 * For performance reasons we do not rebind on
21076 				 * each packet but keep the binding until the
21077 				 * next IP_MULTICAST_IF option.
21078 				 *
21079 				 * conn_multicast_{ipif,ill} are shared between
21080 				 * IPv4 and IPv6 and AF_INET6 sockets can
21081 				 * send both IPv4 and IPv6 packets. Hence
21082 				 * we have to check that "isv6" matches above.
21083 				 */
21084 				if (ipif != NULL)
21085 					ipif_refrele(ipif);
21086 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21087 				if (ipif == NULL) {
21088 					ip1dbg(("ip_wput: No ipif for "
21089 					    "multicast\n"));
21090 					BUMP_MIB(&ipst->ips_ip_mib,
21091 					    ipIfStatsOutNoRoutes);
21092 					goto drop_pkt;
21093 				}
21094 				err = conn_set_held_ipif(connp,
21095 				    &connp->conn_multicast_ipif, ipif);
21096 				if (err == IPIF_LOOKUP_FAILED) {
21097 					ipif_refrele(ipif);
21098 					ip1dbg(("ip_wput: No ipif for "
21099 					    "multicast\n"));
21100 					BUMP_MIB(&ipst->ips_ip_mib,
21101 					    ipIfStatsOutNoRoutes);
21102 					goto drop_pkt;
21103 				}
21104 			}
21105 		}
21106 		ASSERT(!ipif->ipif_isv6);
21107 		/*
21108 		 * As we may lose the conn by the time we reach ip_wput_ire,
21109 		 * we copy conn_multicast_loop and conn_dontroute on to an
21110 		 * ipsec_out. In case if this datagram goes out secure,
21111 		 * we need the ill_index also. Copy that also into the
21112 		 * ipsec_out.
21113 		 */
21114 		if (mctl_present) {
21115 			io = (ipsec_out_t *)first_mp->b_rptr;
21116 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21117 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21118 		} else {
21119 			ASSERT(mp == first_mp);
21120 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21121 			    BPRI_HI)) == NULL) {
21122 				ipif_refrele(ipif);
21123 				first_mp = mp;
21124 				goto discard_pkt;
21125 			}
21126 			first_mp->b_datap->db_type = M_CTL;
21127 			first_mp->b_wptr += sizeof (ipsec_info_t);
21128 			/* ipsec_out_secure is B_FALSE now */
21129 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21130 			io = (ipsec_out_t *)first_mp->b_rptr;
21131 			io->ipsec_out_type = IPSEC_OUT;
21132 			io->ipsec_out_len = sizeof (ipsec_out_t);
21133 			io->ipsec_out_use_global_policy = B_TRUE;
21134 			io->ipsec_out_ns = ipst->ips_netstack;
21135 			first_mp->b_cont = mp;
21136 			mctl_present = B_TRUE;
21137 		}
21138 
21139 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21140 		io->ipsec_out_ill_index =
21141 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21142 
21143 		if (connp != NULL) {
21144 			io->ipsec_out_multicast_loop =
21145 			    connp->conn_multicast_loop;
21146 			io->ipsec_out_dontroute = connp->conn_dontroute;
21147 			io->ipsec_out_zoneid = connp->conn_zoneid;
21148 		}
21149 		/*
21150 		 * If the application uses IP_MULTICAST_IF with
21151 		 * different logical addresses of the same ILL, we
21152 		 * need to make sure that the soruce address of
21153 		 * the packet matches the logical IP address used
21154 		 * in the option. We do it by initializing ipha_src
21155 		 * here. This should keep IPsec also happy as
21156 		 * when we return from IPsec processing, we don't
21157 		 * have to worry about getting the right address on
21158 		 * the packet. Thus it is sufficient to look for
21159 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21160 		 * MATCH_IRE_IPIF.
21161 		 *
21162 		 * NOTE : We need to do it for non-secure case also as
21163 		 * this might go out secure if there is a global policy
21164 		 * match in ip_wput_ire.
21165 		 *
21166 		 * As we do not have the ire yet, it is possible that
21167 		 * we set the source address here and then later discover
21168 		 * that the ire implies the source address to be assigned
21169 		 * through the RTF_SETSRC flag.
21170 		 * In that case, the setsrc variable will remind us
21171 		 * that overwritting the source address by the one
21172 		 * of the RTF_SETSRC-flagged ire is allowed.
21173 		 */
21174 		if (ipha->ipha_src == INADDR_ANY &&
21175 		    (connp == NULL || !connp->conn_unspec_src)) {
21176 			ipha->ipha_src = ipif->ipif_src_addr;
21177 			setsrc = RTF_SETSRC;
21178 		}
21179 		/*
21180 		 * Find an IRE which matches the destination and the outgoing
21181 		 * queue (i.e. the outgoing interface.)
21182 		 * For loopback use a unicast IP address for
21183 		 * the ire lookup.
21184 		 */
21185 		if (IS_LOOPBACK(ipif->ipif_ill))
21186 			dst = ipif->ipif_lcl_addr;
21187 
21188 		/*
21189 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21190 		 * We don't need to lookup ire in ctable as the packet
21191 		 * needs to be sent to the destination through the specified
21192 		 * ill irrespective of ires in the cache table.
21193 		 */
21194 		ire = NULL;
21195 		if (xmit_ill == NULL) {
21196 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21197 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21198 		}
21199 
21200 		if (ire == NULL) {
21201 			/*
21202 			 * Multicast loopback and multicast forwarding is
21203 			 * done in ip_wput_ire.
21204 			 *
21205 			 * Mark this packet to make it be delivered to
21206 			 * ip_wput_ire after the new ire has been
21207 			 * created.
21208 			 *
21209 			 * The call to ip_newroute_ipif takes into account
21210 			 * the setsrc reminder. In any case, we take care
21211 			 * of the RTF_MULTIRT flag.
21212 			 */
21213 			mp->b_prev = mp->b_next = NULL;
21214 			if (xmit_ill == NULL ||
21215 			    xmit_ill->ill_ipif_up_count > 0) {
21216 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21217 				    setsrc | RTF_MULTIRT, zoneid, infop);
21218 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21219 				    "ip_wput_end: q %p (%S)", q, "noire");
21220 			} else {
21221 				freemsg(first_mp);
21222 			}
21223 			ipif_refrele(ipif);
21224 			if (xmit_ill != NULL)
21225 				ill_refrele(xmit_ill);
21226 			if (need_decref)
21227 				CONN_DEC_REF(connp);
21228 			return;
21229 		}
21230 
21231 		ipif_refrele(ipif);
21232 		ipif = NULL;
21233 		ASSERT(xmit_ill == NULL);
21234 
21235 		/*
21236 		 * Honor the RTF_SETSRC flag for multicast packets,
21237 		 * if allowed by the setsrc reminder.
21238 		 */
21239 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21240 			ipha->ipha_src = ire->ire_src_addr;
21241 		}
21242 
21243 		/*
21244 		 * Unconditionally force the TTL to 1 for
21245 		 * multirouted multicast packets:
21246 		 * multirouted multicast should not cross
21247 		 * multicast routers.
21248 		 */
21249 		if (ire->ire_flags & RTF_MULTIRT) {
21250 			if (ipha->ipha_ttl > 1) {
21251 				ip2dbg(("ip_wput: forcing multicast "
21252 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21253 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21254 				ipha->ipha_ttl = 1;
21255 			}
21256 		}
21257 	} else {
21258 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21259 		if ((ire != NULL) && (ire->ire_type &
21260 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21261 			ignore_dontroute = B_TRUE;
21262 			ignore_nexthop = B_TRUE;
21263 		}
21264 		if (ire != NULL) {
21265 			ire_refrele(ire);
21266 			ire = NULL;
21267 		}
21268 		/*
21269 		 * Guard against coming in from arp in which case conn is NULL.
21270 		 * Also guard against non M_DATA with dontroute set but
21271 		 * destined to local, loopback or broadcast addresses.
21272 		 */
21273 		if (connp != NULL && connp->conn_dontroute &&
21274 		    !ignore_dontroute) {
21275 dontroute:
21276 			/*
21277 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21278 			 * routing protocols from seeing false direct
21279 			 * connectivity.
21280 			 */
21281 			ipha->ipha_ttl = 1;
21282 			/* If suitable ipif not found, drop packet */
21283 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21284 			if (dst_ipif == NULL) {
21285 noroute:
21286 				ip1dbg(("ip_wput: no route for dst using"
21287 				    " SO_DONTROUTE\n"));
21288 				BUMP_MIB(&ipst->ips_ip_mib,
21289 				    ipIfStatsOutNoRoutes);
21290 				mp->b_prev = mp->b_next = NULL;
21291 				if (first_mp == NULL)
21292 					first_mp = mp;
21293 				goto drop_pkt;
21294 			} else {
21295 				/*
21296 				 * If suitable ipif has been found, set
21297 				 * xmit_ill to the corresponding
21298 				 * ipif_ill because we'll be using the
21299 				 * send_from_ill logic below.
21300 				 */
21301 				ASSERT(xmit_ill == NULL);
21302 				xmit_ill = dst_ipif->ipif_ill;
21303 				mutex_enter(&xmit_ill->ill_lock);
21304 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21305 					mutex_exit(&xmit_ill->ill_lock);
21306 					xmit_ill = NULL;
21307 					ipif_refrele(dst_ipif);
21308 					goto noroute;
21309 				}
21310 				ill_refhold_locked(xmit_ill);
21311 				mutex_exit(&xmit_ill->ill_lock);
21312 				ipif_refrele(dst_ipif);
21313 			}
21314 		}
21315 
21316 send_from_ill:
21317 		if (xmit_ill != NULL) {
21318 			ipif_t *ipif;
21319 
21320 			/*
21321 			 * Mark this packet as originated locally
21322 			 */
21323 			mp->b_prev = mp->b_next = NULL;
21324 
21325 			/*
21326 			 * Could be SO_DONTROUTE case also.
21327 			 * Verify that at least one ipif is up on the ill.
21328 			 */
21329 			if (xmit_ill->ill_ipif_up_count == 0) {
21330 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21331 				    xmit_ill->ill_name));
21332 				goto drop_pkt;
21333 			}
21334 
21335 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21336 			if (ipif == NULL) {
21337 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21338 				    xmit_ill->ill_name));
21339 				goto drop_pkt;
21340 			}
21341 
21342 			match_flags = 0;
21343 			if (IS_UNDER_IPMP(xmit_ill))
21344 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21345 
21346 			/*
21347 			 * Look for a ire that is part of the group,
21348 			 * if found use it else call ip_newroute_ipif.
21349 			 * IPCL_ZONEID is not used for matching because
21350 			 * IP_ALLZONES option is valid only when the
21351 			 * ill is accessible from all zones i.e has a
21352 			 * valid ipif in all zones.
21353 			 */
21354 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21355 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21356 			    msg_getlabel(mp), match_flags, ipst);
21357 			/*
21358 			 * If an ire exists use it or else create
21359 			 * an ire but don't add it to the cache.
21360 			 * Adding an ire may cause issues with
21361 			 * asymmetric routing.
21362 			 * In case of multiroute always act as if
21363 			 * ire does not exist.
21364 			 */
21365 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21366 				if (ire != NULL)
21367 					ire_refrele(ire);
21368 				ip_newroute_ipif(q, first_mp, ipif,
21369 				    dst, connp, 0, zoneid, infop);
21370 				ipif_refrele(ipif);
21371 				ip1dbg(("ip_output: xmit_ill via %s\n",
21372 				    xmit_ill->ill_name));
21373 				ill_refrele(xmit_ill);
21374 				if (need_decref)
21375 					CONN_DEC_REF(connp);
21376 				return;
21377 			}
21378 			ipif_refrele(ipif);
21379 		} else if (ip_nexthop || (connp != NULL &&
21380 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21381 			if (!ip_nexthop) {
21382 				ip_nexthop = B_TRUE;
21383 				nexthop_addr = connp->conn_nexthop_v4;
21384 			}
21385 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21386 			    MATCH_IRE_GW;
21387 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21388 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21389 		} else {
21390 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21391 			    ipst);
21392 		}
21393 		if (!ire) {
21394 			if (ip_nexthop && !ignore_nexthop) {
21395 				if (mctl_present) {
21396 					io = (ipsec_out_t *)first_mp->b_rptr;
21397 					ASSERT(first_mp->b_datap->db_type ==
21398 					    M_CTL);
21399 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21400 				} else {
21401 					ASSERT(mp == first_mp);
21402 					first_mp = allocb(
21403 					    sizeof (ipsec_info_t), BPRI_HI);
21404 					if (first_mp == NULL) {
21405 						first_mp = mp;
21406 						goto discard_pkt;
21407 					}
21408 					first_mp->b_datap->db_type = M_CTL;
21409 					first_mp->b_wptr +=
21410 					    sizeof (ipsec_info_t);
21411 					/* ipsec_out_secure is B_FALSE now */
21412 					bzero(first_mp->b_rptr,
21413 					    sizeof (ipsec_info_t));
21414 					io = (ipsec_out_t *)first_mp->b_rptr;
21415 					io->ipsec_out_type = IPSEC_OUT;
21416 					io->ipsec_out_len =
21417 					    sizeof (ipsec_out_t);
21418 					io->ipsec_out_use_global_policy =
21419 					    B_TRUE;
21420 					io->ipsec_out_ns = ipst->ips_netstack;
21421 					first_mp->b_cont = mp;
21422 					mctl_present = B_TRUE;
21423 				}
21424 				io->ipsec_out_ip_nexthop = ip_nexthop;
21425 				io->ipsec_out_nexthop_addr = nexthop_addr;
21426 			}
21427 noirefound:
21428 			/*
21429 			 * Mark this packet as having originated on
21430 			 * this machine.  This will be noted in
21431 			 * ire_add_then_send, which needs to know
21432 			 * whether to run it back through ip_wput or
21433 			 * ip_rput following successful resolution.
21434 			 */
21435 			mp->b_prev = NULL;
21436 			mp->b_next = NULL;
21437 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21438 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21439 			    "ip_wput_end: q %p (%S)", q, "newroute");
21440 			if (xmit_ill != NULL)
21441 				ill_refrele(xmit_ill);
21442 			if (need_decref)
21443 				CONN_DEC_REF(connp);
21444 			return;
21445 		}
21446 	}
21447 
21448 	/* We now know where we are going with it. */
21449 
21450 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21451 	    "ip_wput_end: q %p (%S)", q, "end");
21452 
21453 	/*
21454 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21455 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21456 	 */
21457 	if (ire->ire_flags & RTF_MULTIRT) {
21458 		/*
21459 		 * Force the TTL of multirouted packets if required.
21460 		 * The TTL of such packets is bounded by the
21461 		 * ip_multirt_ttl ndd variable.
21462 		 */
21463 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21464 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21465 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21466 			    "(was %d), dst 0x%08x\n",
21467 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21468 			    ntohl(ire->ire_addr)));
21469 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21470 		}
21471 		/*
21472 		 * At this point, we check to see if there are any pending
21473 		 * unresolved routes. ire_multirt_resolvable()
21474 		 * checks in O(n) that all IRE_OFFSUBNET ire
21475 		 * entries for the packet's destination and
21476 		 * flagged RTF_MULTIRT are currently resolved.
21477 		 * If some remain unresolved, we make a copy
21478 		 * of the current message. It will be used
21479 		 * to initiate additional route resolutions.
21480 		 */
21481 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21482 		    msg_getlabel(first_mp), ipst);
21483 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21484 		    "multirt_need_resolve %d, first_mp %p\n",
21485 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21486 		if (multirt_need_resolve) {
21487 			copy_mp = copymsg(first_mp);
21488 			if (copy_mp != NULL) {
21489 				MULTIRT_DEBUG_TAG(copy_mp);
21490 			}
21491 		}
21492 	}
21493 
21494 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21495 	/*
21496 	 * Try to resolve another multiroute if
21497 	 * ire_multirt_resolvable() deemed it necessary.
21498 	 * At this point, we need to distinguish
21499 	 * multicasts from other packets. For multicasts,
21500 	 * we call ip_newroute_ipif() and request that both
21501 	 * multirouting and setsrc flags are checked.
21502 	 */
21503 	if (copy_mp != NULL) {
21504 		if (CLASSD(dst)) {
21505 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21506 			if (ipif) {
21507 				ASSERT(infop->ip_opt_ill_index == 0);
21508 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21509 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21510 				ipif_refrele(ipif);
21511 			} else {
21512 				MULTIRT_DEBUG_UNTAG(copy_mp);
21513 				freemsg(copy_mp);
21514 				copy_mp = NULL;
21515 			}
21516 		} else {
21517 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21518 		}
21519 	}
21520 	if (xmit_ill != NULL)
21521 		ill_refrele(xmit_ill);
21522 	if (need_decref)
21523 		CONN_DEC_REF(connp);
21524 	return;
21525 
21526 icmp_parameter_problem:
21527 	/* could not have originated externally */
21528 	ASSERT(mp->b_prev == NULL);
21529 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21530 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21531 		/* it's the IP header length that's in trouble */
21532 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21533 		first_mp = NULL;
21534 	}
21535 
21536 discard_pkt:
21537 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21538 drop_pkt:
21539 	ip1dbg(("ip_wput: dropped packet\n"));
21540 	if (ire != NULL)
21541 		ire_refrele(ire);
21542 	if (need_decref)
21543 		CONN_DEC_REF(connp);
21544 	freemsg(first_mp);
21545 	if (xmit_ill != NULL)
21546 		ill_refrele(xmit_ill);
21547 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21548 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21549 }
21550 
21551 /*
21552  * If this is a conn_t queue, then we pass in the conn. This includes the
21553  * zoneid.
21554  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21555  * in which case we use the global zoneid since those are all part of
21556  * the global zone.
21557  */
21558 void
21559 ip_wput(queue_t *q, mblk_t *mp)
21560 {
21561 	if (CONN_Q(q))
21562 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21563 	else
21564 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21565 }
21566 
21567 /*
21568  *
21569  * The following rules must be observed when accessing any ipif or ill
21570  * that has been cached in the conn. Typically conn_outgoing_ill,
21571  * conn_multicast_ipif and conn_multicast_ill.
21572  *
21573  * Access: The ipif or ill pointed to from the conn can be accessed under
21574  * the protection of the conn_lock or after it has been refheld under the
21575  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21576  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21577  * The reason for this is that a concurrent unplumb could actually be
21578  * cleaning up these cached pointers by walking the conns and might have
21579  * finished cleaning up the conn in question. The macros check that an
21580  * unplumb has not yet started on the ipif or ill.
21581  *
21582  * Caching: An ipif or ill pointer may be cached in the conn only after
21583  * making sure that an unplumb has not started. So the caching is done
21584  * while holding both the conn_lock and the ill_lock and after using the
21585  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21586  * flag before starting the cleanup of conns.
21587  *
21588  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21589  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21590  * or a reference to the ipif or a reference to an ire that references the
21591  * ipif. An ipif only changes its ill when migrating from an underlying ill
21592  * to an IPMP ill in ipif_up().
21593  */
21594 ipif_t *
21595 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21596 {
21597 	ipif_t	*ipif;
21598 	ill_t	*ill;
21599 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21600 
21601 	*err = 0;
21602 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21603 	mutex_enter(&connp->conn_lock);
21604 	ipif = *ipifp;
21605 	if (ipif != NULL) {
21606 		ill = ipif->ipif_ill;
21607 		mutex_enter(&ill->ill_lock);
21608 		if (IPIF_CAN_LOOKUP(ipif)) {
21609 			ipif_refhold_locked(ipif);
21610 			mutex_exit(&ill->ill_lock);
21611 			mutex_exit(&connp->conn_lock);
21612 			rw_exit(&ipst->ips_ill_g_lock);
21613 			return (ipif);
21614 		} else {
21615 			*err = IPIF_LOOKUP_FAILED;
21616 		}
21617 		mutex_exit(&ill->ill_lock);
21618 	}
21619 	mutex_exit(&connp->conn_lock);
21620 	rw_exit(&ipst->ips_ill_g_lock);
21621 	return (NULL);
21622 }
21623 
21624 ill_t *
21625 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21626 {
21627 	ill_t	*ill;
21628 
21629 	*err = 0;
21630 	mutex_enter(&connp->conn_lock);
21631 	ill = *illp;
21632 	if (ill != NULL) {
21633 		mutex_enter(&ill->ill_lock);
21634 		if (ILL_CAN_LOOKUP(ill)) {
21635 			ill_refhold_locked(ill);
21636 			mutex_exit(&ill->ill_lock);
21637 			mutex_exit(&connp->conn_lock);
21638 			return (ill);
21639 		} else {
21640 			*err = ILL_LOOKUP_FAILED;
21641 		}
21642 		mutex_exit(&ill->ill_lock);
21643 	}
21644 	mutex_exit(&connp->conn_lock);
21645 	return (NULL);
21646 }
21647 
21648 static int
21649 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21650 {
21651 	ill_t	*ill;
21652 
21653 	ill = ipif->ipif_ill;
21654 	mutex_enter(&connp->conn_lock);
21655 	mutex_enter(&ill->ill_lock);
21656 	if (IPIF_CAN_LOOKUP(ipif)) {
21657 		*ipifp = ipif;
21658 		mutex_exit(&ill->ill_lock);
21659 		mutex_exit(&connp->conn_lock);
21660 		return (0);
21661 	}
21662 	mutex_exit(&ill->ill_lock);
21663 	mutex_exit(&connp->conn_lock);
21664 	return (IPIF_LOOKUP_FAILED);
21665 }
21666 
21667 /*
21668  * This is called if the outbound datagram needs fragmentation.
21669  *
21670  * NOTE : This function does not ire_refrele the ire argument passed in.
21671  */
21672 static void
21673 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21674     ip_stack_t *ipst, conn_t *connp)
21675 {
21676 	ipha_t		*ipha;
21677 	mblk_t		*mp;
21678 	uint32_t	v_hlen_tos_len;
21679 	uint32_t	max_frag;
21680 	uint32_t	frag_flag;
21681 	boolean_t	dont_use;
21682 
21683 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21684 		mp = ipsec_mp->b_cont;
21685 	} else {
21686 		mp = ipsec_mp;
21687 	}
21688 
21689 	ipha = (ipha_t *)mp->b_rptr;
21690 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21691 
21692 #ifdef	_BIG_ENDIAN
21693 #define	V_HLEN	(v_hlen_tos_len >> 24)
21694 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21695 #else
21696 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21697 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21698 #endif
21699 
21700 #ifndef SPEED_BEFORE_SAFETY
21701 	/*
21702 	 * Check that ipha_length is consistent with
21703 	 * the mblk length
21704 	 */
21705 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21706 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21707 		    LENGTH, msgdsize(mp)));
21708 		freemsg(ipsec_mp);
21709 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21710 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21711 		    "packet length mismatch");
21712 		return;
21713 	}
21714 #endif
21715 	/*
21716 	 * Don't use frag_flag if pre-built packet or source
21717 	 * routed or if multicast (since multicast packets do not solicit
21718 	 * ICMP "packet too big" messages). Get the values of
21719 	 * max_frag and frag_flag atomically by acquiring the
21720 	 * ire_lock.
21721 	 */
21722 	mutex_enter(&ire->ire_lock);
21723 	max_frag = ire->ire_max_frag;
21724 	frag_flag = ire->ire_frag_flag;
21725 	mutex_exit(&ire->ire_lock);
21726 
21727 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21728 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21729 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21730 
21731 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21732 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21733 }
21734 
21735 /*
21736  * Used for deciding the MSS size for the upper layer. Thus
21737  * we need to check the outbound policy values in the conn.
21738  */
21739 int
21740 conn_ipsec_length(conn_t *connp)
21741 {
21742 	ipsec_latch_t *ipl;
21743 
21744 	ipl = connp->conn_latch;
21745 	if (ipl == NULL)
21746 		return (0);
21747 
21748 	if (ipl->ipl_out_policy == NULL)
21749 		return (0);
21750 
21751 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21752 }
21753 
21754 /*
21755  * Returns an estimate of the IPsec headers size. This is used if
21756  * we don't want to call into IPsec to get the exact size.
21757  */
21758 int
21759 ipsec_out_extra_length(mblk_t *ipsec_mp)
21760 {
21761 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21762 	ipsec_action_t *a;
21763 
21764 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21765 	if (!io->ipsec_out_secure)
21766 		return (0);
21767 
21768 	a = io->ipsec_out_act;
21769 
21770 	if (a == NULL) {
21771 		ASSERT(io->ipsec_out_policy != NULL);
21772 		a = io->ipsec_out_policy->ipsp_act;
21773 	}
21774 	ASSERT(a != NULL);
21775 
21776 	return (a->ipa_ovhd);
21777 }
21778 
21779 /*
21780  * Returns an estimate of the IPsec headers size. This is used if
21781  * we don't want to call into IPsec to get the exact size.
21782  */
21783 int
21784 ipsec_in_extra_length(mblk_t *ipsec_mp)
21785 {
21786 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21787 	ipsec_action_t *a;
21788 
21789 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21790 
21791 	a = ii->ipsec_in_action;
21792 	return (a == NULL ? 0 : a->ipa_ovhd);
21793 }
21794 
21795 /*
21796  * If there are any source route options, return the true final
21797  * destination. Otherwise, return the destination.
21798  */
21799 ipaddr_t
21800 ip_get_dst(ipha_t *ipha)
21801 {
21802 	ipoptp_t	opts;
21803 	uchar_t		*opt;
21804 	uint8_t		optval;
21805 	uint8_t		optlen;
21806 	ipaddr_t	dst;
21807 	uint32_t off;
21808 
21809 	dst = ipha->ipha_dst;
21810 
21811 	if (IS_SIMPLE_IPH(ipha))
21812 		return (dst);
21813 
21814 	for (optval = ipoptp_first(&opts, ipha);
21815 	    optval != IPOPT_EOL;
21816 	    optval = ipoptp_next(&opts)) {
21817 		opt = opts.ipoptp_cur;
21818 		optlen = opts.ipoptp_len;
21819 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21820 		switch (optval) {
21821 		case IPOPT_SSRR:
21822 		case IPOPT_LSRR:
21823 			off = opt[IPOPT_OFFSET];
21824 			/*
21825 			 * If one of the conditions is true, it means
21826 			 * end of options and dst already has the right
21827 			 * value.
21828 			 */
21829 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21830 				off = optlen - IP_ADDR_LEN;
21831 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21832 			}
21833 			return (dst);
21834 		default:
21835 			break;
21836 		}
21837 	}
21838 
21839 	return (dst);
21840 }
21841 
21842 mblk_t *
21843 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21844     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21845 {
21846 	ipsec_out_t	*io;
21847 	mblk_t		*first_mp;
21848 	boolean_t policy_present;
21849 	ip_stack_t	*ipst;
21850 	ipsec_stack_t	*ipss;
21851 
21852 	ASSERT(ire != NULL);
21853 	ipst = ire->ire_ipst;
21854 	ipss = ipst->ips_netstack->netstack_ipsec;
21855 
21856 	first_mp = mp;
21857 	if (mp->b_datap->db_type == M_CTL) {
21858 		io = (ipsec_out_t *)first_mp->b_rptr;
21859 		/*
21860 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21861 		 *
21862 		 * 1) There is per-socket policy (including cached global
21863 		 *    policy) or a policy on the IP-in-IP tunnel.
21864 		 * 2) There is no per-socket policy, but it is
21865 		 *    a multicast packet that needs to go out
21866 		 *    on a specific interface. This is the case
21867 		 *    where (ip_wput and ip_wput_multicast) attaches
21868 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21869 		 *
21870 		 * In case (2) we check with global policy to
21871 		 * see if there is a match and set the ill_index
21872 		 * appropriately so that we can lookup the ire
21873 		 * properly in ip_wput_ipsec_out.
21874 		 */
21875 
21876 		/*
21877 		 * ipsec_out_use_global_policy is set to B_FALSE
21878 		 * in ipsec_in_to_out(). Refer to that function for
21879 		 * details.
21880 		 */
21881 		if ((io->ipsec_out_latch == NULL) &&
21882 		    (io->ipsec_out_use_global_policy)) {
21883 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21884 			    ire, connp, unspec_src, zoneid));
21885 		}
21886 		if (!io->ipsec_out_secure) {
21887 			/*
21888 			 * If this is not a secure packet, drop
21889 			 * the IPSEC_OUT mp and treat it as a clear
21890 			 * packet. This happens when we are sending
21891 			 * a ICMP reply back to a clear packet. See
21892 			 * ipsec_in_to_out() for details.
21893 			 */
21894 			mp = first_mp->b_cont;
21895 			freeb(first_mp);
21896 		}
21897 		return (mp);
21898 	}
21899 	/*
21900 	 * See whether we need to attach a global policy here. We
21901 	 * don't depend on the conn (as it could be null) for deciding
21902 	 * what policy this datagram should go through because it
21903 	 * should have happened in ip_wput if there was some
21904 	 * policy. This normally happens for connections which are not
21905 	 * fully bound preventing us from caching policies in
21906 	 * ip_bind. Packets coming from the TCP listener/global queue
21907 	 * - which are non-hard_bound - could also be affected by
21908 	 * applying policy here.
21909 	 *
21910 	 * If this packet is coming from tcp global queue or listener,
21911 	 * we will be applying policy here.  This may not be *right*
21912 	 * if these packets are coming from the detached connection as
21913 	 * it could have gone in clear before. This happens only if a
21914 	 * TCP connection started when there is no policy and somebody
21915 	 * added policy before it became detached. Thus packets of the
21916 	 * detached connection could go out secure and the other end
21917 	 * would drop it because it will be expecting in clear. The
21918 	 * converse is not true i.e if somebody starts a TCP
21919 	 * connection and deletes the policy, all the packets will
21920 	 * still go out with the policy that existed before deleting
21921 	 * because ip_unbind sends up policy information which is used
21922 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21923 	 * TCP to attach a dummy IPSEC_OUT and set
21924 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21925 	 * affect performance for normal cases, we are not doing it.
21926 	 * Thus, set policy before starting any TCP connections.
21927 	 *
21928 	 * NOTE - We might apply policy even for a hard bound connection
21929 	 * - for which we cached policy in ip_bind - if somebody added
21930 	 * global policy after we inherited the policy in ip_bind.
21931 	 * This means that the packets that were going out in clear
21932 	 * previously would start going secure and hence get dropped
21933 	 * on the other side. To fix this, TCP attaches a dummy
21934 	 * ipsec_out and make sure that we don't apply global policy.
21935 	 */
21936 	if (ipha != NULL)
21937 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21938 	else
21939 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21940 	if (!policy_present)
21941 		return (mp);
21942 
21943 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21944 	    zoneid));
21945 }
21946 
21947 /*
21948  * This function does the ire_refrele of the ire passed in as the
21949  * argument. As this function looks up more ires i.e broadcast ires,
21950  * it needs to REFRELE them. Currently, for simplicity we don't
21951  * differentiate the one passed in and looked up here. We always
21952  * REFRELE.
21953  * IPQoS Notes:
21954  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21955  * IPsec packets are done in ipsec_out_process.
21956  */
21957 void
21958 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21959     zoneid_t zoneid)
21960 {
21961 	ipha_t		*ipha;
21962 #define	rptr	((uchar_t *)ipha)
21963 	queue_t		*stq;
21964 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21965 	uint32_t	v_hlen_tos_len;
21966 	uint32_t	ttl_protocol;
21967 	ipaddr_t	src;
21968 	ipaddr_t	dst;
21969 	uint32_t	cksum;
21970 	ipaddr_t	orig_src;
21971 	ire_t		*ire1;
21972 	mblk_t		*next_mp;
21973 	uint_t		hlen;
21974 	uint16_t	*up;
21975 	uint32_t	max_frag = ire->ire_max_frag;
21976 	ill_t		*ill = ire_to_ill(ire);
21977 	int		clusterwide;
21978 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21979 	int		ipsec_len;
21980 	mblk_t		*first_mp;
21981 	ipsec_out_t	*io;
21982 	boolean_t	conn_dontroute;		/* conn value for multicast */
21983 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21984 	boolean_t	multicast_forward;	/* Should we forward ? */
21985 	boolean_t	unspec_src;
21986 	ill_t		*conn_outgoing_ill = NULL;
21987 	ill_t		*ire_ill;
21988 	ill_t		*ire1_ill;
21989 	ill_t		*out_ill;
21990 	uint32_t 	ill_index = 0;
21991 	boolean_t	multirt_send = B_FALSE;
21992 	int		err;
21993 	ipxmit_state_t	pktxmit_state;
21994 	ip_stack_t	*ipst = ire->ire_ipst;
21995 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21996 
21997 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21998 	    "ip_wput_ire_start: q %p", q);
21999 
22000 	multicast_forward = B_FALSE;
22001 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22002 
22003 	if (ire->ire_flags & RTF_MULTIRT) {
22004 		/*
22005 		 * Multirouting case. The bucket where ire is stored
22006 		 * probably holds other RTF_MULTIRT flagged ire
22007 		 * to the destination. In this call to ip_wput_ire,
22008 		 * we attempt to send the packet through all
22009 		 * those ires. Thus, we first ensure that ire is the
22010 		 * first RTF_MULTIRT ire in the bucket,
22011 		 * before walking the ire list.
22012 		 */
22013 		ire_t *first_ire;
22014 		irb_t *irb = ire->ire_bucket;
22015 		ASSERT(irb != NULL);
22016 
22017 		/* Make sure we do not omit any multiroute ire. */
22018 		IRB_REFHOLD(irb);
22019 		for (first_ire = irb->irb_ire;
22020 		    first_ire != NULL;
22021 		    first_ire = first_ire->ire_next) {
22022 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22023 			    (first_ire->ire_addr == ire->ire_addr) &&
22024 			    !(first_ire->ire_marks &
22025 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22026 				break;
22027 		}
22028 
22029 		if ((first_ire != NULL) && (first_ire != ire)) {
22030 			IRE_REFHOLD(first_ire);
22031 			ire_refrele(ire);
22032 			ire = first_ire;
22033 			ill = ire_to_ill(ire);
22034 		}
22035 		IRB_REFRELE(irb);
22036 	}
22037 
22038 	/*
22039 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22040 	 * for performance we don't grab the mutexs in the fastpath
22041 	 */
22042 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22043 	    connp->conn_outgoing_ill != NULL) {
22044 		conn_outgoing_ill = conn_get_held_ill(connp,
22045 		    &connp->conn_outgoing_ill, &err);
22046 		if (err == ILL_LOOKUP_FAILED) {
22047 			ire_refrele(ire);
22048 			freemsg(mp);
22049 			return;
22050 		}
22051 	}
22052 
22053 	if (mp->b_datap->db_type != M_CTL) {
22054 		ipha = (ipha_t *)mp->b_rptr;
22055 	} else {
22056 		io = (ipsec_out_t *)mp->b_rptr;
22057 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22058 		ASSERT(zoneid == io->ipsec_out_zoneid);
22059 		ASSERT(zoneid != ALL_ZONES);
22060 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22061 		dst = ipha->ipha_dst;
22062 		/*
22063 		 * For the multicast case, ipsec_out carries conn_dontroute and
22064 		 * conn_multicast_loop as conn may not be available here. We
22065 		 * need this for multicast loopback and forwarding which is done
22066 		 * later in the code.
22067 		 */
22068 		if (CLASSD(dst)) {
22069 			conn_dontroute = io->ipsec_out_dontroute;
22070 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22071 			/*
22072 			 * If conn_dontroute is not set or conn_multicast_loop
22073 			 * is set, we need to do forwarding/loopback. For
22074 			 * datagrams from ip_wput_multicast, conn_dontroute is
22075 			 * set to B_TRUE and conn_multicast_loop is set to
22076 			 * B_FALSE so that we neither do forwarding nor
22077 			 * loopback.
22078 			 */
22079 			if (!conn_dontroute || conn_multicast_loop)
22080 				multicast_forward = B_TRUE;
22081 		}
22082 	}
22083 
22084 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22085 	    ire->ire_zoneid != ALL_ZONES) {
22086 		/*
22087 		 * When a zone sends a packet to another zone, we try to deliver
22088 		 * the packet under the same conditions as if the destination
22089 		 * was a real node on the network. To do so, we look for a
22090 		 * matching route in the forwarding table.
22091 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22092 		 * ip_newroute() does.
22093 		 * Note that IRE_LOCAL are special, since they are used
22094 		 * when the zoneid doesn't match in some cases. This means that
22095 		 * we need to handle ipha_src differently since ire_src_addr
22096 		 * belongs to the receiving zone instead of the sending zone.
22097 		 * When ip_restrict_interzone_loopback is set, then
22098 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22099 		 * for loopback between zones when the logical "Ethernet" would
22100 		 * have looped them back.
22101 		 */
22102 		ire_t *src_ire;
22103 
22104 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22105 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22106 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22107 		if (src_ire != NULL &&
22108 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22109 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22110 		    ire_local_same_lan(ire, src_ire))) {
22111 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22112 				ipha->ipha_src = src_ire->ire_src_addr;
22113 			ire_refrele(src_ire);
22114 		} else {
22115 			ire_refrele(ire);
22116 			if (conn_outgoing_ill != NULL)
22117 				ill_refrele(conn_outgoing_ill);
22118 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22119 			if (src_ire != NULL) {
22120 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22121 					ire_refrele(src_ire);
22122 					freemsg(mp);
22123 					return;
22124 				}
22125 				ire_refrele(src_ire);
22126 			}
22127 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22128 				/* Failed */
22129 				freemsg(mp);
22130 				return;
22131 			}
22132 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22133 			    ipst);
22134 			return;
22135 		}
22136 	}
22137 
22138 	if (mp->b_datap->db_type == M_CTL ||
22139 	    ipss->ipsec_outbound_v4_policy_present) {
22140 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22141 		    unspec_src, zoneid);
22142 		if (mp == NULL) {
22143 			ire_refrele(ire);
22144 			if (conn_outgoing_ill != NULL)
22145 				ill_refrele(conn_outgoing_ill);
22146 			return;
22147 		}
22148 		/*
22149 		 * Trusted Extensions supports all-zones interfaces, so
22150 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22151 		 * the global zone.
22152 		 */
22153 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22154 			io = (ipsec_out_t *)mp->b_rptr;
22155 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22156 			zoneid = io->ipsec_out_zoneid;
22157 		}
22158 	}
22159 
22160 	first_mp = mp;
22161 	ipsec_len = 0;
22162 
22163 	if (first_mp->b_datap->db_type == M_CTL) {
22164 		io = (ipsec_out_t *)first_mp->b_rptr;
22165 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22166 		mp = first_mp->b_cont;
22167 		ipsec_len = ipsec_out_extra_length(first_mp);
22168 		ASSERT(ipsec_len >= 0);
22169 		/* We already picked up the zoneid from the M_CTL above */
22170 		ASSERT(zoneid == io->ipsec_out_zoneid);
22171 		ASSERT(zoneid != ALL_ZONES);
22172 
22173 		/*
22174 		 * Drop M_CTL here if IPsec processing is not needed.
22175 		 * (Non-IPsec use of M_CTL extracted any information it
22176 		 * needed above).
22177 		 */
22178 		if (ipsec_len == 0) {
22179 			freeb(first_mp);
22180 			first_mp = mp;
22181 		}
22182 	}
22183 
22184 	/*
22185 	 * Fast path for ip_wput_ire
22186 	 */
22187 
22188 	ipha = (ipha_t *)mp->b_rptr;
22189 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22190 	dst = ipha->ipha_dst;
22191 
22192 	/*
22193 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22194 	 * if the socket is a SOCK_RAW type. The transport checksum should
22195 	 * be provided in the pre-built packet, so we don't need to compute it.
22196 	 * Also, other application set flags, like DF, should not be altered.
22197 	 * Other transport MUST pass down zero.
22198 	 */
22199 	ip_hdr_included = ipha->ipha_ident;
22200 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22201 
22202 	if (CLASSD(dst)) {
22203 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22204 		    ntohl(dst),
22205 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22206 		    ntohl(ire->ire_addr)));
22207 	}
22208 
22209 /* Macros to extract header fields from data already in registers */
22210 #ifdef	_BIG_ENDIAN
22211 #define	V_HLEN	(v_hlen_tos_len >> 24)
22212 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22213 #define	PROTO	(ttl_protocol & 0xFF)
22214 #else
22215 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22216 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22217 #define	PROTO	(ttl_protocol >> 8)
22218 #endif
22219 
22220 	orig_src = src = ipha->ipha_src;
22221 	/* (The loop back to "another" is explained down below.) */
22222 another:;
22223 	/*
22224 	 * Assign an ident value for this packet.  We assign idents on
22225 	 * a per destination basis out of the IRE.  There could be
22226 	 * other threads targeting the same destination, so we have to
22227 	 * arrange for a atomic increment.  Note that we use a 32-bit
22228 	 * atomic add because it has better performance than its
22229 	 * 16-bit sibling.
22230 	 *
22231 	 * If running in cluster mode and if the source address
22232 	 * belongs to a replicated service then vector through
22233 	 * cl_inet_ipident vector to allocate ip identifier
22234 	 * NOTE: This is a contract private interface with the
22235 	 * clustering group.
22236 	 */
22237 	clusterwide = 0;
22238 	if (cl_inet_ipident) {
22239 		ASSERT(cl_inet_isclusterwide);
22240 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22241 
22242 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22243 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22244 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22245 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22246 			    (uint8_t *)(uintptr_t)dst, NULL);
22247 			clusterwide = 1;
22248 		}
22249 	}
22250 	if (!clusterwide) {
22251 		ipha->ipha_ident =
22252 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22253 	}
22254 
22255 #ifndef _BIG_ENDIAN
22256 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22257 #endif
22258 
22259 	/*
22260 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22261 	 * This is needed to obey conn_unspec_src when packets go through
22262 	 * ip_newroute + arp.
22263 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22264 	 */
22265 	if (src == INADDR_ANY && !unspec_src) {
22266 		/*
22267 		 * Assign the appropriate source address from the IRE if none
22268 		 * was specified.
22269 		 */
22270 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22271 
22272 		src = ire->ire_src_addr;
22273 		if (connp == NULL) {
22274 			ip1dbg(("ip_wput_ire: no connp and no src "
22275 			    "address for dst 0x%x, using src 0x%x\n",
22276 			    ntohl(dst),
22277 			    ntohl(src)));
22278 		}
22279 		ipha->ipha_src = src;
22280 	}
22281 	stq = ire->ire_stq;
22282 
22283 	/*
22284 	 * We only allow ire chains for broadcasts since there will
22285 	 * be multiple IRE_CACHE entries for the same multicast
22286 	 * address (one per ipif).
22287 	 */
22288 	next_mp = NULL;
22289 
22290 	/* broadcast packet */
22291 	if (ire->ire_type == IRE_BROADCAST)
22292 		goto broadcast;
22293 
22294 	/* loopback ? */
22295 	if (stq == NULL)
22296 		goto nullstq;
22297 
22298 	/* The ill_index for outbound ILL */
22299 	ill_index = Q_TO_INDEX(stq);
22300 
22301 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22302 	ttl_protocol = ((uint16_t *)ipha)[4];
22303 
22304 	/* pseudo checksum (do it in parts for IP header checksum) */
22305 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22306 
22307 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22308 		queue_t *dev_q = stq->q_next;
22309 
22310 		/*
22311 		 * For DIRECT_CAPABLE, we do flow control at
22312 		 * the time of sending the packet. See
22313 		 * ILL_SEND_TX().
22314 		 */
22315 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22316 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22317 			goto blocked;
22318 
22319 		if ((PROTO == IPPROTO_UDP) &&
22320 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22321 			hlen = (V_HLEN & 0xF) << 2;
22322 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22323 			if (*up != 0) {
22324 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22325 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22326 				/* Software checksum? */
22327 				if (DB_CKSUMFLAGS(mp) == 0) {
22328 					IP_STAT(ipst, ip_out_sw_cksum);
22329 					IP_STAT_UPDATE(ipst,
22330 					    ip_udp_out_sw_cksum_bytes,
22331 					    LENGTH - hlen);
22332 				}
22333 			}
22334 		}
22335 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22336 		hlen = (V_HLEN & 0xF) << 2;
22337 		if (PROTO == IPPROTO_TCP) {
22338 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22339 			/*
22340 			 * The packet header is processed once and for all, even
22341 			 * in the multirouting case. We disable hardware
22342 			 * checksum if the packet is multirouted, as it will be
22343 			 * replicated via several interfaces, and not all of
22344 			 * them may have this capability.
22345 			 */
22346 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22347 			    LENGTH, max_frag, ipsec_len, cksum);
22348 			/* Software checksum? */
22349 			if (DB_CKSUMFLAGS(mp) == 0) {
22350 				IP_STAT(ipst, ip_out_sw_cksum);
22351 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22352 				    LENGTH - hlen);
22353 			}
22354 		} else {
22355 			sctp_hdr_t	*sctph;
22356 
22357 			ASSERT(PROTO == IPPROTO_SCTP);
22358 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22359 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22360 			/*
22361 			 * Zero out the checksum field to ensure proper
22362 			 * checksum calculation.
22363 			 */
22364 			sctph->sh_chksum = 0;
22365 #ifdef	DEBUG
22366 			if (!skip_sctp_cksum)
22367 #endif
22368 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22369 		}
22370 	}
22371 
22372 	/*
22373 	 * If this is a multicast packet and originated from ip_wput
22374 	 * we need to do loopback and forwarding checks. If it comes
22375 	 * from ip_wput_multicast, we SHOULD not do this.
22376 	 */
22377 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22378 
22379 	/* checksum */
22380 	cksum += ttl_protocol;
22381 
22382 	/* fragment the packet */
22383 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22384 		goto fragmentit;
22385 	/*
22386 	 * Don't use frag_flag if packet is pre-built or source
22387 	 * routed or if multicast (since multicast packets do
22388 	 * not solicit ICMP "packet too big" messages).
22389 	 */
22390 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22391 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22392 	    !ip_source_route_included(ipha)) &&
22393 	    !CLASSD(ipha->ipha_dst))
22394 		ipha->ipha_fragment_offset_and_flags |=
22395 		    htons(ire->ire_frag_flag);
22396 
22397 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22398 		/* calculate IP header checksum */
22399 		cksum += ipha->ipha_ident;
22400 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22401 		cksum += ipha->ipha_fragment_offset_and_flags;
22402 
22403 		/* IP options present */
22404 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22405 		if (hlen)
22406 			goto checksumoptions;
22407 
22408 		/* calculate hdr checksum */
22409 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22410 		cksum = ~(cksum + (cksum >> 16));
22411 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22412 	}
22413 	if (ipsec_len != 0) {
22414 		/*
22415 		 * We will do the rest of the processing after
22416 		 * we come back from IPsec in ip_wput_ipsec_out().
22417 		 */
22418 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22419 
22420 		io = (ipsec_out_t *)first_mp->b_rptr;
22421 		io->ipsec_out_ill_index =
22422 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22423 		ipsec_out_process(q, first_mp, ire, 0);
22424 		ire_refrele(ire);
22425 		if (conn_outgoing_ill != NULL)
22426 			ill_refrele(conn_outgoing_ill);
22427 		return;
22428 	}
22429 
22430 	/*
22431 	 * In most cases, the emission loop below is entered only
22432 	 * once. Only in the case where the ire holds the
22433 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22434 	 * flagged ires in the bucket, and send the packet
22435 	 * through all crossed RTF_MULTIRT routes.
22436 	 */
22437 	if (ire->ire_flags & RTF_MULTIRT) {
22438 		multirt_send = B_TRUE;
22439 	}
22440 	do {
22441 		if (multirt_send) {
22442 			irb_t *irb;
22443 			/*
22444 			 * We are in a multiple send case, need to get
22445 			 * the next ire and make a duplicate of the packet.
22446 			 * ire1 holds here the next ire to process in the
22447 			 * bucket. If multirouting is expected,
22448 			 * any non-RTF_MULTIRT ire that has the
22449 			 * right destination address is ignored.
22450 			 */
22451 			irb = ire->ire_bucket;
22452 			ASSERT(irb != NULL);
22453 
22454 			IRB_REFHOLD(irb);
22455 			for (ire1 = ire->ire_next;
22456 			    ire1 != NULL;
22457 			    ire1 = ire1->ire_next) {
22458 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22459 					continue;
22460 				if (ire1->ire_addr != ire->ire_addr)
22461 					continue;
22462 				if (ire1->ire_marks &
22463 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22464 					continue;
22465 
22466 				/* Got one */
22467 				IRE_REFHOLD(ire1);
22468 				break;
22469 			}
22470 			IRB_REFRELE(irb);
22471 
22472 			if (ire1 != NULL) {
22473 				next_mp = copyb(mp);
22474 				if ((next_mp == NULL) ||
22475 				    ((mp->b_cont != NULL) &&
22476 				    ((next_mp->b_cont =
22477 				    dupmsg(mp->b_cont)) == NULL))) {
22478 					freemsg(next_mp);
22479 					next_mp = NULL;
22480 					ire_refrele(ire1);
22481 					ire1 = NULL;
22482 				}
22483 			}
22484 
22485 			/* Last multiroute ire; don't loop anymore. */
22486 			if (ire1 == NULL) {
22487 				multirt_send = B_FALSE;
22488 			}
22489 		}
22490 
22491 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22492 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22493 		    mblk_t *, mp);
22494 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22495 		    ipst->ips_ipv4firewall_physical_out,
22496 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22497 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22498 
22499 		if (mp == NULL)
22500 			goto release_ire_and_ill;
22501 
22502 		if (ipst->ips_ip4_observe.he_interested) {
22503 			zoneid_t szone;
22504 
22505 			/*
22506 			 * On the outbound path the destination zone will be
22507 			 * unknown as we're sending this packet out on the
22508 			 * wire.
22509 			 */
22510 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22511 			    ALL_ZONES);
22512 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22513 			    ire->ire_ipif->ipif_ill, ipst);
22514 		}
22515 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22516 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22517 
22518 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22519 
22520 		if ((pktxmit_state == SEND_FAILED) ||
22521 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22522 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22523 			    "- packet dropped\n"));
22524 release_ire_and_ill:
22525 			ire_refrele(ire);
22526 			if (next_mp != NULL) {
22527 				freemsg(next_mp);
22528 				ire_refrele(ire1);
22529 			}
22530 			if (conn_outgoing_ill != NULL)
22531 				ill_refrele(conn_outgoing_ill);
22532 			return;
22533 		}
22534 
22535 		if (CLASSD(dst)) {
22536 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22537 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22538 			    LENGTH);
22539 		}
22540 
22541 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22542 		    "ip_wput_ire_end: q %p (%S)",
22543 		    q, "last copy out");
22544 		IRE_REFRELE(ire);
22545 
22546 		if (multirt_send) {
22547 			ASSERT(ire1);
22548 			/*
22549 			 * Proceed with the next RTF_MULTIRT ire,
22550 			 * Also set up the send-to queue accordingly.
22551 			 */
22552 			ire = ire1;
22553 			ire1 = NULL;
22554 			stq = ire->ire_stq;
22555 			mp = next_mp;
22556 			next_mp = NULL;
22557 			ipha = (ipha_t *)mp->b_rptr;
22558 			ill_index = Q_TO_INDEX(stq);
22559 			ill = (ill_t *)stq->q_ptr;
22560 		}
22561 	} while (multirt_send);
22562 	if (conn_outgoing_ill != NULL)
22563 		ill_refrele(conn_outgoing_ill);
22564 	return;
22565 
22566 	/*
22567 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22568 	 */
22569 broadcast:
22570 	{
22571 		/*
22572 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22573 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22574 		 * can be overridden stack-wide through the ip_broadcast_ttl
22575 		 * ndd tunable, or on a per-connection basis through the
22576 		 * IP_BROADCAST_TTL socket option.
22577 		 *
22578 		 * In the event that we are replying to incoming ICMP packets,
22579 		 * connp could be NULL.
22580 		 */
22581 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22582 		if (connp != NULL) {
22583 			if (connp->conn_dontroute)
22584 				ipha->ipha_ttl = 1;
22585 			else if (connp->conn_broadcast_ttl != 0)
22586 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22587 		}
22588 
22589 		/*
22590 		 * Note that we are not doing a IRB_REFHOLD here.
22591 		 * Actually we don't care if the list changes i.e
22592 		 * if somebody deletes an IRE from the list while
22593 		 * we drop the lock, the next time we come around
22594 		 * ire_next will be NULL and hence we won't send
22595 		 * out multiple copies which is fine.
22596 		 */
22597 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22598 		ire1 = ire->ire_next;
22599 		if (conn_outgoing_ill != NULL) {
22600 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22601 				ASSERT(ire1 == ire->ire_next);
22602 				if (ire1 != NULL && ire1->ire_addr == dst) {
22603 					ire_refrele(ire);
22604 					ire = ire1;
22605 					IRE_REFHOLD(ire);
22606 					ire1 = ire->ire_next;
22607 					continue;
22608 				}
22609 				rw_exit(&ire->ire_bucket->irb_lock);
22610 				/* Did not find a matching ill */
22611 				ip1dbg(("ip_wput_ire: broadcast with no "
22612 				    "matching IP_BOUND_IF ill %s dst %x\n",
22613 				    conn_outgoing_ill->ill_name, dst));
22614 				freemsg(first_mp);
22615 				if (ire != NULL)
22616 					ire_refrele(ire);
22617 				ill_refrele(conn_outgoing_ill);
22618 				return;
22619 			}
22620 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22621 			/*
22622 			 * If the next IRE has the same address and is not one
22623 			 * of the two copies that we need to send, try to see
22624 			 * whether this copy should be sent at all. This
22625 			 * assumes that we insert loopbacks first and then
22626 			 * non-loopbacks. This is acheived by inserting the
22627 			 * loopback always before non-loopback.
22628 			 * This is used to send a single copy of a broadcast
22629 			 * packet out all physical interfaces that have an
22630 			 * matching IRE_BROADCAST while also looping
22631 			 * back one copy (to ip_wput_local) for each
22632 			 * matching physical interface. However, we avoid
22633 			 * sending packets out different logical that match by
22634 			 * having ipif_up/ipif_down supress duplicate
22635 			 * IRE_BROADCASTS.
22636 			 *
22637 			 * This feature is currently used to get broadcasts
22638 			 * sent to multiple interfaces, when the broadcast
22639 			 * address being used applies to multiple interfaces.
22640 			 * For example, a whole net broadcast will be
22641 			 * replicated on every connected subnet of
22642 			 * the target net.
22643 			 *
22644 			 * Each zone has its own set of IRE_BROADCASTs, so that
22645 			 * we're able to distribute inbound packets to multiple
22646 			 * zones who share a broadcast address. We avoid looping
22647 			 * back outbound packets in different zones but on the
22648 			 * same ill, as the application would see duplicates.
22649 			 *
22650 			 * This logic assumes that ire_add_v4() groups the
22651 			 * IRE_BROADCAST entries so that those with the same
22652 			 * ire_addr are kept together.
22653 			 */
22654 			ire_ill = ire->ire_ipif->ipif_ill;
22655 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22656 				while (ire1 != NULL && ire1->ire_addr == dst) {
22657 					ire1_ill = ire1->ire_ipif->ipif_ill;
22658 					if (ire1_ill != ire_ill)
22659 						break;
22660 					ire1 = ire1->ire_next;
22661 				}
22662 			}
22663 		}
22664 		ASSERT(multirt_send == B_FALSE);
22665 		if (ire1 != NULL && ire1->ire_addr == dst) {
22666 			if ((ire->ire_flags & RTF_MULTIRT) &&
22667 			    (ire1->ire_flags & RTF_MULTIRT)) {
22668 				/*
22669 				 * We are in the multirouting case.
22670 				 * The message must be sent at least
22671 				 * on both ires. These ires have been
22672 				 * inserted AFTER the standard ones
22673 				 * in ip_rt_add(). There are thus no
22674 				 * other ire entries for the destination
22675 				 * address in the rest of the bucket
22676 				 * that do not have the RTF_MULTIRT
22677 				 * flag. We don't process a copy
22678 				 * of the message here. This will be
22679 				 * done in the final sending loop.
22680 				 */
22681 				multirt_send = B_TRUE;
22682 			} else {
22683 				next_mp = ip_copymsg(first_mp);
22684 				if (next_mp != NULL)
22685 					IRE_REFHOLD(ire1);
22686 			}
22687 		}
22688 		rw_exit(&ire->ire_bucket->irb_lock);
22689 	}
22690 
22691 	if (stq) {
22692 		/*
22693 		 * A non-NULL send-to queue means this packet is going
22694 		 * out of this machine.
22695 		 */
22696 		out_ill = (ill_t *)stq->q_ptr;
22697 
22698 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22699 		ttl_protocol = ((uint16_t *)ipha)[4];
22700 		/*
22701 		 * We accumulate the pseudo header checksum in cksum.
22702 		 * This is pretty hairy code, so watch close.  One
22703 		 * thing to keep in mind is that UDP and TCP have
22704 		 * stored their respective datagram lengths in their
22705 		 * checksum fields.  This lines things up real nice.
22706 		 */
22707 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22708 		    (src >> 16) + (src & 0xFFFF);
22709 		/*
22710 		 * We assume the udp checksum field contains the
22711 		 * length, so to compute the pseudo header checksum,
22712 		 * all we need is the protocol number and src/dst.
22713 		 */
22714 		/* Provide the checksums for UDP and TCP. */
22715 		if ((PROTO == IPPROTO_TCP) &&
22716 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22717 			/* hlen gets the number of uchar_ts in the IP header */
22718 			hlen = (V_HLEN & 0xF) << 2;
22719 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22720 			IP_STAT(ipst, ip_out_sw_cksum);
22721 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22722 			    LENGTH - hlen);
22723 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22724 		} else if (PROTO == IPPROTO_SCTP &&
22725 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22726 			sctp_hdr_t	*sctph;
22727 
22728 			hlen = (V_HLEN & 0xF) << 2;
22729 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22730 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22731 			sctph->sh_chksum = 0;
22732 #ifdef	DEBUG
22733 			if (!skip_sctp_cksum)
22734 #endif
22735 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22736 		} else {
22737 			queue_t	*dev_q = stq->q_next;
22738 
22739 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22740 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22741 blocked:
22742 				ipha->ipha_ident = ip_hdr_included;
22743 				/*
22744 				 * If we don't have a conn to apply
22745 				 * backpressure, free the message.
22746 				 * In the ire_send path, we don't know
22747 				 * the position to requeue the packet. Rather
22748 				 * than reorder packets, we just drop this
22749 				 * packet.
22750 				 */
22751 				if (ipst->ips_ip_output_queue &&
22752 				    connp != NULL &&
22753 				    caller != IRE_SEND) {
22754 					if (caller == IP_WSRV) {
22755 						idl_tx_list_t *idl_txl;
22756 
22757 						idl_txl =
22758 						    &ipst->ips_idl_tx_list[0];
22759 						connp->conn_did_putbq = 1;
22760 						(void) putbq(connp->conn_wq,
22761 						    first_mp);
22762 						conn_drain_insert(connp,
22763 						    idl_txl);
22764 						/*
22765 						 * This is the service thread,
22766 						 * and the queue is already
22767 						 * noenabled. The check for
22768 						 * canput and the putbq is not
22769 						 * atomic. So we need to check
22770 						 * again.
22771 						 */
22772 						if (canput(stq->q_next))
22773 							connp->conn_did_putbq
22774 							    = 0;
22775 						IP_STAT(ipst, ip_conn_flputbq);
22776 					} else {
22777 						/*
22778 						 * We are not the service proc.
22779 						 * ip_wsrv will be scheduled or
22780 						 * is already running.
22781 						 */
22782 
22783 						(void) putq(connp->conn_wq,
22784 						    first_mp);
22785 					}
22786 				} else {
22787 					out_ill = (ill_t *)stq->q_ptr;
22788 					BUMP_MIB(out_ill->ill_ip_mib,
22789 					    ipIfStatsOutDiscards);
22790 					freemsg(first_mp);
22791 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22792 					    "ip_wput_ire_end: q %p (%S)",
22793 					    q, "discard");
22794 				}
22795 				ire_refrele(ire);
22796 				if (next_mp) {
22797 					ire_refrele(ire1);
22798 					freemsg(next_mp);
22799 				}
22800 				if (conn_outgoing_ill != NULL)
22801 					ill_refrele(conn_outgoing_ill);
22802 				return;
22803 			}
22804 			if ((PROTO == IPPROTO_UDP) &&
22805 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22806 				/*
22807 				 * hlen gets the number of uchar_ts in the
22808 				 * IP header
22809 				 */
22810 				hlen = (V_HLEN & 0xF) << 2;
22811 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22812 				max_frag = ire->ire_max_frag;
22813 				if (*up != 0) {
22814 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22815 					    up, PROTO, hlen, LENGTH, max_frag,
22816 					    ipsec_len, cksum);
22817 					/* Software checksum? */
22818 					if (DB_CKSUMFLAGS(mp) == 0) {
22819 						IP_STAT(ipst, ip_out_sw_cksum);
22820 						IP_STAT_UPDATE(ipst,
22821 						    ip_udp_out_sw_cksum_bytes,
22822 						    LENGTH - hlen);
22823 					}
22824 				}
22825 			}
22826 		}
22827 		/*
22828 		 * Need to do this even when fragmenting. The local
22829 		 * loopback can be done without computing checksums
22830 		 * but forwarding out other interface must be done
22831 		 * after the IP checksum (and ULP checksums) have been
22832 		 * computed.
22833 		 *
22834 		 * NOTE : multicast_forward is set only if this packet
22835 		 * originated from ip_wput. For packets originating from
22836 		 * ip_wput_multicast, it is not set.
22837 		 */
22838 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22839 multi_loopback:
22840 			ip2dbg(("ip_wput: multicast, loop %d\n",
22841 			    conn_multicast_loop));
22842 
22843 			/*  Forget header checksum offload */
22844 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22845 
22846 			/*
22847 			 * Local loopback of multicasts?  Check the
22848 			 * ill.
22849 			 *
22850 			 * Note that the loopback function will not come
22851 			 * in through ip_rput - it will only do the
22852 			 * client fanout thus we need to do an mforward
22853 			 * as well.  The is different from the BSD
22854 			 * logic.
22855 			 */
22856 			if (ill != NULL) {
22857 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22858 				    ALL_ZONES) != NULL) {
22859 					/*
22860 					 * Pass along the virtual output q.
22861 					 * ip_wput_local() will distribute the
22862 					 * packet to all the matching zones,
22863 					 * except the sending zone when
22864 					 * IP_MULTICAST_LOOP is false.
22865 					 */
22866 					ip_multicast_loopback(q, ill, first_mp,
22867 					    conn_multicast_loop ? 0 :
22868 					    IP_FF_NO_MCAST_LOOP, zoneid);
22869 				}
22870 			}
22871 			if (ipha->ipha_ttl == 0) {
22872 				/*
22873 				 * 0 => only to this host i.e. we are
22874 				 * done. We are also done if this was the
22875 				 * loopback interface since it is sufficient
22876 				 * to loopback one copy of a multicast packet.
22877 				 */
22878 				freemsg(first_mp);
22879 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22880 				    "ip_wput_ire_end: q %p (%S)",
22881 				    q, "loopback");
22882 				ire_refrele(ire);
22883 				if (conn_outgoing_ill != NULL)
22884 					ill_refrele(conn_outgoing_ill);
22885 				return;
22886 			}
22887 			/*
22888 			 * ILLF_MULTICAST is checked in ip_newroute
22889 			 * i.e. we don't need to check it here since
22890 			 * all IRE_CACHEs come from ip_newroute.
22891 			 * For multicast traffic, SO_DONTROUTE is interpreted
22892 			 * to mean only send the packet out the interface
22893 			 * (optionally specified with IP_MULTICAST_IF)
22894 			 * and do not forward it out additional interfaces.
22895 			 * RSVP and the rsvp daemon is an example of a
22896 			 * protocol and user level process that
22897 			 * handles it's own routing. Hence, it uses the
22898 			 * SO_DONTROUTE option to accomplish this.
22899 			 */
22900 
22901 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22902 			    ill != NULL) {
22903 				/* Unconditionally redo the checksum */
22904 				ipha->ipha_hdr_checksum = 0;
22905 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22906 
22907 				/*
22908 				 * If this needs to go out secure, we need
22909 				 * to wait till we finish the IPsec
22910 				 * processing.
22911 				 */
22912 				if (ipsec_len == 0 &&
22913 				    ip_mforward(ill, ipha, mp)) {
22914 					freemsg(first_mp);
22915 					ip1dbg(("ip_wput: mforward failed\n"));
22916 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22917 					    "ip_wput_ire_end: q %p (%S)",
22918 					    q, "mforward failed");
22919 					ire_refrele(ire);
22920 					if (conn_outgoing_ill != NULL)
22921 						ill_refrele(conn_outgoing_ill);
22922 					return;
22923 				}
22924 			}
22925 		}
22926 		max_frag = ire->ire_max_frag;
22927 		cksum += ttl_protocol;
22928 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22929 			/* No fragmentation required for this one. */
22930 			/*
22931 			 * Don't use frag_flag if packet is pre-built or source
22932 			 * routed or if multicast (since multicast packets do
22933 			 * not solicit ICMP "packet too big" messages).
22934 			 */
22935 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22936 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22937 			    !ip_source_route_included(ipha)) &&
22938 			    !CLASSD(ipha->ipha_dst))
22939 				ipha->ipha_fragment_offset_and_flags |=
22940 				    htons(ire->ire_frag_flag);
22941 
22942 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22943 				/* Complete the IP header checksum. */
22944 				cksum += ipha->ipha_ident;
22945 				cksum += (v_hlen_tos_len >> 16)+
22946 				    (v_hlen_tos_len & 0xFFFF);
22947 				cksum += ipha->ipha_fragment_offset_and_flags;
22948 				hlen = (V_HLEN & 0xF) -
22949 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22950 				if (hlen) {
22951 checksumoptions:
22952 					/*
22953 					 * Account for the IP Options in the IP
22954 					 * header checksum.
22955 					 */
22956 					up = (uint16_t *)(rptr+
22957 					    IP_SIMPLE_HDR_LENGTH);
22958 					do {
22959 						cksum += up[0];
22960 						cksum += up[1];
22961 						up += 2;
22962 					} while (--hlen);
22963 				}
22964 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22965 				cksum = ~(cksum + (cksum >> 16));
22966 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22967 			}
22968 			if (ipsec_len != 0) {
22969 				ipsec_out_process(q, first_mp, ire, ill_index);
22970 				if (!next_mp) {
22971 					ire_refrele(ire);
22972 					if (conn_outgoing_ill != NULL)
22973 						ill_refrele(conn_outgoing_ill);
22974 					return;
22975 				}
22976 				goto next;
22977 			}
22978 
22979 			/*
22980 			 * multirt_send has already been handled
22981 			 * for broadcast, but not yet for multicast
22982 			 * or IP options.
22983 			 */
22984 			if (next_mp == NULL) {
22985 				if (ire->ire_flags & RTF_MULTIRT) {
22986 					multirt_send = B_TRUE;
22987 				}
22988 			}
22989 
22990 			/*
22991 			 * In most cases, the emission loop below is
22992 			 * entered only once. Only in the case where
22993 			 * the ire holds the RTF_MULTIRT flag, do we loop
22994 			 * to process all RTF_MULTIRT ires in the bucket,
22995 			 * and send the packet through all crossed
22996 			 * RTF_MULTIRT routes.
22997 			 */
22998 			do {
22999 				if (multirt_send) {
23000 					irb_t *irb;
23001 
23002 					irb = ire->ire_bucket;
23003 					ASSERT(irb != NULL);
23004 					/*
23005 					 * We are in a multiple send case,
23006 					 * need to get the next IRE and make
23007 					 * a duplicate of the packet.
23008 					 */
23009 					IRB_REFHOLD(irb);
23010 					for (ire1 = ire->ire_next;
23011 					    ire1 != NULL;
23012 					    ire1 = ire1->ire_next) {
23013 						if (!(ire1->ire_flags &
23014 						    RTF_MULTIRT))
23015 							continue;
23016 
23017 						if (ire1->ire_addr !=
23018 						    ire->ire_addr)
23019 							continue;
23020 
23021 						if (ire1->ire_marks &
23022 						    (IRE_MARK_CONDEMNED |
23023 						    IRE_MARK_TESTHIDDEN))
23024 							continue;
23025 
23026 						/* Got one */
23027 						IRE_REFHOLD(ire1);
23028 						break;
23029 					}
23030 					IRB_REFRELE(irb);
23031 
23032 					if (ire1 != NULL) {
23033 						next_mp = copyb(mp);
23034 						if ((next_mp == NULL) ||
23035 						    ((mp->b_cont != NULL) &&
23036 						    ((next_mp->b_cont =
23037 						    dupmsg(mp->b_cont))
23038 						    == NULL))) {
23039 							freemsg(next_mp);
23040 							next_mp = NULL;
23041 							ire_refrele(ire1);
23042 							ire1 = NULL;
23043 						}
23044 					}
23045 
23046 					/*
23047 					 * Last multiroute ire; don't loop
23048 					 * anymore. The emission is over
23049 					 * and next_mp is NULL.
23050 					 */
23051 					if (ire1 == NULL) {
23052 						multirt_send = B_FALSE;
23053 					}
23054 				}
23055 
23056 				out_ill = ire_to_ill(ire);
23057 				DTRACE_PROBE4(ip4__physical__out__start,
23058 				    ill_t *, NULL,
23059 				    ill_t *, out_ill,
23060 				    ipha_t *, ipha, mblk_t *, mp);
23061 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23062 				    ipst->ips_ipv4firewall_physical_out,
23063 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23064 				DTRACE_PROBE1(ip4__physical__out__end,
23065 				    mblk_t *, mp);
23066 				if (mp == NULL)
23067 					goto release_ire_and_ill_2;
23068 
23069 				ASSERT(ipsec_len == 0);
23070 				mp->b_prev =
23071 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23072 				DTRACE_PROBE2(ip__xmit__2,
23073 				    mblk_t *, mp, ire_t *, ire);
23074 				pktxmit_state = ip_xmit_v4(mp, ire,
23075 				    NULL, B_TRUE, connp);
23076 				if ((pktxmit_state == SEND_FAILED) ||
23077 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23078 release_ire_and_ill_2:
23079 					if (next_mp) {
23080 						freemsg(next_mp);
23081 						ire_refrele(ire1);
23082 					}
23083 					ire_refrele(ire);
23084 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23085 					    "ip_wput_ire_end: q %p (%S)",
23086 					    q, "discard MDATA");
23087 					if (conn_outgoing_ill != NULL)
23088 						ill_refrele(conn_outgoing_ill);
23089 					return;
23090 				}
23091 
23092 				if (CLASSD(dst)) {
23093 					BUMP_MIB(out_ill->ill_ip_mib,
23094 					    ipIfStatsHCOutMcastPkts);
23095 					UPDATE_MIB(out_ill->ill_ip_mib,
23096 					    ipIfStatsHCOutMcastOctets,
23097 					    LENGTH);
23098 				} else if (ire->ire_type == IRE_BROADCAST) {
23099 					BUMP_MIB(out_ill->ill_ip_mib,
23100 					    ipIfStatsHCOutBcastPkts);
23101 				}
23102 
23103 				if (multirt_send) {
23104 					/*
23105 					 * We are in a multiple send case,
23106 					 * need to re-enter the sending loop
23107 					 * using the next ire.
23108 					 */
23109 					ire_refrele(ire);
23110 					ire = ire1;
23111 					stq = ire->ire_stq;
23112 					mp = next_mp;
23113 					next_mp = NULL;
23114 					ipha = (ipha_t *)mp->b_rptr;
23115 					ill_index = Q_TO_INDEX(stq);
23116 				}
23117 			} while (multirt_send);
23118 
23119 			if (!next_mp) {
23120 				/*
23121 				 * Last copy going out (the ultra-common
23122 				 * case).  Note that we intentionally replicate
23123 				 * the putnext rather than calling it before
23124 				 * the next_mp check in hopes of a little
23125 				 * tail-call action out of the compiler.
23126 				 */
23127 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23128 				    "ip_wput_ire_end: q %p (%S)",
23129 				    q, "last copy out(1)");
23130 				ire_refrele(ire);
23131 				if (conn_outgoing_ill != NULL)
23132 					ill_refrele(conn_outgoing_ill);
23133 				return;
23134 			}
23135 			/* More copies going out below. */
23136 		} else {
23137 			int offset;
23138 fragmentit:
23139 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23140 			/*
23141 			 * If this would generate a icmp_frag_needed message,
23142 			 * we need to handle it before we do the IPsec
23143 			 * processing. Otherwise, we need to strip the IPsec
23144 			 * headers before we send up the message to the ULPs
23145 			 * which becomes messy and difficult.
23146 			 */
23147 			if (ipsec_len != 0) {
23148 				if ((max_frag < (unsigned int)(LENGTH +
23149 				    ipsec_len)) && (offset & IPH_DF)) {
23150 					out_ill = (ill_t *)stq->q_ptr;
23151 					BUMP_MIB(out_ill->ill_ip_mib,
23152 					    ipIfStatsOutFragFails);
23153 					BUMP_MIB(out_ill->ill_ip_mib,
23154 					    ipIfStatsOutFragReqds);
23155 					ipha->ipha_hdr_checksum = 0;
23156 					ipha->ipha_hdr_checksum =
23157 					    (uint16_t)ip_csum_hdr(ipha);
23158 					icmp_frag_needed(ire->ire_stq, first_mp,
23159 					    max_frag, zoneid, ipst);
23160 					if (!next_mp) {
23161 						ire_refrele(ire);
23162 						if (conn_outgoing_ill != NULL) {
23163 							ill_refrele(
23164 							    conn_outgoing_ill);
23165 						}
23166 						return;
23167 					}
23168 				} else {
23169 					/*
23170 					 * This won't cause a icmp_frag_needed
23171 					 * message. to be generated. Send it on
23172 					 * the wire. Note that this could still
23173 					 * cause fragmentation and all we
23174 					 * do is the generation of the message
23175 					 * to the ULP if needed before IPsec.
23176 					 */
23177 					if (!next_mp) {
23178 						ipsec_out_process(q, first_mp,
23179 						    ire, ill_index);
23180 						TRACE_2(TR_FAC_IP,
23181 						    TR_IP_WPUT_IRE_END,
23182 						    "ip_wput_ire_end: q %p "
23183 						    "(%S)", q,
23184 						    "last ipsec_out_process");
23185 						ire_refrele(ire);
23186 						if (conn_outgoing_ill != NULL) {
23187 							ill_refrele(
23188 							    conn_outgoing_ill);
23189 						}
23190 						return;
23191 					}
23192 					ipsec_out_process(q, first_mp,
23193 					    ire, ill_index);
23194 				}
23195 			} else {
23196 				/*
23197 				 * Initiate IPPF processing. For
23198 				 * fragmentable packets we finish
23199 				 * all QOS packet processing before
23200 				 * calling:
23201 				 * ip_wput_ire_fragmentit->ip_wput_frag
23202 				 */
23203 
23204 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23205 					ip_process(IPP_LOCAL_OUT, &mp,
23206 					    ill_index);
23207 					if (mp == NULL) {
23208 						out_ill = (ill_t *)stq->q_ptr;
23209 						BUMP_MIB(out_ill->ill_ip_mib,
23210 						    ipIfStatsOutDiscards);
23211 						if (next_mp != NULL) {
23212 							freemsg(next_mp);
23213 							ire_refrele(ire1);
23214 						}
23215 						ire_refrele(ire);
23216 						TRACE_2(TR_FAC_IP,
23217 						    TR_IP_WPUT_IRE_END,
23218 						    "ip_wput_ire: q %p (%S)",
23219 						    q, "discard MDATA");
23220 						if (conn_outgoing_ill != NULL) {
23221 							ill_refrele(
23222 							    conn_outgoing_ill);
23223 						}
23224 						return;
23225 					}
23226 				}
23227 				if (!next_mp) {
23228 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23229 					    "ip_wput_ire_end: q %p (%S)",
23230 					    q, "last fragmentation");
23231 					ip_wput_ire_fragmentit(mp, ire,
23232 					    zoneid, ipst, connp);
23233 					ire_refrele(ire);
23234 					if (conn_outgoing_ill != NULL)
23235 						ill_refrele(conn_outgoing_ill);
23236 					return;
23237 				}
23238 				ip_wput_ire_fragmentit(mp, ire,
23239 				    zoneid, ipst, connp);
23240 			}
23241 		}
23242 	} else {
23243 nullstq:
23244 		/* A NULL stq means the destination address is local. */
23245 		UPDATE_OB_PKT_COUNT(ire);
23246 		ire->ire_last_used_time = lbolt;
23247 		ASSERT(ire->ire_ipif != NULL);
23248 		if (!next_mp) {
23249 			/*
23250 			 * Is there an "in" and "out" for traffic local
23251 			 * to a host (loopback)?  The code in Solaris doesn't
23252 			 * explicitly draw a line in its code for in vs out,
23253 			 * so we've had to draw a line in the sand: ip_wput_ire
23254 			 * is considered to be the "output" side and
23255 			 * ip_wput_local to be the "input" side.
23256 			 */
23257 			out_ill = ire_to_ill(ire);
23258 
23259 			/*
23260 			 * DTrace this as ip:::send.  A blocked packet will
23261 			 * fire the send probe, but not the receive probe.
23262 			 */
23263 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23264 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23265 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23266 
23267 			DTRACE_PROBE4(ip4__loopback__out__start,
23268 			    ill_t *, NULL, ill_t *, out_ill,
23269 			    ipha_t *, ipha, mblk_t *, first_mp);
23270 
23271 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23272 			    ipst->ips_ipv4firewall_loopback_out,
23273 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23274 
23275 			DTRACE_PROBE1(ip4__loopback__out_end,
23276 			    mblk_t *, first_mp);
23277 
23278 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23279 			    "ip_wput_ire_end: q %p (%S)",
23280 			    q, "local address");
23281 
23282 			if (first_mp != NULL)
23283 				ip_wput_local(q, out_ill, ipha,
23284 				    first_mp, ire, 0, ire->ire_zoneid);
23285 			ire_refrele(ire);
23286 			if (conn_outgoing_ill != NULL)
23287 				ill_refrele(conn_outgoing_ill);
23288 			return;
23289 		}
23290 
23291 		out_ill = ire_to_ill(ire);
23292 
23293 		/*
23294 		 * DTrace this as ip:::send.  A blocked packet will fire the
23295 		 * send probe, but not the receive probe.
23296 		 */
23297 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23298 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23299 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23300 
23301 		DTRACE_PROBE4(ip4__loopback__out__start,
23302 		    ill_t *, NULL, ill_t *, out_ill,
23303 		    ipha_t *, ipha, mblk_t *, first_mp);
23304 
23305 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23306 		    ipst->ips_ipv4firewall_loopback_out,
23307 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23308 
23309 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23310 
23311 		if (first_mp != NULL)
23312 			ip_wput_local(q, out_ill, ipha,
23313 			    first_mp, ire, 0, ire->ire_zoneid);
23314 	}
23315 next:
23316 	/*
23317 	 * More copies going out to additional interfaces.
23318 	 * ire1 has already been held. We don't need the
23319 	 * "ire" anymore.
23320 	 */
23321 	ire_refrele(ire);
23322 	ire = ire1;
23323 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23324 	mp = next_mp;
23325 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23326 	ill = ire_to_ill(ire);
23327 	first_mp = mp;
23328 	if (ipsec_len != 0) {
23329 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23330 		mp = mp->b_cont;
23331 	}
23332 	dst = ire->ire_addr;
23333 	ipha = (ipha_t *)mp->b_rptr;
23334 	/*
23335 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23336 	 * Restore ipha_ident "no checksum" flag.
23337 	 */
23338 	src = orig_src;
23339 	ipha->ipha_ident = ip_hdr_included;
23340 	goto another;
23341 
23342 #undef	rptr
23343 #undef	Q_TO_INDEX
23344 }
23345 
23346 /*
23347  * Routine to allocate a message that is used to notify the ULP about MDT.
23348  * The caller may provide a pointer to the link-layer MDT capabilities,
23349  * or NULL if MDT is to be disabled on the stream.
23350  */
23351 mblk_t *
23352 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23353 {
23354 	mblk_t *mp;
23355 	ip_mdt_info_t *mdti;
23356 	ill_mdt_capab_t *idst;
23357 
23358 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23359 		DB_TYPE(mp) = M_CTL;
23360 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23361 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23362 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23363 		idst = &(mdti->mdt_capab);
23364 
23365 		/*
23366 		 * If the caller provides us with the capability, copy
23367 		 * it over into our notification message; otherwise
23368 		 * we zero out the capability portion.
23369 		 */
23370 		if (isrc != NULL)
23371 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23372 		else
23373 			bzero((caddr_t)idst, sizeof (*idst));
23374 	}
23375 	return (mp);
23376 }
23377 
23378 /*
23379  * Routine which determines whether MDT can be enabled on the destination
23380  * IRE and IPC combination, and if so, allocates and returns the MDT
23381  * notification mblk that may be used by ULP.  We also check if we need to
23382  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23383  * MDT usage in the past have been lifted.  This gets called during IP
23384  * and ULP binding.
23385  */
23386 mblk_t *
23387 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23388     ill_mdt_capab_t *mdt_cap)
23389 {
23390 	mblk_t *mp;
23391 	boolean_t rc = B_FALSE;
23392 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23393 
23394 	ASSERT(dst_ire != NULL);
23395 	ASSERT(connp != NULL);
23396 	ASSERT(mdt_cap != NULL);
23397 
23398 	/*
23399 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23400 	 * Multidata, which is handled in tcp_multisend().  This
23401 	 * is the reason why we do all these checks here, to ensure
23402 	 * that we don't enable Multidata for the cases which we
23403 	 * can't handle at the moment.
23404 	 */
23405 	do {
23406 		/* Only do TCP at the moment */
23407 		if (connp->conn_ulp != IPPROTO_TCP)
23408 			break;
23409 
23410 		/*
23411 		 * IPsec outbound policy present?  Note that we get here
23412 		 * after calling ipsec_conn_cache_policy() where the global
23413 		 * policy checking is performed.  conn_latch will be
23414 		 * non-NULL as long as there's a policy defined,
23415 		 * i.e. conn_out_enforce_policy may be NULL in such case
23416 		 * when the connection is non-secure, and hence we check
23417 		 * further if the latch refers to an outbound policy.
23418 		 */
23419 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23420 			break;
23421 
23422 		/* CGTP (multiroute) is enabled? */
23423 		if (dst_ire->ire_flags & RTF_MULTIRT)
23424 			break;
23425 
23426 		/* Outbound IPQoS enabled? */
23427 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23428 			/*
23429 			 * In this case, we disable MDT for this and all
23430 			 * future connections going over the interface.
23431 			 */
23432 			mdt_cap->ill_mdt_on = 0;
23433 			break;
23434 		}
23435 
23436 		/* socket option(s) present? */
23437 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23438 			break;
23439 
23440 		rc = B_TRUE;
23441 	/* CONSTCOND */
23442 	} while (0);
23443 
23444 	/* Remember the result */
23445 	connp->conn_mdt_ok = rc;
23446 
23447 	if (!rc)
23448 		return (NULL);
23449 	else if (!mdt_cap->ill_mdt_on) {
23450 		/*
23451 		 * If MDT has been previously turned off in the past, and we
23452 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23453 		 * then enable it for this interface.
23454 		 */
23455 		mdt_cap->ill_mdt_on = 1;
23456 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23457 		    "interface %s\n", ill_name));
23458 	}
23459 
23460 	/* Allocate the MDT info mblk */
23461 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23462 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23463 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23464 		return (NULL);
23465 	}
23466 	return (mp);
23467 }
23468 
23469 /*
23470  * Routine to allocate a message that is used to notify the ULP about LSO.
23471  * The caller may provide a pointer to the link-layer LSO capabilities,
23472  * or NULL if LSO is to be disabled on the stream.
23473  */
23474 mblk_t *
23475 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23476 {
23477 	mblk_t *mp;
23478 	ip_lso_info_t *lsoi;
23479 	ill_lso_capab_t *idst;
23480 
23481 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23482 		DB_TYPE(mp) = M_CTL;
23483 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23484 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23485 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23486 		idst = &(lsoi->lso_capab);
23487 
23488 		/*
23489 		 * If the caller provides us with the capability, copy
23490 		 * it over into our notification message; otherwise
23491 		 * we zero out the capability portion.
23492 		 */
23493 		if (isrc != NULL)
23494 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23495 		else
23496 			bzero((caddr_t)idst, sizeof (*idst));
23497 	}
23498 	return (mp);
23499 }
23500 
23501 /*
23502  * Routine which determines whether LSO can be enabled on the destination
23503  * IRE and IPC combination, and if so, allocates and returns the LSO
23504  * notification mblk that may be used by ULP.  We also check if we need to
23505  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23506  * LSO usage in the past have been lifted.  This gets called during IP
23507  * and ULP binding.
23508  */
23509 mblk_t *
23510 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23511     ill_lso_capab_t *lso_cap)
23512 {
23513 	mblk_t *mp;
23514 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23515 
23516 	ASSERT(dst_ire != NULL);
23517 	ASSERT(connp != NULL);
23518 	ASSERT(lso_cap != NULL);
23519 
23520 	connp->conn_lso_ok = B_TRUE;
23521 
23522 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23523 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23524 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23525 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23526 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23527 		connp->conn_lso_ok = B_FALSE;
23528 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23529 			/*
23530 			 * Disable LSO for this and all future connections going
23531 			 * over the interface.
23532 			 */
23533 			lso_cap->ill_lso_on = 0;
23534 		}
23535 	}
23536 
23537 	if (!connp->conn_lso_ok)
23538 		return (NULL);
23539 	else if (!lso_cap->ill_lso_on) {
23540 		/*
23541 		 * If LSO has been previously turned off in the past, and we
23542 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23543 		 * then enable it for this interface.
23544 		 */
23545 		lso_cap->ill_lso_on = 1;
23546 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23547 		    ill_name));
23548 	}
23549 
23550 	/* Allocate the LSO info mblk */
23551 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23552 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23553 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23554 
23555 	return (mp);
23556 }
23557 
23558 /*
23559  * Create destination address attribute, and fill it with the physical
23560  * destination address and SAP taken from the template DL_UNITDATA_REQ
23561  * message block.
23562  */
23563 boolean_t
23564 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23565 {
23566 	dl_unitdata_req_t *dlurp;
23567 	pattr_t *pa;
23568 	pattrinfo_t pa_info;
23569 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23570 	uint_t das_len, das_off;
23571 
23572 	ASSERT(dlmp != NULL);
23573 
23574 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23575 	das_len = dlurp->dl_dest_addr_length;
23576 	das_off = dlurp->dl_dest_addr_offset;
23577 
23578 	pa_info.type = PATTR_DSTADDRSAP;
23579 	pa_info.len = sizeof (**das) + das_len - 1;
23580 
23581 	/* create and associate the attribute */
23582 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23583 	if (pa != NULL) {
23584 		ASSERT(*das != NULL);
23585 		(*das)->addr_is_group = 0;
23586 		(*das)->addr_len = (uint8_t)das_len;
23587 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23588 	}
23589 
23590 	return (pa != NULL);
23591 }
23592 
23593 /*
23594  * Create hardware checksum attribute and fill it with the values passed.
23595  */
23596 boolean_t
23597 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23598     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23599 {
23600 	pattr_t *pa;
23601 	pattrinfo_t pa_info;
23602 
23603 	ASSERT(mmd != NULL);
23604 
23605 	pa_info.type = PATTR_HCKSUM;
23606 	pa_info.len = sizeof (pattr_hcksum_t);
23607 
23608 	/* create and associate the attribute */
23609 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23610 	if (pa != NULL) {
23611 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23612 
23613 		hck->hcksum_start_offset = start_offset;
23614 		hck->hcksum_stuff_offset = stuff_offset;
23615 		hck->hcksum_end_offset = end_offset;
23616 		hck->hcksum_flags = flags;
23617 	}
23618 	return (pa != NULL);
23619 }
23620 
23621 /*
23622  * Create zerocopy attribute and fill it with the specified flags
23623  */
23624 boolean_t
23625 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23626 {
23627 	pattr_t *pa;
23628 	pattrinfo_t pa_info;
23629 
23630 	ASSERT(mmd != NULL);
23631 	pa_info.type = PATTR_ZCOPY;
23632 	pa_info.len = sizeof (pattr_zcopy_t);
23633 
23634 	/* create and associate the attribute */
23635 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23636 	if (pa != NULL) {
23637 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23638 
23639 		zcopy->zcopy_flags = flags;
23640 	}
23641 	return (pa != NULL);
23642 }
23643 
23644 /*
23645  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23646  * block chain. We could rewrite to handle arbitrary message block chains but
23647  * that would make the code complicated and slow. Right now there three
23648  * restrictions:
23649  *
23650  *   1. The first message block must contain the complete IP header and
23651  *	at least 1 byte of payload data.
23652  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23653  *	so that we can use a single Multidata message.
23654  *   3. No frag must be distributed over two or more message blocks so
23655  *	that we don't need more than two packet descriptors per frag.
23656  *
23657  * The above restrictions allow us to support userland applications (which
23658  * will send down a single message block) and NFS over UDP (which will
23659  * send down a chain of at most three message blocks).
23660  *
23661  * We also don't use MDT for payloads with less than or equal to
23662  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23663  */
23664 boolean_t
23665 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23666 {
23667 	int	blocks;
23668 	ssize_t	total, missing, size;
23669 
23670 	ASSERT(mp != NULL);
23671 	ASSERT(hdr_len > 0);
23672 
23673 	size = MBLKL(mp) - hdr_len;
23674 	if (size <= 0)
23675 		return (B_FALSE);
23676 
23677 	/* The first mblk contains the header and some payload. */
23678 	blocks = 1;
23679 	total = size;
23680 	size %= len;
23681 	missing = (size == 0) ? 0 : (len - size);
23682 	mp = mp->b_cont;
23683 
23684 	while (mp != NULL) {
23685 		/*
23686 		 * Give up if we encounter a zero length message block.
23687 		 * In practice, this should rarely happen and therefore
23688 		 * not worth the trouble of freeing and re-linking the
23689 		 * mblk from the chain to handle such case.
23690 		 */
23691 		if ((size = MBLKL(mp)) == 0)
23692 			return (B_FALSE);
23693 
23694 		/* Too many payload buffers for a single Multidata message? */
23695 		if (++blocks > MULTIDATA_MAX_PBUFS)
23696 			return (B_FALSE);
23697 
23698 		total += size;
23699 		/* Is a frag distributed over two or more message blocks? */
23700 		if (missing > size)
23701 			return (B_FALSE);
23702 		size -= missing;
23703 
23704 		size %= len;
23705 		missing = (size == 0) ? 0 : (len - size);
23706 
23707 		mp = mp->b_cont;
23708 	}
23709 
23710 	return (total > ip_wput_frag_mdt_min);
23711 }
23712 
23713 /*
23714  * Outbound IPv4 fragmentation routine using MDT.
23715  */
23716 static void
23717 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23718     uint32_t frag_flag, int offset)
23719 {
23720 	ipha_t		*ipha_orig;
23721 	int		i1, ip_data_end;
23722 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23723 	mblk_t		*hdr_mp, *md_mp = NULL;
23724 	unsigned char	*hdr_ptr, *pld_ptr;
23725 	multidata_t	*mmd;
23726 	ip_pdescinfo_t	pdi;
23727 	ill_t		*ill;
23728 	ip_stack_t	*ipst = ire->ire_ipst;
23729 
23730 	ASSERT(DB_TYPE(mp) == M_DATA);
23731 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23732 
23733 	ill = ire_to_ill(ire);
23734 	ASSERT(ill != NULL);
23735 
23736 	ipha_orig = (ipha_t *)mp->b_rptr;
23737 	mp->b_rptr += sizeof (ipha_t);
23738 
23739 	/* Calculate how many packets we will send out */
23740 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23741 	pkts = (i1 + len - 1) / len;
23742 	ASSERT(pkts > 1);
23743 
23744 	/* Allocate a message block which will hold all the IP Headers. */
23745 	wroff = ipst->ips_ip_wroff_extra;
23746 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23747 
23748 	i1 = pkts * hdr_chunk_len;
23749 	/*
23750 	 * Create the header buffer, Multidata and destination address
23751 	 * and SAP attribute that should be associated with it.
23752 	 */
23753 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23754 	    ((hdr_mp->b_wptr += i1),
23755 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23756 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23757 		freemsg(mp);
23758 		if (md_mp == NULL) {
23759 			freemsg(hdr_mp);
23760 		} else {
23761 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23762 			freemsg(md_mp);
23763 		}
23764 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23765 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23766 		return;
23767 	}
23768 	IP_STAT(ipst, ip_frag_mdt_allocd);
23769 
23770 	/*
23771 	 * Add a payload buffer to the Multidata; this operation must not
23772 	 * fail, or otherwise our logic in this routine is broken.  There
23773 	 * is no memory allocation done by the routine, so any returned
23774 	 * failure simply tells us that we've done something wrong.
23775 	 *
23776 	 * A failure tells us that either we're adding the same payload
23777 	 * buffer more than once, or we're trying to add more buffers than
23778 	 * allowed.  None of the above cases should happen, and we panic
23779 	 * because either there's horrible heap corruption, and/or
23780 	 * programming mistake.
23781 	 */
23782 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23783 		goto pbuf_panic;
23784 
23785 	hdr_ptr = hdr_mp->b_rptr;
23786 	pld_ptr = mp->b_rptr;
23787 
23788 	/* Establish the ending byte offset, based on the starting offset. */
23789 	offset <<= 3;
23790 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23791 	    IP_SIMPLE_HDR_LENGTH;
23792 
23793 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23794 
23795 	while (pld_ptr < mp->b_wptr) {
23796 		ipha_t		*ipha;
23797 		uint16_t	offset_and_flags;
23798 		uint16_t	ip_len;
23799 		int		error;
23800 
23801 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23802 		ipha = (ipha_t *)(hdr_ptr + wroff);
23803 		ASSERT(OK_32PTR(ipha));
23804 		*ipha = *ipha_orig;
23805 
23806 		if (ip_data_end - offset > len) {
23807 			offset_and_flags = IPH_MF;
23808 		} else {
23809 			/*
23810 			 * Last frag. Set len to the length of this last piece.
23811 			 */
23812 			len = ip_data_end - offset;
23813 			/* A frag of a frag might have IPH_MF non-zero */
23814 			offset_and_flags =
23815 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23816 			    IPH_MF;
23817 		}
23818 		offset_and_flags |= (uint16_t)(offset >> 3);
23819 		offset_and_flags |= (uint16_t)frag_flag;
23820 		/* Store the offset and flags in the IP header. */
23821 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23822 
23823 		/* Store the length in the IP header. */
23824 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23825 		ipha->ipha_length = htons(ip_len);
23826 
23827 		/*
23828 		 * Set the IP header checksum.  Note that mp is just
23829 		 * the header, so this is easy to pass to ip_csum.
23830 		 */
23831 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23832 
23833 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23834 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23835 		    NULL, int, 0);
23836 
23837 		/*
23838 		 * Record offset and size of header and data of the next packet
23839 		 * in the multidata message.
23840 		 */
23841 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23842 		PDESC_PLD_INIT(&pdi);
23843 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23844 		ASSERT(i1 > 0);
23845 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23846 		if (i1 == len) {
23847 			pld_ptr += len;
23848 		} else {
23849 			i1 = len - i1;
23850 			mp = mp->b_cont;
23851 			ASSERT(mp != NULL);
23852 			ASSERT(MBLKL(mp) >= i1);
23853 			/*
23854 			 * Attach the next payload message block to the
23855 			 * multidata message.
23856 			 */
23857 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23858 				goto pbuf_panic;
23859 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23860 			pld_ptr = mp->b_rptr + i1;
23861 		}
23862 
23863 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23864 		    KM_NOSLEEP)) == NULL) {
23865 			/*
23866 			 * Any failure other than ENOMEM indicates that we
23867 			 * have passed in invalid pdesc info or parameters
23868 			 * to mmd_addpdesc, which must not happen.
23869 			 *
23870 			 * EINVAL is a result of failure on boundary checks
23871 			 * against the pdesc info contents.  It should not
23872 			 * happen, and we panic because either there's
23873 			 * horrible heap corruption, and/or programming
23874 			 * mistake.
23875 			 */
23876 			if (error != ENOMEM) {
23877 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23878 				    "pdesc logic error detected for "
23879 				    "mmd %p pinfo %p (%d)\n",
23880 				    (void *)mmd, (void *)&pdi, error);
23881 				/* NOTREACHED */
23882 			}
23883 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23884 			/* Free unattached payload message blocks as well */
23885 			md_mp->b_cont = mp->b_cont;
23886 			goto free_mmd;
23887 		}
23888 
23889 		/* Advance fragment offset. */
23890 		offset += len;
23891 
23892 		/* Advance to location for next header in the buffer. */
23893 		hdr_ptr += hdr_chunk_len;
23894 
23895 		/* Did we reach the next payload message block? */
23896 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23897 			mp = mp->b_cont;
23898 			/*
23899 			 * Attach the next message block with payload
23900 			 * data to the multidata message.
23901 			 */
23902 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23903 				goto pbuf_panic;
23904 			pld_ptr = mp->b_rptr;
23905 		}
23906 	}
23907 
23908 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23909 	ASSERT(mp->b_wptr == pld_ptr);
23910 
23911 	/* Update IP statistics */
23912 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23913 
23914 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23915 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23916 
23917 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23918 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23919 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23920 
23921 	if (pkt_type == OB_PKT) {
23922 		ire->ire_ob_pkt_count += pkts;
23923 		if (ire->ire_ipif != NULL)
23924 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23925 	} else {
23926 		/* The type is IB_PKT in the forwarding path. */
23927 		ire->ire_ib_pkt_count += pkts;
23928 		ASSERT(!IRE_IS_LOCAL(ire));
23929 		if (ire->ire_type & IRE_BROADCAST) {
23930 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23931 		} else {
23932 			UPDATE_MIB(ill->ill_ip_mib,
23933 			    ipIfStatsHCOutForwDatagrams, pkts);
23934 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23935 		}
23936 	}
23937 	ire->ire_last_used_time = lbolt;
23938 	/* Send it down */
23939 	putnext(ire->ire_stq, md_mp);
23940 	return;
23941 
23942 pbuf_panic:
23943 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23944 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23945 	    pbuf_idx);
23946 	/* NOTREACHED */
23947 }
23948 
23949 /*
23950  * Outbound IP fragmentation routine.
23951  *
23952  * NOTE : This routine does not ire_refrele the ire that is passed in
23953  * as the argument.
23954  */
23955 static void
23956 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23957     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
23958 {
23959 	int		i1;
23960 	mblk_t		*ll_hdr_mp;
23961 	int 		ll_hdr_len;
23962 	int		hdr_len;
23963 	mblk_t		*hdr_mp;
23964 	ipha_t		*ipha;
23965 	int		ip_data_end;
23966 	int		len;
23967 	mblk_t		*mp = mp_orig, *mp1;
23968 	int		offset;
23969 	queue_t		*q;
23970 	uint32_t	v_hlen_tos_len;
23971 	mblk_t		*first_mp;
23972 	boolean_t	mctl_present;
23973 	ill_t		*ill;
23974 	ill_t		*out_ill;
23975 	mblk_t		*xmit_mp;
23976 	mblk_t		*carve_mp;
23977 	ire_t		*ire1 = NULL;
23978 	ire_t		*save_ire = NULL;
23979 	mblk_t  	*next_mp = NULL;
23980 	boolean_t	last_frag = B_FALSE;
23981 	boolean_t	multirt_send = B_FALSE;
23982 	ire_t		*first_ire = NULL;
23983 	irb_t		*irb = NULL;
23984 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23985 
23986 	ill = ire_to_ill(ire);
23987 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
23988 
23989 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23990 
23991 	if (max_frag == 0) {
23992 		ip1dbg(("ip_wput_frag: ire frag size is 0"
23993 		    " -  dropping packet\n"));
23994 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23995 		freemsg(mp);
23996 		return;
23997 	}
23998 
23999 	/*
24000 	 * IPsec does not allow hw accelerated packets to be fragmented
24001 	 * This check is made in ip_wput_ipsec_out prior to coming here
24002 	 * via ip_wput_ire_fragmentit.
24003 	 *
24004 	 * If at this point we have an ire whose ARP request has not
24005 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24006 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24007 	 * This packet and all fragmentable packets for this ire will
24008 	 * continue to get dropped while ire_nce->nce_state remains in
24009 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24010 	 * ND_REACHABLE, all subsquent large packets for this ire will
24011 	 * get fragemented and sent out by this function.
24012 	 */
24013 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24014 		/* If nce_state is ND_INITIAL, trigger ARP query */
24015 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24016 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24017 		    " -  dropping packet\n"));
24018 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24019 		freemsg(mp);
24020 		return;
24021 	}
24022 
24023 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24024 	    "ip_wput_frag_start:");
24025 
24026 	if (mp->b_datap->db_type == M_CTL) {
24027 		first_mp = mp;
24028 		mp_orig = mp = mp->b_cont;
24029 		mctl_present = B_TRUE;
24030 	} else {
24031 		first_mp = mp;
24032 		mctl_present = B_FALSE;
24033 	}
24034 
24035 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24036 	ipha = (ipha_t *)mp->b_rptr;
24037 
24038 	/*
24039 	 * If the Don't Fragment flag is on, generate an ICMP destination
24040 	 * unreachable, fragmentation needed.
24041 	 */
24042 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24043 	if (offset & IPH_DF) {
24044 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24045 		if (is_system_labeled()) {
24046 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24047 			    ire->ire_max_frag - max_frag, AF_INET);
24048 		}
24049 		/*
24050 		 * Need to compute hdr checksum if called from ip_wput_ire.
24051 		 * Note that ip_rput_forward verifies the checksum before
24052 		 * calling this routine so in that case this is a noop.
24053 		 */
24054 		ipha->ipha_hdr_checksum = 0;
24055 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24056 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24057 		    ipst);
24058 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24059 		    "ip_wput_frag_end:(%S)",
24060 		    "don't fragment");
24061 		return;
24062 	}
24063 	/*
24064 	 * Labeled systems adjust max_frag if they add a label
24065 	 * to send the correct path mtu.  We need the real mtu since we
24066 	 * are fragmenting the packet after label adjustment.
24067 	 */
24068 	if (is_system_labeled())
24069 		max_frag = ire->ire_max_frag;
24070 	if (mctl_present)
24071 		freeb(first_mp);
24072 	/*
24073 	 * Establish the starting offset.  May not be zero if we are fragging
24074 	 * a fragment that is being forwarded.
24075 	 */
24076 	offset = offset & IPH_OFFSET;
24077 
24078 	/* TODO why is this test needed? */
24079 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24080 	if (((max_frag - LENGTH) & ~7) < 8) {
24081 		/* TODO: notify ulp somehow */
24082 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24083 		freemsg(mp);
24084 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24085 		    "ip_wput_frag_end:(%S)",
24086 		    "len < 8");
24087 		return;
24088 	}
24089 
24090 	hdr_len = (V_HLEN & 0xF) << 2;
24091 
24092 	ipha->ipha_hdr_checksum = 0;
24093 
24094 	/*
24095 	 * Establish the number of bytes maximum per frag, after putting
24096 	 * in the header.
24097 	 */
24098 	len = (max_frag - hdr_len) & ~7;
24099 
24100 	/* Check if we can use MDT to send out the frags. */
24101 	ASSERT(!IRE_IS_LOCAL(ire));
24102 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24103 	    ipst->ips_ip_multidata_outbound &&
24104 	    !(ire->ire_flags & RTF_MULTIRT) &&
24105 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24106 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24107 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24108 		ASSERT(ill->ill_mdt_capab != NULL);
24109 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24110 			/*
24111 			 * If MDT has been previously turned off in the past,
24112 			 * and we currently can do MDT (due to IPQoS policy
24113 			 * removal, etc.) then enable it for this interface.
24114 			 */
24115 			ill->ill_mdt_capab->ill_mdt_on = 1;
24116 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24117 			    ill->ill_name));
24118 		}
24119 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24120 		    offset);
24121 		return;
24122 	}
24123 
24124 	/* Get a copy of the header for the trailing frags */
24125 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24126 	    mp);
24127 	if (!hdr_mp) {
24128 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24129 		freemsg(mp);
24130 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24131 		    "ip_wput_frag_end:(%S)",
24132 		    "couldn't copy hdr");
24133 		return;
24134 	}
24135 
24136 	/* Store the starting offset, with the MoreFrags flag. */
24137 	i1 = offset | IPH_MF | frag_flag;
24138 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24139 
24140 	/* Establish the ending byte offset, based on the starting offset. */
24141 	offset <<= 3;
24142 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24143 
24144 	/* Store the length of the first fragment in the IP header. */
24145 	i1 = len + hdr_len;
24146 	ASSERT(i1 <= IP_MAXPACKET);
24147 	ipha->ipha_length = htons((uint16_t)i1);
24148 
24149 	/*
24150 	 * Compute the IP header checksum for the first frag.  We have to
24151 	 * watch out that we stop at the end of the header.
24152 	 */
24153 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24154 
24155 	/*
24156 	 * Now carve off the first frag.  Note that this will include the
24157 	 * original IP header.
24158 	 */
24159 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24160 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24161 		freeb(hdr_mp);
24162 		freemsg(mp_orig);
24163 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24164 		    "ip_wput_frag_end:(%S)",
24165 		    "couldn't carve first");
24166 		return;
24167 	}
24168 
24169 	/*
24170 	 * Multirouting case. Each fragment is replicated
24171 	 * via all non-condemned RTF_MULTIRT routes
24172 	 * currently resolved.
24173 	 * We ensure that first_ire is the first RTF_MULTIRT
24174 	 * ire in the bucket.
24175 	 */
24176 	if (ire->ire_flags & RTF_MULTIRT) {
24177 		irb = ire->ire_bucket;
24178 		ASSERT(irb != NULL);
24179 
24180 		multirt_send = B_TRUE;
24181 
24182 		/* Make sure we do not omit any multiroute ire. */
24183 		IRB_REFHOLD(irb);
24184 		for (first_ire = irb->irb_ire;
24185 		    first_ire != NULL;
24186 		    first_ire = first_ire->ire_next) {
24187 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24188 			    (first_ire->ire_addr == ire->ire_addr) &&
24189 			    !(first_ire->ire_marks &
24190 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24191 				break;
24192 		}
24193 
24194 		if (first_ire != NULL) {
24195 			if (first_ire != ire) {
24196 				IRE_REFHOLD(first_ire);
24197 				/*
24198 				 * Do not release the ire passed in
24199 				 * as the argument.
24200 				 */
24201 				ire = first_ire;
24202 			} else {
24203 				first_ire = NULL;
24204 			}
24205 		}
24206 		IRB_REFRELE(irb);
24207 
24208 		/*
24209 		 * Save the first ire; we will need to restore it
24210 		 * for the trailing frags.
24211 		 * We REFHOLD save_ire, as each iterated ire will be
24212 		 * REFRELEd.
24213 		 */
24214 		save_ire = ire;
24215 		IRE_REFHOLD(save_ire);
24216 	}
24217 
24218 	/*
24219 	 * First fragment emission loop.
24220 	 * In most cases, the emission loop below is entered only
24221 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24222 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24223 	 * bucket, and send the fragment through all crossed
24224 	 * RTF_MULTIRT routes.
24225 	 */
24226 	do {
24227 		if (ire->ire_flags & RTF_MULTIRT) {
24228 			/*
24229 			 * We are in a multiple send case, need to get
24230 			 * the next ire and make a copy of the packet.
24231 			 * ire1 holds here the next ire to process in the
24232 			 * bucket. If multirouting is expected,
24233 			 * any non-RTF_MULTIRT ire that has the
24234 			 * right destination address is ignored.
24235 			 *
24236 			 * We have to take into account the MTU of
24237 			 * each walked ire. max_frag is set by the
24238 			 * the caller and generally refers to
24239 			 * the primary ire entry. Here we ensure that
24240 			 * no route with a lower MTU will be used, as
24241 			 * fragments are carved once for all ires,
24242 			 * then replicated.
24243 			 */
24244 			ASSERT(irb != NULL);
24245 			IRB_REFHOLD(irb);
24246 			for (ire1 = ire->ire_next;
24247 			    ire1 != NULL;
24248 			    ire1 = ire1->ire_next) {
24249 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24250 					continue;
24251 				if (ire1->ire_addr != ire->ire_addr)
24252 					continue;
24253 				if (ire1->ire_marks &
24254 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24255 					continue;
24256 				/*
24257 				 * Ensure we do not exceed the MTU
24258 				 * of the next route.
24259 				 */
24260 				if (ire1->ire_max_frag < max_frag) {
24261 					ip_multirt_bad_mtu(ire1, max_frag);
24262 					continue;
24263 				}
24264 
24265 				/* Got one. */
24266 				IRE_REFHOLD(ire1);
24267 				break;
24268 			}
24269 			IRB_REFRELE(irb);
24270 
24271 			if (ire1 != NULL) {
24272 				next_mp = copyb(mp);
24273 				if ((next_mp == NULL) ||
24274 				    ((mp->b_cont != NULL) &&
24275 				    ((next_mp->b_cont =
24276 				    dupmsg(mp->b_cont)) == NULL))) {
24277 					freemsg(next_mp);
24278 					next_mp = NULL;
24279 					ire_refrele(ire1);
24280 					ire1 = NULL;
24281 				}
24282 			}
24283 
24284 			/* Last multiroute ire; don't loop anymore. */
24285 			if (ire1 == NULL) {
24286 				multirt_send = B_FALSE;
24287 			}
24288 		}
24289 
24290 		ll_hdr_len = 0;
24291 		LOCK_IRE_FP_MP(ire);
24292 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24293 		if (ll_hdr_mp != NULL) {
24294 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24295 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24296 		} else {
24297 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24298 		}
24299 
24300 		/* If there is a transmit header, get a copy for this frag. */
24301 		/*
24302 		 * TODO: should check db_ref before calling ip_carve_mp since
24303 		 * it might give us a dup.
24304 		 */
24305 		if (!ll_hdr_mp) {
24306 			/* No xmit header. */
24307 			xmit_mp = mp;
24308 
24309 		/* We have a link-layer header that can fit in our mblk. */
24310 		} else if (mp->b_datap->db_ref == 1 &&
24311 		    ll_hdr_len != 0 &&
24312 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24313 			/* M_DATA fastpath */
24314 			mp->b_rptr -= ll_hdr_len;
24315 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24316 			xmit_mp = mp;
24317 
24318 		/* Corner case if copyb has failed */
24319 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24320 			UNLOCK_IRE_FP_MP(ire);
24321 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24322 			freeb(hdr_mp);
24323 			freemsg(mp);
24324 			freemsg(mp_orig);
24325 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24326 			    "ip_wput_frag_end:(%S)",
24327 			    "discard");
24328 
24329 			if (multirt_send) {
24330 				ASSERT(ire1);
24331 				ASSERT(next_mp);
24332 
24333 				freemsg(next_mp);
24334 				ire_refrele(ire1);
24335 			}
24336 			if (save_ire != NULL)
24337 				IRE_REFRELE(save_ire);
24338 
24339 			if (first_ire != NULL)
24340 				ire_refrele(first_ire);
24341 			return;
24342 
24343 		/*
24344 		 * Case of res_mp OR the fastpath mp can't fit
24345 		 * in the mblk
24346 		 */
24347 		} else {
24348 			xmit_mp->b_cont = mp;
24349 
24350 			/*
24351 			 * Get priority marking, if any.
24352 			 * We propagate the CoS marking from the
24353 			 * original packet that went to QoS processing
24354 			 * in ip_wput_ire to the newly carved mp.
24355 			 */
24356 			if (DB_TYPE(xmit_mp) == M_DATA)
24357 				xmit_mp->b_band = mp->b_band;
24358 		}
24359 		UNLOCK_IRE_FP_MP(ire);
24360 
24361 		q = ire->ire_stq;
24362 		out_ill = (ill_t *)q->q_ptr;
24363 
24364 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24365 
24366 		DTRACE_PROBE4(ip4__physical__out__start,
24367 		    ill_t *, NULL, ill_t *, out_ill,
24368 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24369 
24370 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24371 		    ipst->ips_ipv4firewall_physical_out,
24372 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24373 
24374 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24375 
24376 		if (xmit_mp != NULL) {
24377 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24378 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24379 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24380 
24381 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24382 
24383 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24384 			UPDATE_MIB(out_ill->ill_ip_mib,
24385 			    ipIfStatsHCOutOctets, i1);
24386 
24387 			if (pkt_type != OB_PKT) {
24388 				/*
24389 				 * Update the packet count and MIB stats
24390 				 * of trailing RTF_MULTIRT ires.
24391 				 */
24392 				UPDATE_OB_PKT_COUNT(ire);
24393 				BUMP_MIB(out_ill->ill_ip_mib,
24394 				    ipIfStatsOutFragReqds);
24395 			}
24396 		}
24397 
24398 		if (multirt_send) {
24399 			/*
24400 			 * We are in a multiple send case; look for
24401 			 * the next ire and re-enter the loop.
24402 			 */
24403 			ASSERT(ire1);
24404 			ASSERT(next_mp);
24405 			/* REFRELE the current ire before looping */
24406 			ire_refrele(ire);
24407 			ire = ire1;
24408 			ire1 = NULL;
24409 			mp = next_mp;
24410 			next_mp = NULL;
24411 		}
24412 	} while (multirt_send);
24413 
24414 	ASSERT(ire1 == NULL);
24415 
24416 	/* Restore the original ire; we need it for the trailing frags */
24417 	if (save_ire != NULL) {
24418 		/* REFRELE the last iterated ire */
24419 		ire_refrele(ire);
24420 		/* save_ire has been REFHOLDed */
24421 		ire = save_ire;
24422 		save_ire = NULL;
24423 		q = ire->ire_stq;
24424 	}
24425 
24426 	if (pkt_type == OB_PKT) {
24427 		UPDATE_OB_PKT_COUNT(ire);
24428 	} else {
24429 		out_ill = (ill_t *)q->q_ptr;
24430 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24431 		UPDATE_IB_PKT_COUNT(ire);
24432 	}
24433 
24434 	/* Advance the offset to the second frag starting point. */
24435 	offset += len;
24436 	/*
24437 	 * Update hdr_len from the copied header - there might be less options
24438 	 * in the later fragments.
24439 	 */
24440 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24441 	/* Loop until done. */
24442 	for (;;) {
24443 		uint16_t	offset_and_flags;
24444 		uint16_t	ip_len;
24445 
24446 		if (ip_data_end - offset > len) {
24447 			/*
24448 			 * Carve off the appropriate amount from the original
24449 			 * datagram.
24450 			 */
24451 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24452 				mp = NULL;
24453 				break;
24454 			}
24455 			/*
24456 			 * More frags after this one.  Get another copy
24457 			 * of the header.
24458 			 */
24459 			if (carve_mp->b_datap->db_ref == 1 &&
24460 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24461 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24462 				/* Inline IP header */
24463 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24464 				    hdr_mp->b_rptr;
24465 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24466 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24467 				mp = carve_mp;
24468 			} else {
24469 				if (!(mp = copyb(hdr_mp))) {
24470 					freemsg(carve_mp);
24471 					break;
24472 				}
24473 				/* Get priority marking, if any. */
24474 				mp->b_band = carve_mp->b_band;
24475 				mp->b_cont = carve_mp;
24476 			}
24477 			ipha = (ipha_t *)mp->b_rptr;
24478 			offset_and_flags = IPH_MF;
24479 		} else {
24480 			/*
24481 			 * Last frag.  Consume the header. Set len to
24482 			 * the length of this last piece.
24483 			 */
24484 			len = ip_data_end - offset;
24485 
24486 			/*
24487 			 * Carve off the appropriate amount from the original
24488 			 * datagram.
24489 			 */
24490 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24491 				mp = NULL;
24492 				break;
24493 			}
24494 			if (carve_mp->b_datap->db_ref == 1 &&
24495 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24496 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24497 				/* Inline IP header */
24498 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24499 				    hdr_mp->b_rptr;
24500 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24501 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24502 				mp = carve_mp;
24503 				freeb(hdr_mp);
24504 				hdr_mp = mp;
24505 			} else {
24506 				mp = hdr_mp;
24507 				/* Get priority marking, if any. */
24508 				mp->b_band = carve_mp->b_band;
24509 				mp->b_cont = carve_mp;
24510 			}
24511 			ipha = (ipha_t *)mp->b_rptr;
24512 			/* A frag of a frag might have IPH_MF non-zero */
24513 			offset_and_flags =
24514 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24515 			    IPH_MF;
24516 		}
24517 		offset_and_flags |= (uint16_t)(offset >> 3);
24518 		offset_and_flags |= (uint16_t)frag_flag;
24519 		/* Store the offset and flags in the IP header. */
24520 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24521 
24522 		/* Store the length in the IP header. */
24523 		ip_len = (uint16_t)(len + hdr_len);
24524 		ipha->ipha_length = htons(ip_len);
24525 
24526 		/*
24527 		 * Set the IP header checksum.	Note that mp is just
24528 		 * the header, so this is easy to pass to ip_csum.
24529 		 */
24530 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24531 
24532 		/* Attach a transmit header, if any, and ship it. */
24533 		if (pkt_type == OB_PKT) {
24534 			UPDATE_OB_PKT_COUNT(ire);
24535 		} else {
24536 			out_ill = (ill_t *)q->q_ptr;
24537 			BUMP_MIB(out_ill->ill_ip_mib,
24538 			    ipIfStatsHCOutForwDatagrams);
24539 			UPDATE_IB_PKT_COUNT(ire);
24540 		}
24541 
24542 		if (ire->ire_flags & RTF_MULTIRT) {
24543 			irb = ire->ire_bucket;
24544 			ASSERT(irb != NULL);
24545 
24546 			multirt_send = B_TRUE;
24547 
24548 			/*
24549 			 * Save the original ire; we will need to restore it
24550 			 * for the tailing frags.
24551 			 */
24552 			save_ire = ire;
24553 			IRE_REFHOLD(save_ire);
24554 		}
24555 		/*
24556 		 * Emission loop for this fragment, similar
24557 		 * to what is done for the first fragment.
24558 		 */
24559 		do {
24560 			if (multirt_send) {
24561 				/*
24562 				 * We are in a multiple send case, need to get
24563 				 * the next ire and make a copy of the packet.
24564 				 */
24565 				ASSERT(irb != NULL);
24566 				IRB_REFHOLD(irb);
24567 				for (ire1 = ire->ire_next;
24568 				    ire1 != NULL;
24569 				    ire1 = ire1->ire_next) {
24570 					if (!(ire1->ire_flags & RTF_MULTIRT))
24571 						continue;
24572 					if (ire1->ire_addr != ire->ire_addr)
24573 						continue;
24574 					if (ire1->ire_marks &
24575 					    (IRE_MARK_CONDEMNED |
24576 					    IRE_MARK_TESTHIDDEN))
24577 						continue;
24578 					/*
24579 					 * Ensure we do not exceed the MTU
24580 					 * of the next route.
24581 					 */
24582 					if (ire1->ire_max_frag < max_frag) {
24583 						ip_multirt_bad_mtu(ire1,
24584 						    max_frag);
24585 						continue;
24586 					}
24587 
24588 					/* Got one. */
24589 					IRE_REFHOLD(ire1);
24590 					break;
24591 				}
24592 				IRB_REFRELE(irb);
24593 
24594 				if (ire1 != NULL) {
24595 					next_mp = copyb(mp);
24596 					if ((next_mp == NULL) ||
24597 					    ((mp->b_cont != NULL) &&
24598 					    ((next_mp->b_cont =
24599 					    dupmsg(mp->b_cont)) == NULL))) {
24600 						freemsg(next_mp);
24601 						next_mp = NULL;
24602 						ire_refrele(ire1);
24603 						ire1 = NULL;
24604 					}
24605 				}
24606 
24607 				/* Last multiroute ire; don't loop anymore. */
24608 				if (ire1 == NULL) {
24609 					multirt_send = B_FALSE;
24610 				}
24611 			}
24612 
24613 			/* Update transmit header */
24614 			ll_hdr_len = 0;
24615 			LOCK_IRE_FP_MP(ire);
24616 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24617 			if (ll_hdr_mp != NULL) {
24618 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24619 				ll_hdr_len = MBLKL(ll_hdr_mp);
24620 			} else {
24621 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24622 			}
24623 
24624 			if (!ll_hdr_mp) {
24625 				xmit_mp = mp;
24626 
24627 			/*
24628 			 * We have link-layer header that can fit in
24629 			 * our mblk.
24630 			 */
24631 			} else if (mp->b_datap->db_ref == 1 &&
24632 			    ll_hdr_len != 0 &&
24633 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24634 				/* M_DATA fastpath */
24635 				mp->b_rptr -= ll_hdr_len;
24636 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24637 				    ll_hdr_len);
24638 				xmit_mp = mp;
24639 
24640 			/*
24641 			 * Case of res_mp OR the fastpath mp can't fit
24642 			 * in the mblk
24643 			 */
24644 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24645 				xmit_mp->b_cont = mp;
24646 				/* Get priority marking, if any. */
24647 				if (DB_TYPE(xmit_mp) == M_DATA)
24648 					xmit_mp->b_band = mp->b_band;
24649 
24650 			/* Corner case if copyb failed */
24651 			} else {
24652 				/*
24653 				 * Exit both the replication and
24654 				 * fragmentation loops.
24655 				 */
24656 				UNLOCK_IRE_FP_MP(ire);
24657 				goto drop_pkt;
24658 			}
24659 			UNLOCK_IRE_FP_MP(ire);
24660 
24661 			mp1 = mp;
24662 			out_ill = (ill_t *)q->q_ptr;
24663 
24664 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24665 
24666 			DTRACE_PROBE4(ip4__physical__out__start,
24667 			    ill_t *, NULL, ill_t *, out_ill,
24668 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24669 
24670 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24671 			    ipst->ips_ipv4firewall_physical_out,
24672 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24673 
24674 			DTRACE_PROBE1(ip4__physical__out__end,
24675 			    mblk_t *, xmit_mp);
24676 
24677 			if (mp != mp1 && hdr_mp == mp1)
24678 				hdr_mp = mp;
24679 			if (mp != mp1 && mp_orig == mp1)
24680 				mp_orig = mp;
24681 
24682 			if (xmit_mp != NULL) {
24683 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24684 				    NULL, void_ip_t *, ipha,
24685 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24686 				    ipha, ip6_t *, NULL, int, 0);
24687 
24688 				ILL_SEND_TX(out_ill, ire, connp,
24689 				    xmit_mp, 0, connp);
24690 
24691 				BUMP_MIB(out_ill->ill_ip_mib,
24692 				    ipIfStatsHCOutTransmits);
24693 				UPDATE_MIB(out_ill->ill_ip_mib,
24694 				    ipIfStatsHCOutOctets, ip_len);
24695 
24696 				if (pkt_type != OB_PKT) {
24697 					/*
24698 					 * Update the packet count of trailing
24699 					 * RTF_MULTIRT ires.
24700 					 */
24701 					UPDATE_OB_PKT_COUNT(ire);
24702 				}
24703 			}
24704 
24705 			/* All done if we just consumed the hdr_mp. */
24706 			if (mp == hdr_mp) {
24707 				last_frag = B_TRUE;
24708 				BUMP_MIB(out_ill->ill_ip_mib,
24709 				    ipIfStatsOutFragOKs);
24710 			}
24711 
24712 			if (multirt_send) {
24713 				/*
24714 				 * We are in a multiple send case; look for
24715 				 * the next ire and re-enter the loop.
24716 				 */
24717 				ASSERT(ire1);
24718 				ASSERT(next_mp);
24719 				/* REFRELE the current ire before looping */
24720 				ire_refrele(ire);
24721 				ire = ire1;
24722 				ire1 = NULL;
24723 				q = ire->ire_stq;
24724 				mp = next_mp;
24725 				next_mp = NULL;
24726 			}
24727 		} while (multirt_send);
24728 		/*
24729 		 * Restore the original ire; we need it for the
24730 		 * trailing frags
24731 		 */
24732 		if (save_ire != NULL) {
24733 			ASSERT(ire1 == NULL);
24734 			/* REFRELE the last iterated ire */
24735 			ire_refrele(ire);
24736 			/* save_ire has been REFHOLDed */
24737 			ire = save_ire;
24738 			q = ire->ire_stq;
24739 			save_ire = NULL;
24740 		}
24741 
24742 		if (last_frag) {
24743 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24744 			    "ip_wput_frag_end:(%S)",
24745 			    "consumed hdr_mp");
24746 
24747 			if (first_ire != NULL)
24748 				ire_refrele(first_ire);
24749 			return;
24750 		}
24751 		/* Otherwise, advance and loop. */
24752 		offset += len;
24753 	}
24754 
24755 drop_pkt:
24756 	/* Clean up following allocation failure. */
24757 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24758 	freemsg(mp);
24759 	if (mp != hdr_mp)
24760 		freeb(hdr_mp);
24761 	if (mp != mp_orig)
24762 		freemsg(mp_orig);
24763 
24764 	if (save_ire != NULL)
24765 		IRE_REFRELE(save_ire);
24766 	if (first_ire != NULL)
24767 		ire_refrele(first_ire);
24768 
24769 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24770 	    "ip_wput_frag_end:(%S)",
24771 	    "end--alloc failure");
24772 }
24773 
24774 /*
24775  * Copy the header plus those options which have the copy bit set
24776  * src is the template to make sure we preserve the cred for TX purposes.
24777  */
24778 static mblk_t *
24779 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24780     mblk_t *src)
24781 {
24782 	mblk_t	*mp;
24783 	uchar_t	*up;
24784 
24785 	/*
24786 	 * Quick check if we need to look for options without the copy bit
24787 	 * set
24788 	 */
24789 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24790 	if (!mp)
24791 		return (mp);
24792 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24793 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24794 		bcopy(rptr, mp->b_rptr, hdr_len);
24795 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24796 		return (mp);
24797 	}
24798 	up  = mp->b_rptr;
24799 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24800 	up += IP_SIMPLE_HDR_LENGTH;
24801 	rptr += IP_SIMPLE_HDR_LENGTH;
24802 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24803 	while (hdr_len > 0) {
24804 		uint32_t optval;
24805 		uint32_t optlen;
24806 
24807 		optval = *rptr;
24808 		if (optval == IPOPT_EOL)
24809 			break;
24810 		if (optval == IPOPT_NOP)
24811 			optlen = 1;
24812 		else
24813 			optlen = rptr[1];
24814 		if (optval & IPOPT_COPY) {
24815 			bcopy(rptr, up, optlen);
24816 			up += optlen;
24817 		}
24818 		rptr += optlen;
24819 		hdr_len -= optlen;
24820 	}
24821 	/*
24822 	 * Make sure that we drop an even number of words by filling
24823 	 * with EOL to the next word boundary.
24824 	 */
24825 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24826 	    hdr_len & 0x3; hdr_len++)
24827 		*up++ = IPOPT_EOL;
24828 	mp->b_wptr = up;
24829 	/* Update header length */
24830 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24831 	return (mp);
24832 }
24833 
24834 /*
24835  * Delivery to local recipients including fanout to multiple recipients.
24836  * Does not do checksumming of UDP/TCP.
24837  * Note: q should be the read side queue for either the ill or conn.
24838  * Note: rq should be the read side q for the lower (ill) stream.
24839  * We don't send packets to IPPF processing, thus the last argument
24840  * to all the fanout calls are B_FALSE.
24841  */
24842 void
24843 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24844     int fanout_flags, zoneid_t zoneid)
24845 {
24846 	uint32_t	protocol;
24847 	mblk_t		*first_mp;
24848 	boolean_t	mctl_present;
24849 	int		ire_type;
24850 #define	rptr	((uchar_t *)ipha)
24851 	ip_stack_t	*ipst = ill->ill_ipst;
24852 
24853 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24854 	    "ip_wput_local_start: q %p", q);
24855 
24856 	if (ire != NULL) {
24857 		ire_type = ire->ire_type;
24858 	} else {
24859 		/*
24860 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24861 		 * packet is not multicast, we can't tell the ire type.
24862 		 */
24863 		ASSERT(CLASSD(ipha->ipha_dst));
24864 		ire_type = IRE_BROADCAST;
24865 	}
24866 
24867 	first_mp = mp;
24868 	if (first_mp->b_datap->db_type == M_CTL) {
24869 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24870 		if (!io->ipsec_out_secure) {
24871 			/*
24872 			 * This ipsec_out_t was allocated in ip_wput
24873 			 * for multicast packets to store the ill_index.
24874 			 * As this is being delivered locally, we don't
24875 			 * need this anymore.
24876 			 */
24877 			mp = first_mp->b_cont;
24878 			freeb(first_mp);
24879 			first_mp = mp;
24880 			mctl_present = B_FALSE;
24881 		} else {
24882 			/*
24883 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24884 			 * security properties for the looped-back packet.
24885 			 */
24886 			mctl_present = B_TRUE;
24887 			mp = first_mp->b_cont;
24888 			ASSERT(mp != NULL);
24889 			ipsec_out_to_in(first_mp);
24890 		}
24891 	} else {
24892 		mctl_present = B_FALSE;
24893 	}
24894 
24895 	DTRACE_PROBE4(ip4__loopback__in__start,
24896 	    ill_t *, ill, ill_t *, NULL,
24897 	    ipha_t *, ipha, mblk_t *, first_mp);
24898 
24899 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24900 	    ipst->ips_ipv4firewall_loopback_in,
24901 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24902 
24903 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24904 
24905 	if (first_mp == NULL)
24906 		return;
24907 
24908 	if (ipst->ips_ip4_observe.he_interested) {
24909 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
24910 		zoneid_t stackzoneid = netstackid_to_zoneid(
24911 		    ipst->ips_netstack->netstack_stackid);
24912 
24913 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
24914 		/*
24915 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
24916 		 * address.  Restrict the lookup below to the destination zone.
24917 		 */
24918 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
24919 			lookup_zoneid = zoneid;
24920 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
24921 		    lookup_zoneid);
24922 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill, ipst);
24923 	}
24924 
24925 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
24926 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
24927 	    int, 1);
24928 
24929 	ipst->ips_loopback_packets++;
24930 
24931 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24932 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24933 	if (!IS_SIMPLE_IPH(ipha)) {
24934 		ip_wput_local_options(ipha, ipst);
24935 	}
24936 
24937 	protocol = ipha->ipha_protocol;
24938 	switch (protocol) {
24939 	case IPPROTO_ICMP: {
24940 		ire_t		*ire_zone;
24941 		ilm_t		*ilm;
24942 		mblk_t		*mp1;
24943 		zoneid_t	last_zoneid;
24944 		ilm_walker_t	ilw;
24945 
24946 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24947 			ASSERT(ire_type == IRE_BROADCAST);
24948 			/*
24949 			 * In the multicast case, applications may have joined
24950 			 * the group from different zones, so we need to deliver
24951 			 * the packet to each of them. Loop through the
24952 			 * multicast memberships structures (ilm) on the receive
24953 			 * ill and send a copy of the packet up each matching
24954 			 * one. However, we don't do this for multicasts sent on
24955 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24956 			 * they must stay in the sender's zone.
24957 			 *
24958 			 * ilm_add_v6() ensures that ilms in the same zone are
24959 			 * contiguous in the ill_ilm list. We use this property
24960 			 * to avoid sending duplicates needed when two
24961 			 * applications in the same zone join the same group on
24962 			 * different logical interfaces: we ignore the ilm if
24963 			 * it's zoneid is the same as the last matching one.
24964 			 * In addition, the sending of the packet for
24965 			 * ire_zoneid is delayed until all of the other ilms
24966 			 * have been exhausted.
24967 			 */
24968 			last_zoneid = -1;
24969 			ilm = ilm_walker_start(&ilw, ill);
24970 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
24971 				if (ipha->ipha_dst != ilm->ilm_addr ||
24972 				    ilm->ilm_zoneid == last_zoneid ||
24973 				    ilm->ilm_zoneid == zoneid ||
24974 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24975 					continue;
24976 				mp1 = ip_copymsg(first_mp);
24977 				if (mp1 == NULL)
24978 					continue;
24979 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
24980 				    0, 0, mctl_present, B_FALSE, ill,
24981 				    ilm->ilm_zoneid);
24982 				last_zoneid = ilm->ilm_zoneid;
24983 			}
24984 			ilm_walker_finish(&ilw);
24985 			/*
24986 			 * Loopback case: the sending endpoint has
24987 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24988 			 * dispatch the multicast packet to the sending zone.
24989 			 */
24990 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24991 				freemsg(first_mp);
24992 				return;
24993 			}
24994 		} else if (ire_type == IRE_BROADCAST) {
24995 			/*
24996 			 * In the broadcast case, there may be many zones
24997 			 * which need a copy of the packet delivered to them.
24998 			 * There is one IRE_BROADCAST per broadcast address
24999 			 * and per zone; we walk those using a helper function.
25000 			 * In addition, the sending of the packet for zoneid is
25001 			 * delayed until all of the other ires have been
25002 			 * processed.
25003 			 */
25004 			IRB_REFHOLD(ire->ire_bucket);
25005 			ire_zone = NULL;
25006 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25007 			    ire)) != NULL) {
25008 				mp1 = ip_copymsg(first_mp);
25009 				if (mp1 == NULL)
25010 					continue;
25011 
25012 				UPDATE_IB_PKT_COUNT(ire_zone);
25013 				ire_zone->ire_last_used_time = lbolt;
25014 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25015 				    mctl_present, B_FALSE, ill,
25016 				    ire_zone->ire_zoneid);
25017 			}
25018 			IRB_REFRELE(ire->ire_bucket);
25019 		}
25020 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25021 		    0, mctl_present, B_FALSE, ill, zoneid);
25022 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25023 		    "ip_wput_local_end: q %p (%S)",
25024 		    q, "icmp");
25025 		return;
25026 	}
25027 	case IPPROTO_IGMP:
25028 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25029 			/* Bad packet - discarded by igmp_input */
25030 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25031 			    "ip_wput_local_end: q %p (%S)",
25032 			    q, "igmp_input--bad packet");
25033 			if (mctl_present)
25034 				freeb(first_mp);
25035 			return;
25036 		}
25037 		/*
25038 		 * igmp_input() may have returned the pulled up message.
25039 		 * So first_mp and ipha need to be reinitialized.
25040 		 */
25041 		ipha = (ipha_t *)mp->b_rptr;
25042 		if (mctl_present)
25043 			first_mp->b_cont = mp;
25044 		else
25045 			first_mp = mp;
25046 		/* deliver to local raw users */
25047 		break;
25048 	case IPPROTO_ENCAP:
25049 		/*
25050 		 * This case is covered by either ip_fanout_proto, or by
25051 		 * the above security processing for self-tunneled packets.
25052 		 */
25053 		break;
25054 	case IPPROTO_UDP: {
25055 		uint16_t	*up;
25056 		uint32_t	ports;
25057 
25058 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25059 		    UDP_PORTS_OFFSET);
25060 		/* Force a 'valid' checksum. */
25061 		up[3] = 0;
25062 
25063 		ports = *(uint32_t *)up;
25064 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25065 		    (ire_type == IRE_BROADCAST),
25066 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25067 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25068 		    ill, zoneid);
25069 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25070 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25071 		return;
25072 	}
25073 	case IPPROTO_TCP: {
25074 
25075 		/*
25076 		 * For TCP, discard broadcast packets.
25077 		 */
25078 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25079 			freemsg(first_mp);
25080 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25081 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25082 			return;
25083 		}
25084 
25085 		if (mp->b_datap->db_type == M_DATA) {
25086 			/*
25087 			 * M_DATA mblk, so init mblk (chain) for no struio().
25088 			 */
25089 			mblk_t	*mp1 = mp;
25090 
25091 			do {
25092 				mp1->b_datap->db_struioflag = 0;
25093 			} while ((mp1 = mp1->b_cont) != NULL);
25094 		}
25095 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25096 		    <= mp->b_wptr);
25097 		ip_fanout_tcp(q, first_mp, ill, ipha,
25098 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25099 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25100 		    mctl_present, B_FALSE, zoneid);
25101 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25102 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25103 		return;
25104 	}
25105 	case IPPROTO_SCTP:
25106 	{
25107 		uint32_t	ports;
25108 
25109 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25110 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25111 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25112 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25113 		return;
25114 	}
25115 
25116 	default:
25117 		break;
25118 	}
25119 	/*
25120 	 * Find a client for some other protocol.  We give
25121 	 * copies to multiple clients, if more than one is
25122 	 * bound.
25123 	 */
25124 	ip_fanout_proto(q, first_mp, ill, ipha,
25125 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25126 	    mctl_present, B_FALSE, ill, zoneid);
25127 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25128 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25129 #undef	rptr
25130 }
25131 
25132 /*
25133  * Update any source route, record route, or timestamp options.
25134  * Check that we are at end of strict source route.
25135  * The options have been sanity checked by ip_wput_options().
25136  */
25137 static void
25138 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25139 {
25140 	ipoptp_t	opts;
25141 	uchar_t		*opt;
25142 	uint8_t		optval;
25143 	uint8_t		optlen;
25144 	ipaddr_t	dst;
25145 	uint32_t	ts;
25146 	ire_t		*ire;
25147 	timestruc_t	now;
25148 
25149 	ip2dbg(("ip_wput_local_options\n"));
25150 	for (optval = ipoptp_first(&opts, ipha);
25151 	    optval != IPOPT_EOL;
25152 	    optval = ipoptp_next(&opts)) {
25153 		opt = opts.ipoptp_cur;
25154 		optlen = opts.ipoptp_len;
25155 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25156 		switch (optval) {
25157 			uint32_t off;
25158 		case IPOPT_SSRR:
25159 		case IPOPT_LSRR:
25160 			off = opt[IPOPT_OFFSET];
25161 			off--;
25162 			if (optlen < IP_ADDR_LEN ||
25163 			    off > optlen - IP_ADDR_LEN) {
25164 				/* End of source route */
25165 				break;
25166 			}
25167 			/*
25168 			 * This will only happen if two consecutive entries
25169 			 * in the source route contains our address or if
25170 			 * it is a packet with a loose source route which
25171 			 * reaches us before consuming the whole source route
25172 			 */
25173 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25174 			if (optval == IPOPT_SSRR) {
25175 				return;
25176 			}
25177 			/*
25178 			 * Hack: instead of dropping the packet truncate the
25179 			 * source route to what has been used by filling the
25180 			 * rest with IPOPT_NOP.
25181 			 */
25182 			opt[IPOPT_OLEN] = (uint8_t)off;
25183 			while (off < optlen) {
25184 				opt[off++] = IPOPT_NOP;
25185 			}
25186 			break;
25187 		case IPOPT_RR:
25188 			off = opt[IPOPT_OFFSET];
25189 			off--;
25190 			if (optlen < IP_ADDR_LEN ||
25191 			    off > optlen - IP_ADDR_LEN) {
25192 				/* No more room - ignore */
25193 				ip1dbg((
25194 				    "ip_wput_forward_options: end of RR\n"));
25195 				break;
25196 			}
25197 			dst = htonl(INADDR_LOOPBACK);
25198 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25199 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25200 			break;
25201 		case IPOPT_TS:
25202 			/* Insert timestamp if there is romm */
25203 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25204 			case IPOPT_TS_TSONLY:
25205 				off = IPOPT_TS_TIMELEN;
25206 				break;
25207 			case IPOPT_TS_PRESPEC:
25208 			case IPOPT_TS_PRESPEC_RFC791:
25209 				/* Verify that the address matched */
25210 				off = opt[IPOPT_OFFSET] - 1;
25211 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25212 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25213 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25214 				    ipst);
25215 				if (ire == NULL) {
25216 					/* Not for us */
25217 					break;
25218 				}
25219 				ire_refrele(ire);
25220 				/* FALLTHRU */
25221 			case IPOPT_TS_TSANDADDR:
25222 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25223 				break;
25224 			default:
25225 				/*
25226 				 * ip_*put_options should have already
25227 				 * dropped this packet.
25228 				 */
25229 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25230 				    "unknown IT - bug in ip_wput_options?\n");
25231 				return;	/* Keep "lint" happy */
25232 			}
25233 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25234 				/* Increase overflow counter */
25235 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25236 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25237 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25238 				    (off << 4);
25239 				break;
25240 			}
25241 			off = opt[IPOPT_OFFSET] - 1;
25242 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25243 			case IPOPT_TS_PRESPEC:
25244 			case IPOPT_TS_PRESPEC_RFC791:
25245 			case IPOPT_TS_TSANDADDR:
25246 				dst = htonl(INADDR_LOOPBACK);
25247 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25248 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25249 				/* FALLTHRU */
25250 			case IPOPT_TS_TSONLY:
25251 				off = opt[IPOPT_OFFSET] - 1;
25252 				/* Compute # of milliseconds since midnight */
25253 				gethrestime(&now);
25254 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25255 				    now.tv_nsec / (NANOSEC / MILLISEC);
25256 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25257 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25258 				break;
25259 			}
25260 			break;
25261 		}
25262 	}
25263 }
25264 
25265 /*
25266  * Send out a multicast packet on interface ipif.
25267  * The sender does not have an conn.
25268  * Caller verifies that this isn't a PHYI_LOOPBACK.
25269  */
25270 void
25271 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25272 {
25273 	ipha_t	*ipha;
25274 	ire_t	*ire;
25275 	ipaddr_t	dst;
25276 	mblk_t		*first_mp;
25277 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25278 
25279 	/* igmp_sendpkt always allocates a ipsec_out_t */
25280 	ASSERT(mp->b_datap->db_type == M_CTL);
25281 	ASSERT(!ipif->ipif_isv6);
25282 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25283 
25284 	first_mp = mp;
25285 	mp = first_mp->b_cont;
25286 	ASSERT(mp->b_datap->db_type == M_DATA);
25287 	ipha = (ipha_t *)mp->b_rptr;
25288 
25289 	/*
25290 	 * Find an IRE which matches the destination and the outgoing
25291 	 * queue (i.e. the outgoing interface.)
25292 	 */
25293 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25294 		dst = ipif->ipif_pp_dst_addr;
25295 	else
25296 		dst = ipha->ipha_dst;
25297 	/*
25298 	 * The source address has already been initialized by the
25299 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25300 	 * be sufficient rather than MATCH_IRE_IPIF.
25301 	 *
25302 	 * This function is used for sending IGMP packets.  For IPMP,
25303 	 * we sidestep IGMP snooping issues by sending all multicast
25304 	 * traffic on a single interface in the IPMP group.
25305 	 */
25306 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25307 	    MATCH_IRE_ILL, ipst);
25308 	if (!ire) {
25309 		/*
25310 		 * Mark this packet to make it be delivered to
25311 		 * ip_wput_ire after the new ire has been
25312 		 * created.
25313 		 */
25314 		mp->b_prev = NULL;
25315 		mp->b_next = NULL;
25316 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25317 		    zoneid, &zero_info);
25318 		return;
25319 	}
25320 
25321 	/*
25322 	 * Honor the RTF_SETSRC flag; this is the only case
25323 	 * where we force this addr whatever the current src addr is,
25324 	 * because this address is set by igmp_sendpkt(), and
25325 	 * cannot be specified by any user.
25326 	 */
25327 	if (ire->ire_flags & RTF_SETSRC) {
25328 		ipha->ipha_src = ire->ire_src_addr;
25329 	}
25330 
25331 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25332 }
25333 
25334 /*
25335  * NOTE : This function does not ire_refrele the ire argument passed in.
25336  *
25337  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25338  * failure. The nce_fp_mp can vanish any time in the case of
25339  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25340  * the ire_lock to access the nce_fp_mp in this case.
25341  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25342  * prepending a fastpath message IPQoS processing must precede it, we also set
25343  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25344  * (IPQoS might have set the b_band for CoS marking).
25345  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25346  * must follow it so that IPQoS can mark the dl_priority field for CoS
25347  * marking, if needed.
25348  */
25349 static mblk_t *
25350 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25351     uint32_t ill_index, ipha_t **iphap)
25352 {
25353 	uint_t	hlen;
25354 	ipha_t *ipha;
25355 	mblk_t *mp1;
25356 	boolean_t qos_done = B_FALSE;
25357 	uchar_t	*ll_hdr;
25358 	ip_stack_t	*ipst = ire->ire_ipst;
25359 
25360 #define	rptr	((uchar_t *)ipha)
25361 
25362 	ipha = (ipha_t *)mp->b_rptr;
25363 	hlen = 0;
25364 	LOCK_IRE_FP_MP(ire);
25365 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25366 		ASSERT(DB_TYPE(mp1) == M_DATA);
25367 		/* Initiate IPPF processing */
25368 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25369 			UNLOCK_IRE_FP_MP(ire);
25370 			ip_process(proc, &mp, ill_index);
25371 			if (mp == NULL)
25372 				return (NULL);
25373 
25374 			ipha = (ipha_t *)mp->b_rptr;
25375 			LOCK_IRE_FP_MP(ire);
25376 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25377 				qos_done = B_TRUE;
25378 				goto no_fp_mp;
25379 			}
25380 			ASSERT(DB_TYPE(mp1) == M_DATA);
25381 		}
25382 		hlen = MBLKL(mp1);
25383 		/*
25384 		 * Check if we have enough room to prepend fastpath
25385 		 * header
25386 		 */
25387 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25388 			ll_hdr = rptr - hlen;
25389 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25390 			/*
25391 			 * Set the b_rptr to the start of the link layer
25392 			 * header
25393 			 */
25394 			mp->b_rptr = ll_hdr;
25395 			mp1 = mp;
25396 		} else {
25397 			mp1 = copyb(mp1);
25398 			if (mp1 == NULL)
25399 				goto unlock_err;
25400 			mp1->b_band = mp->b_band;
25401 			mp1->b_cont = mp;
25402 			/*
25403 			 * XXX disable ICK_VALID and compute checksum
25404 			 * here; can happen if nce_fp_mp changes and
25405 			 * it can't be copied now due to insufficient
25406 			 * space. (unlikely, fp mp can change, but it
25407 			 * does not increase in length)
25408 			 */
25409 		}
25410 		UNLOCK_IRE_FP_MP(ire);
25411 	} else {
25412 no_fp_mp:
25413 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25414 		if (mp1 == NULL) {
25415 unlock_err:
25416 			UNLOCK_IRE_FP_MP(ire);
25417 			freemsg(mp);
25418 			return (NULL);
25419 		}
25420 		UNLOCK_IRE_FP_MP(ire);
25421 		mp1->b_cont = mp;
25422 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25423 			ip_process(proc, &mp1, ill_index);
25424 			if (mp1 == NULL)
25425 				return (NULL);
25426 
25427 			if (mp1->b_cont == NULL)
25428 				ipha = NULL;
25429 			else
25430 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25431 		}
25432 	}
25433 
25434 	*iphap = ipha;
25435 	return (mp1);
25436 #undef rptr
25437 }
25438 
25439 /*
25440  * Finish the outbound IPsec processing for an IPv6 packet. This function
25441  * is called from ipsec_out_process() if the IPsec packet was processed
25442  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25443  * asynchronously.
25444  */
25445 void
25446 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25447     ire_t *ire_arg)
25448 {
25449 	in6_addr_t *v6dstp;
25450 	ire_t *ire;
25451 	mblk_t *mp;
25452 	ip6_t *ip6h1;
25453 	uint_t	ill_index;
25454 	ipsec_out_t *io;
25455 	boolean_t hwaccel;
25456 	uint32_t flags = IP6_NO_IPPOLICY;
25457 	int match_flags;
25458 	zoneid_t zoneid;
25459 	boolean_t ill_need_rele = B_FALSE;
25460 	boolean_t ire_need_rele = B_FALSE;
25461 	ip_stack_t	*ipst;
25462 
25463 	mp = ipsec_mp->b_cont;
25464 	ip6h1 = (ip6_t *)mp->b_rptr;
25465 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25466 	ASSERT(io->ipsec_out_ns != NULL);
25467 	ipst = io->ipsec_out_ns->netstack_ip;
25468 	ill_index = io->ipsec_out_ill_index;
25469 	if (io->ipsec_out_reachable) {
25470 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25471 	}
25472 	hwaccel = io->ipsec_out_accelerated;
25473 	zoneid = io->ipsec_out_zoneid;
25474 	ASSERT(zoneid != ALL_ZONES);
25475 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25476 	/* Multicast addresses should have non-zero ill_index. */
25477 	v6dstp = &ip6h->ip6_dst;
25478 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25479 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25480 
25481 	if (ill == NULL && ill_index != 0) {
25482 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25483 		/* Failure case frees things for us. */
25484 		if (ill == NULL)
25485 			return;
25486 
25487 		ill_need_rele = B_TRUE;
25488 	}
25489 	ASSERT(mp != NULL);
25490 
25491 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25492 		boolean_t unspec_src;
25493 		ipif_t	*ipif;
25494 
25495 		/*
25496 		 * Use the ill_index to get the right ill.
25497 		 */
25498 		unspec_src = io->ipsec_out_unspec_src;
25499 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25500 		if (ipif == NULL) {
25501 			if (ill_need_rele)
25502 				ill_refrele(ill);
25503 			freemsg(ipsec_mp);
25504 			return;
25505 		}
25506 
25507 		if (ire_arg != NULL) {
25508 			ire = ire_arg;
25509 		} else {
25510 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25511 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25512 			ire_need_rele = B_TRUE;
25513 		}
25514 		if (ire != NULL) {
25515 			ipif_refrele(ipif);
25516 			/*
25517 			 * XXX Do the multicast forwarding now, as the IPsec
25518 			 * processing has been done.
25519 			 */
25520 			goto send;
25521 		}
25522 
25523 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25524 		mp->b_prev = NULL;
25525 		mp->b_next = NULL;
25526 
25527 		/*
25528 		 * If the IPsec packet was processed asynchronously,
25529 		 * drop it now.
25530 		 */
25531 		if (q == NULL) {
25532 			if (ill_need_rele)
25533 				ill_refrele(ill);
25534 			freemsg(ipsec_mp);
25535 			return;
25536 		}
25537 
25538 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25539 		    unspec_src, zoneid);
25540 		ipif_refrele(ipif);
25541 	} else {
25542 		if (ire_arg != NULL) {
25543 			ire = ire_arg;
25544 		} else {
25545 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25546 			ire_need_rele = B_TRUE;
25547 		}
25548 		if (ire != NULL)
25549 			goto send;
25550 		/*
25551 		 * ire disappeared underneath.
25552 		 *
25553 		 * What we need to do here is the ip_newroute
25554 		 * logic to get the ire without doing the IPsec
25555 		 * processing. Follow the same old path. But this
25556 		 * time, ip_wput or ire_add_then_send will call us
25557 		 * directly as all the IPsec operations are done.
25558 		 */
25559 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25560 		mp->b_prev = NULL;
25561 		mp->b_next = NULL;
25562 
25563 		/*
25564 		 * If the IPsec packet was processed asynchronously,
25565 		 * drop it now.
25566 		 */
25567 		if (q == NULL) {
25568 			if (ill_need_rele)
25569 				ill_refrele(ill);
25570 			freemsg(ipsec_mp);
25571 			return;
25572 		}
25573 
25574 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25575 		    zoneid, ipst);
25576 	}
25577 	if (ill != NULL && ill_need_rele)
25578 		ill_refrele(ill);
25579 	return;
25580 send:
25581 	if (ill != NULL && ill_need_rele)
25582 		ill_refrele(ill);
25583 
25584 	/* Local delivery */
25585 	if (ire->ire_stq == NULL) {
25586 		ill_t	*out_ill;
25587 		ASSERT(q != NULL);
25588 
25589 		/* PFHooks: LOOPBACK_OUT */
25590 		out_ill = ire_to_ill(ire);
25591 
25592 		/*
25593 		 * DTrace this as ip:::send.  A blocked packet will fire the
25594 		 * send probe, but not the receive probe.
25595 		 */
25596 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25597 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25598 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25599 
25600 		DTRACE_PROBE4(ip6__loopback__out__start,
25601 		    ill_t *, NULL, ill_t *, out_ill,
25602 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25603 
25604 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25605 		    ipst->ips_ipv6firewall_loopback_out,
25606 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25607 
25608 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25609 
25610 		if (ipsec_mp != NULL) {
25611 			ip_wput_local_v6(RD(q), out_ill,
25612 			    ip6h, ipsec_mp, ire, 0, zoneid);
25613 		}
25614 		if (ire_need_rele)
25615 			ire_refrele(ire);
25616 		return;
25617 	}
25618 	/*
25619 	 * Everything is done. Send it out on the wire.
25620 	 * We force the insertion of a fragment header using the
25621 	 * IPH_FRAG_HDR flag in two cases:
25622 	 * - after reception of an ICMPv6 "packet too big" message
25623 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25624 	 * - for multirouted IPv6 packets, so that the receiver can
25625 	 *   discard duplicates according to their fragment identifier
25626 	 */
25627 	/* XXX fix flow control problems. */
25628 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25629 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25630 		if (hwaccel) {
25631 			/*
25632 			 * hardware acceleration does not handle these
25633 			 * "slow path" cases.
25634 			 */
25635 			/* IPsec KSTATS: should bump bean counter here. */
25636 			if (ire_need_rele)
25637 				ire_refrele(ire);
25638 			freemsg(ipsec_mp);
25639 			return;
25640 		}
25641 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25642 		    (mp->b_cont ? msgdsize(mp) :
25643 		    mp->b_wptr - (uchar_t *)ip6h)) {
25644 			/* IPsec KSTATS: should bump bean counter here. */
25645 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25646 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25647 			    msgdsize(mp)));
25648 			if (ire_need_rele)
25649 				ire_refrele(ire);
25650 			freemsg(ipsec_mp);
25651 			return;
25652 		}
25653 		ASSERT(mp->b_prev == NULL);
25654 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25655 		    ntohs(ip6h->ip6_plen) +
25656 		    IPV6_HDR_LEN, ire->ire_max_frag));
25657 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25658 		    ire->ire_max_frag);
25659 	} else {
25660 		UPDATE_OB_PKT_COUNT(ire);
25661 		ire->ire_last_used_time = lbolt;
25662 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25663 	}
25664 	if (ire_need_rele)
25665 		ire_refrele(ire);
25666 	freeb(ipsec_mp);
25667 }
25668 
25669 void
25670 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25671 {
25672 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25673 	da_ipsec_t *hada;	/* data attributes */
25674 	ill_t *ill = (ill_t *)q->q_ptr;
25675 
25676 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25677 
25678 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25679 		/* IPsec KSTATS: Bump lose counter here! */
25680 		freemsg(mp);
25681 		return;
25682 	}
25683 
25684 	/*
25685 	 * It's an IPsec packet that must be
25686 	 * accelerated by the Provider, and the
25687 	 * outbound ill is IPsec acceleration capable.
25688 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25689 	 * to the ill.
25690 	 * IPsec KSTATS: should bump packet counter here.
25691 	 */
25692 
25693 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25694 	if (hada_mp == NULL) {
25695 		/* IPsec KSTATS: should bump packet counter here. */
25696 		freemsg(mp);
25697 		return;
25698 	}
25699 
25700 	hada_mp->b_datap->db_type = M_CTL;
25701 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25702 	hada_mp->b_cont = mp;
25703 
25704 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25705 	bzero(hada, sizeof (da_ipsec_t));
25706 	hada->da_type = IPHADA_M_CTL;
25707 
25708 	putnext(q, hada_mp);
25709 }
25710 
25711 /*
25712  * Finish the outbound IPsec processing. This function is called from
25713  * ipsec_out_process() if the IPsec packet was processed
25714  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25715  * asynchronously.
25716  */
25717 void
25718 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25719     ire_t *ire_arg)
25720 {
25721 	uint32_t v_hlen_tos_len;
25722 	ipaddr_t	dst;
25723 	ipif_t	*ipif = NULL;
25724 	ire_t *ire;
25725 	ire_t *ire1 = NULL;
25726 	mblk_t *next_mp = NULL;
25727 	uint32_t max_frag;
25728 	boolean_t multirt_send = B_FALSE;
25729 	mblk_t *mp;
25730 	ipha_t *ipha1;
25731 	uint_t	ill_index;
25732 	ipsec_out_t *io;
25733 	int match_flags;
25734 	irb_t *irb = NULL;
25735 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25736 	zoneid_t zoneid;
25737 	ipxmit_state_t	pktxmit_state;
25738 	ip_stack_t	*ipst;
25739 
25740 #ifdef	_BIG_ENDIAN
25741 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25742 #else
25743 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25744 #endif
25745 
25746 	mp = ipsec_mp->b_cont;
25747 	ipha1 = (ipha_t *)mp->b_rptr;
25748 	ASSERT(mp != NULL);
25749 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25750 	dst = ipha->ipha_dst;
25751 
25752 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25753 	ill_index = io->ipsec_out_ill_index;
25754 	zoneid = io->ipsec_out_zoneid;
25755 	ASSERT(zoneid != ALL_ZONES);
25756 	ipst = io->ipsec_out_ns->netstack_ip;
25757 	ASSERT(io->ipsec_out_ns != NULL);
25758 
25759 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25760 	if (ill == NULL && ill_index != 0) {
25761 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25762 		/* Failure case frees things for us. */
25763 		if (ill == NULL)
25764 			return;
25765 
25766 		ill_need_rele = B_TRUE;
25767 	}
25768 
25769 	if (CLASSD(dst)) {
25770 		boolean_t conn_dontroute;
25771 		/*
25772 		 * Use the ill_index to get the right ipif.
25773 		 */
25774 		conn_dontroute = io->ipsec_out_dontroute;
25775 		if (ill_index == 0)
25776 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25777 		else
25778 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25779 		if (ipif == NULL) {
25780 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25781 			    " multicast\n"));
25782 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25783 			freemsg(ipsec_mp);
25784 			goto done;
25785 		}
25786 		/*
25787 		 * ipha_src has already been intialized with the
25788 		 * value of the ipif in ip_wput. All we need now is
25789 		 * an ire to send this downstream.
25790 		 */
25791 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25792 		    msg_getlabel(mp), match_flags, ipst);
25793 		if (ire != NULL) {
25794 			ill_t *ill1;
25795 			/*
25796 			 * Do the multicast forwarding now, as the IPsec
25797 			 * processing has been done.
25798 			 */
25799 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25800 			    (ill1 = ire_to_ill(ire))) {
25801 				if (ip_mforward(ill1, ipha, mp)) {
25802 					freemsg(ipsec_mp);
25803 					ip1dbg(("ip_wput_ipsec_out: mforward "
25804 					    "failed\n"));
25805 					ire_refrele(ire);
25806 					goto done;
25807 				}
25808 			}
25809 			goto send;
25810 		}
25811 
25812 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25813 		mp->b_prev = NULL;
25814 		mp->b_next = NULL;
25815 
25816 		/*
25817 		 * If the IPsec packet was processed asynchronously,
25818 		 * drop it now.
25819 		 */
25820 		if (q == NULL) {
25821 			freemsg(ipsec_mp);
25822 			goto done;
25823 		}
25824 
25825 		/*
25826 		 * We may be using a wrong ipif to create the ire.
25827 		 * But it is okay as the source address is assigned
25828 		 * for the packet already. Next outbound packet would
25829 		 * create the IRE with the right IPIF in ip_wput.
25830 		 *
25831 		 * Also handle RTF_MULTIRT routes.
25832 		 */
25833 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25834 		    zoneid, &zero_info);
25835 	} else {
25836 		if (ire_arg != NULL) {
25837 			ire = ire_arg;
25838 			ire_need_rele = B_FALSE;
25839 		} else {
25840 			ire = ire_cache_lookup(dst, zoneid,
25841 			    msg_getlabel(mp), ipst);
25842 		}
25843 		if (ire != NULL) {
25844 			goto send;
25845 		}
25846 
25847 		/*
25848 		 * ire disappeared underneath.
25849 		 *
25850 		 * What we need to do here is the ip_newroute
25851 		 * logic to get the ire without doing the IPsec
25852 		 * processing. Follow the same old path. But this
25853 		 * time, ip_wput or ire_add_then_put will call us
25854 		 * directly as all the IPsec operations are done.
25855 		 */
25856 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25857 		mp->b_prev = NULL;
25858 		mp->b_next = NULL;
25859 
25860 		/*
25861 		 * If the IPsec packet was processed asynchronously,
25862 		 * drop it now.
25863 		 */
25864 		if (q == NULL) {
25865 			freemsg(ipsec_mp);
25866 			goto done;
25867 		}
25868 
25869 		/*
25870 		 * Since we're going through ip_newroute() again, we
25871 		 * need to make sure we don't:
25872 		 *
25873 		 *	1.) Trigger the ASSERT() with the ipha_ident
25874 		 *	    overloading.
25875 		 *	2.) Redo transport-layer checksumming, since we've
25876 		 *	    already done all that to get this far.
25877 		 *
25878 		 * The easiest way not do either of the above is to set
25879 		 * the ipha_ident field to IP_HDR_INCLUDED.
25880 		 */
25881 		ipha->ipha_ident = IP_HDR_INCLUDED;
25882 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25883 		    zoneid, ipst);
25884 	}
25885 	goto done;
25886 send:
25887 	if (ire->ire_stq == NULL) {
25888 		ill_t	*out_ill;
25889 		/*
25890 		 * Loopbacks go through ip_wput_local except for one case.
25891 		 * We come here if we generate a icmp_frag_needed message
25892 		 * after IPsec processing is over. When this function calls
25893 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25894 		 * icmp_frag_needed. The message generated comes back here
25895 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25896 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25897 		 * source address as it is usually set in ip_wput_ire. As
25898 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25899 		 * and we end up here. We can't enter ip_wput_ire once the
25900 		 * IPsec processing is over and hence we need to do it here.
25901 		 */
25902 		ASSERT(q != NULL);
25903 		UPDATE_OB_PKT_COUNT(ire);
25904 		ire->ire_last_used_time = lbolt;
25905 		if (ipha->ipha_src == 0)
25906 			ipha->ipha_src = ire->ire_src_addr;
25907 
25908 		/* PFHooks: LOOPBACK_OUT */
25909 		out_ill = ire_to_ill(ire);
25910 
25911 		/*
25912 		 * DTrace this as ip:::send.  A blocked packet will fire the
25913 		 * send probe, but not the receive probe.
25914 		 */
25915 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25916 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
25917 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
25918 
25919 		DTRACE_PROBE4(ip4__loopback__out__start,
25920 		    ill_t *, NULL, ill_t *, out_ill,
25921 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25922 
25923 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25924 		    ipst->ips_ipv4firewall_loopback_out,
25925 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
25926 
25927 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25928 
25929 		if (ipsec_mp != NULL)
25930 			ip_wput_local(RD(q), out_ill,
25931 			    ipha, ipsec_mp, ire, 0, zoneid);
25932 		if (ire_need_rele)
25933 			ire_refrele(ire);
25934 		goto done;
25935 	}
25936 
25937 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25938 		/*
25939 		 * We are through with IPsec processing.
25940 		 * Fragment this and send it on the wire.
25941 		 */
25942 		if (io->ipsec_out_accelerated) {
25943 			/*
25944 			 * The packet has been accelerated but must
25945 			 * be fragmented. This should not happen
25946 			 * since AH and ESP must not accelerate
25947 			 * packets that need fragmentation, however
25948 			 * the configuration could have changed
25949 			 * since the AH or ESP processing.
25950 			 * Drop packet.
25951 			 * IPsec KSTATS: bump bean counter here.
25952 			 */
25953 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25954 			    "fragmented accelerated packet!\n"));
25955 			freemsg(ipsec_mp);
25956 		} else {
25957 			ip_wput_ire_fragmentit(ipsec_mp, ire,
25958 			    zoneid, ipst, NULL);
25959 		}
25960 		if (ire_need_rele)
25961 			ire_refrele(ire);
25962 		goto done;
25963 	}
25964 
25965 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25966 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25967 	    (void *)ire->ire_ipif, (void *)ipif));
25968 
25969 	/*
25970 	 * Multiroute the secured packet.
25971 	 */
25972 	if (ire->ire_flags & RTF_MULTIRT) {
25973 		ire_t *first_ire;
25974 		irb = ire->ire_bucket;
25975 		ASSERT(irb != NULL);
25976 		/*
25977 		 * This ire has been looked up as the one that
25978 		 * goes through the given ipif;
25979 		 * make sure we do not omit any other multiroute ire
25980 		 * that may be present in the bucket before this one.
25981 		 */
25982 		IRB_REFHOLD(irb);
25983 		for (first_ire = irb->irb_ire;
25984 		    first_ire != NULL;
25985 		    first_ire = first_ire->ire_next) {
25986 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25987 			    (first_ire->ire_addr == ire->ire_addr) &&
25988 			    !(first_ire->ire_marks &
25989 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
25990 				break;
25991 		}
25992 
25993 		if ((first_ire != NULL) && (first_ire != ire)) {
25994 			/*
25995 			 * Don't change the ire if the packet must
25996 			 * be fragmented if sent via this new one.
25997 			 */
25998 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25999 				IRE_REFHOLD(first_ire);
26000 				if (ire_need_rele)
26001 					ire_refrele(ire);
26002 				else
26003 					ire_need_rele = B_TRUE;
26004 				ire = first_ire;
26005 			}
26006 		}
26007 		IRB_REFRELE(irb);
26008 
26009 		multirt_send = B_TRUE;
26010 		max_frag = ire->ire_max_frag;
26011 	}
26012 
26013 	/*
26014 	 * In most cases, the emission loop below is entered only once.
26015 	 * Only in the case where the ire holds the RTF_MULTIRT
26016 	 * flag, we loop to process all RTF_MULTIRT ires in the
26017 	 * bucket, and send the packet through all crossed
26018 	 * RTF_MULTIRT routes.
26019 	 */
26020 	do {
26021 		if (multirt_send) {
26022 			/*
26023 			 * ire1 holds here the next ire to process in the
26024 			 * bucket. If multirouting is expected,
26025 			 * any non-RTF_MULTIRT ire that has the
26026 			 * right destination address is ignored.
26027 			 */
26028 			ASSERT(irb != NULL);
26029 			IRB_REFHOLD(irb);
26030 			for (ire1 = ire->ire_next;
26031 			    ire1 != NULL;
26032 			    ire1 = ire1->ire_next) {
26033 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26034 					continue;
26035 				if (ire1->ire_addr != ire->ire_addr)
26036 					continue;
26037 				if (ire1->ire_marks &
26038 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26039 					continue;
26040 				/* No loopback here */
26041 				if (ire1->ire_stq == NULL)
26042 					continue;
26043 				/*
26044 				 * Ensure we do not exceed the MTU
26045 				 * of the next route.
26046 				 */
26047 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26048 					ip_multirt_bad_mtu(ire1, max_frag);
26049 					continue;
26050 				}
26051 
26052 				IRE_REFHOLD(ire1);
26053 				break;
26054 			}
26055 			IRB_REFRELE(irb);
26056 			if (ire1 != NULL) {
26057 				/*
26058 				 * We are in a multiple send case, need to
26059 				 * make a copy of the packet.
26060 				 */
26061 				next_mp = copymsg(ipsec_mp);
26062 				if (next_mp == NULL) {
26063 					ire_refrele(ire1);
26064 					ire1 = NULL;
26065 				}
26066 			}
26067 		}
26068 		/*
26069 		 * Everything is done. Send it out on the wire
26070 		 *
26071 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26072 		 * either send it on the wire or, in the case of
26073 		 * HW acceleration, call ipsec_hw_putnext.
26074 		 */
26075 		if (ire->ire_nce &&
26076 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26077 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26078 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26079 			/*
26080 			 * If ire's link-layer is unresolved (this
26081 			 * would only happen if the incomplete ire
26082 			 * was added to cachetable via forwarding path)
26083 			 * don't bother going to ip_xmit_v4. Just drop the
26084 			 * packet.
26085 			 * There is a slight risk here, in that, if we
26086 			 * have the forwarding path create an incomplete
26087 			 * IRE, then until the IRE is completed, any
26088 			 * transmitted IPsec packets will be dropped
26089 			 * instead of being queued waiting for resolution.
26090 			 *
26091 			 * But the likelihood of a forwarding packet and a wput
26092 			 * packet sending to the same dst at the same time
26093 			 * and there not yet be an ARP entry for it is small.
26094 			 * Furthermore, if this actually happens, it might
26095 			 * be likely that wput would generate multiple
26096 			 * packets (and forwarding would also have a train
26097 			 * of packets) for that destination. If this is
26098 			 * the case, some of them would have been dropped
26099 			 * anyway, since ARP only queues a few packets while
26100 			 * waiting for resolution
26101 			 *
26102 			 * NOTE: We should really call ip_xmit_v4,
26103 			 * and let it queue the packet and send the
26104 			 * ARP query and have ARP come back thus:
26105 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26106 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26107 			 * hw accel work. But it's too complex to get
26108 			 * the IPsec hw  acceleration approach to fit
26109 			 * well with ip_xmit_v4 doing ARP without
26110 			 * doing IPsec simplification. For now, we just
26111 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26112 			 * that we can continue with the send on the next
26113 			 * attempt.
26114 			 *
26115 			 * XXX THis should be revisited, when
26116 			 * the IPsec/IP interaction is cleaned up
26117 			 */
26118 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26119 			    " - dropping packet\n"));
26120 			freemsg(ipsec_mp);
26121 			/*
26122 			 * Call ip_xmit_v4() to trigger ARP query
26123 			 * in case the nce_state is ND_INITIAL
26124 			 */
26125 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26126 			goto drop_pkt;
26127 		}
26128 
26129 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26130 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26131 		    mblk_t *, ipsec_mp);
26132 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26133 		    ipst->ips_ipv4firewall_physical_out, NULL,
26134 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26135 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26136 		if (ipsec_mp == NULL)
26137 			goto drop_pkt;
26138 
26139 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26140 		pktxmit_state = ip_xmit_v4(mp, ire,
26141 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26142 
26143 		if ((pktxmit_state ==  SEND_FAILED) ||
26144 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26145 
26146 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26147 drop_pkt:
26148 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26149 			    ipIfStatsOutDiscards);
26150 			if (ire_need_rele)
26151 				ire_refrele(ire);
26152 			if (ire1 != NULL) {
26153 				ire_refrele(ire1);
26154 				freemsg(next_mp);
26155 			}
26156 			goto done;
26157 		}
26158 
26159 		freeb(ipsec_mp);
26160 		if (ire_need_rele)
26161 			ire_refrele(ire);
26162 
26163 		if (ire1 != NULL) {
26164 			ire = ire1;
26165 			ire_need_rele = B_TRUE;
26166 			ASSERT(next_mp);
26167 			ipsec_mp = next_mp;
26168 			mp = ipsec_mp->b_cont;
26169 			ire1 = NULL;
26170 			next_mp = NULL;
26171 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26172 		} else {
26173 			multirt_send = B_FALSE;
26174 		}
26175 	} while (multirt_send);
26176 done:
26177 	if (ill != NULL && ill_need_rele)
26178 		ill_refrele(ill);
26179 	if (ipif != NULL)
26180 		ipif_refrele(ipif);
26181 }
26182 
26183 /*
26184  * Get the ill corresponding to the specified ire, and compare its
26185  * capabilities with the protocol and algorithms specified by the
26186  * the SA obtained from ipsec_out. If they match, annotate the
26187  * ipsec_out structure to indicate that the packet needs acceleration.
26188  *
26189  *
26190  * A packet is eligible for outbound hardware acceleration if the
26191  * following conditions are satisfied:
26192  *
26193  * 1. the packet will not be fragmented
26194  * 2. the provider supports the algorithm
26195  * 3. there is no pending control message being exchanged
26196  * 4. snoop is not attached
26197  * 5. the destination address is not a broadcast or multicast address.
26198  *
26199  * Rationale:
26200  *	- Hardware drivers do not support fragmentation with
26201  *	  the current interface.
26202  *	- snoop, multicast, and broadcast may result in exposure of
26203  *	  a cleartext datagram.
26204  * We check all five of these conditions here.
26205  *
26206  * XXX would like to nuke "ire_t *" parameter here; problem is that
26207  * IRE is only way to figure out if a v4 address is a broadcast and
26208  * thus ineligible for acceleration...
26209  */
26210 static void
26211 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26212 {
26213 	ipsec_out_t *io;
26214 	mblk_t *data_mp;
26215 	uint_t plen, overhead;
26216 	ip_stack_t	*ipst;
26217 	phyint_t	*phyint;
26218 
26219 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26220 		return;
26221 
26222 	if (ill == NULL)
26223 		return;
26224 	ipst = ill->ill_ipst;
26225 	phyint = ill->ill_phyint;
26226 
26227 	/*
26228 	 * Destination address is a broadcast or multicast.  Punt.
26229 	 */
26230 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26231 	    IRE_LOCAL)))
26232 		return;
26233 
26234 	data_mp = ipsec_mp->b_cont;
26235 
26236 	if (ill->ill_isv6) {
26237 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26238 
26239 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26240 			return;
26241 
26242 		plen = ip6h->ip6_plen;
26243 	} else {
26244 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26245 
26246 		if (CLASSD(ipha->ipha_dst))
26247 			return;
26248 
26249 		plen = ipha->ipha_length;
26250 	}
26251 	/*
26252 	 * Is there a pending DLPI control message being exchanged
26253 	 * between IP/IPsec and the DLS Provider? If there is, it
26254 	 * could be a SADB update, and the state of the DLS Provider
26255 	 * SADB might not be in sync with the SADB maintained by
26256 	 * IPsec. To avoid dropping packets or using the wrong keying
26257 	 * material, we do not accelerate this packet.
26258 	 */
26259 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26260 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26261 		    "ill_dlpi_pending! don't accelerate packet\n"));
26262 		return;
26263 	}
26264 
26265 	/*
26266 	 * Is the Provider in promiscous mode? If it does, we don't
26267 	 * accelerate the packet since it will bounce back up to the
26268 	 * listeners in the clear.
26269 	 */
26270 	if (phyint->phyint_flags & PHYI_PROMISC) {
26271 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26272 		    "ill in promiscous mode, don't accelerate packet\n"));
26273 		return;
26274 	}
26275 
26276 	/*
26277 	 * Will the packet require fragmentation?
26278 	 */
26279 
26280 	/*
26281 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26282 	 * as is used elsewhere.
26283 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26284 	 *	+ 2-byte trailer
26285 	 */
26286 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26287 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26288 
26289 	if ((plen + overhead) > ill->ill_max_mtu)
26290 		return;
26291 
26292 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26293 
26294 	/*
26295 	 * Can the ill accelerate this IPsec protocol and algorithm
26296 	 * specified by the SA?
26297 	 */
26298 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26299 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26300 		return;
26301 	}
26302 
26303 	/*
26304 	 * Tell AH or ESP that the outbound ill is capable of
26305 	 * accelerating this packet.
26306 	 */
26307 	io->ipsec_out_is_capab_ill = B_TRUE;
26308 }
26309 
26310 /*
26311  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26312  *
26313  * If this function returns B_TRUE, the requested SA's have been filled
26314  * into the ipsec_out_*_sa pointers.
26315  *
26316  * If the function returns B_FALSE, the packet has been "consumed", most
26317  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26318  *
26319  * The SA references created by the protocol-specific "select"
26320  * function will be released when the ipsec_mp is freed, thanks to the
26321  * ipsec_out_free destructor -- see spd.c.
26322  */
26323 static boolean_t
26324 ipsec_out_select_sa(mblk_t *ipsec_mp)
26325 {
26326 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26327 	ipsec_out_t *io;
26328 	ipsec_policy_t *pp;
26329 	ipsec_action_t *ap;
26330 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26331 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26332 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26333 
26334 	if (!io->ipsec_out_secure) {
26335 		/*
26336 		 * We came here by mistake.
26337 		 * Don't bother with ipsec processing
26338 		 * We should "discourage" this path in the future.
26339 		 */
26340 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26341 		return (B_FALSE);
26342 	}
26343 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26344 	ASSERT((io->ipsec_out_policy != NULL) ||
26345 	    (io->ipsec_out_act != NULL));
26346 
26347 	ASSERT(io->ipsec_out_failed == B_FALSE);
26348 
26349 	/*
26350 	 * IPsec processing has started.
26351 	 */
26352 	io->ipsec_out_proc_begin = B_TRUE;
26353 	ap = io->ipsec_out_act;
26354 	if (ap == NULL) {
26355 		pp = io->ipsec_out_policy;
26356 		ASSERT(pp != NULL);
26357 		ap = pp->ipsp_act;
26358 		ASSERT(ap != NULL);
26359 	}
26360 
26361 	/*
26362 	 * We have an action.  now, let's select SA's.
26363 	 * (In the future, we can cache this in the conn_t..)
26364 	 */
26365 	if (ap->ipa_want_esp) {
26366 		if (io->ipsec_out_esp_sa == NULL) {
26367 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26368 			    IPPROTO_ESP);
26369 		}
26370 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26371 	}
26372 
26373 	if (ap->ipa_want_ah) {
26374 		if (io->ipsec_out_ah_sa == NULL) {
26375 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26376 			    IPPROTO_AH);
26377 		}
26378 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26379 		/*
26380 		 * The ESP and AH processing order needs to be preserved
26381 		 * when both protocols are required (ESP should be applied
26382 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26383 		 * when both ESP and AH are required, and an AH ACQUIRE
26384 		 * is needed.
26385 		 */
26386 		if (ap->ipa_want_esp && need_ah_acquire)
26387 			need_esp_acquire = B_TRUE;
26388 	}
26389 
26390 	/*
26391 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26392 	 * Release SAs that got referenced, but will not be used until we
26393 	 * acquire _all_ of the SAs we need.
26394 	 */
26395 	if (need_ah_acquire || need_esp_acquire) {
26396 		if (io->ipsec_out_ah_sa != NULL) {
26397 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26398 			io->ipsec_out_ah_sa = NULL;
26399 		}
26400 		if (io->ipsec_out_esp_sa != NULL) {
26401 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26402 			io->ipsec_out_esp_sa = NULL;
26403 		}
26404 
26405 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26406 		return (B_FALSE);
26407 	}
26408 
26409 	return (B_TRUE);
26410 }
26411 
26412 /*
26413  * Process an IPSEC_OUT message and see what you can
26414  * do with it.
26415  * IPQoS Notes:
26416  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26417  * IPsec.
26418  * XXX would like to nuke ire_t.
26419  * XXX ill_index better be "real"
26420  */
26421 void
26422 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26423 {
26424 	ipsec_out_t *io;
26425 	ipsec_policy_t *pp;
26426 	ipsec_action_t *ap;
26427 	ipha_t *ipha;
26428 	ip6_t *ip6h;
26429 	mblk_t *mp;
26430 	ill_t *ill;
26431 	zoneid_t zoneid;
26432 	ipsec_status_t ipsec_rc;
26433 	boolean_t ill_need_rele = B_FALSE;
26434 	ip_stack_t	*ipst;
26435 	ipsec_stack_t	*ipss;
26436 
26437 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26438 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26439 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26440 	ipst = io->ipsec_out_ns->netstack_ip;
26441 	mp = ipsec_mp->b_cont;
26442 
26443 	/*
26444 	 * Initiate IPPF processing. We do it here to account for packets
26445 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26446 	 * We can check for ipsec_out_proc_begin even for such packets, as
26447 	 * they will always be false (asserted below).
26448 	 */
26449 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26450 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26451 		    io->ipsec_out_ill_index : ill_index);
26452 		if (mp == NULL) {
26453 			ip2dbg(("ipsec_out_process: packet dropped "\
26454 			    "during IPPF processing\n"));
26455 			freeb(ipsec_mp);
26456 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26457 			return;
26458 		}
26459 	}
26460 
26461 	if (!io->ipsec_out_secure) {
26462 		/*
26463 		 * We came here by mistake.
26464 		 * Don't bother with ipsec processing
26465 		 * Should "discourage" this path in the future.
26466 		 */
26467 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26468 		goto done;
26469 	}
26470 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26471 	ASSERT((io->ipsec_out_policy != NULL) ||
26472 	    (io->ipsec_out_act != NULL));
26473 	ASSERT(io->ipsec_out_failed == B_FALSE);
26474 
26475 	ipss = ipst->ips_netstack->netstack_ipsec;
26476 	if (!ipsec_loaded(ipss)) {
26477 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26478 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26479 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26480 		} else {
26481 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26482 		}
26483 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26484 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26485 		    &ipss->ipsec_dropper);
26486 		return;
26487 	}
26488 
26489 	/*
26490 	 * IPsec processing has started.
26491 	 */
26492 	io->ipsec_out_proc_begin = B_TRUE;
26493 	ap = io->ipsec_out_act;
26494 	if (ap == NULL) {
26495 		pp = io->ipsec_out_policy;
26496 		ASSERT(pp != NULL);
26497 		ap = pp->ipsp_act;
26498 		ASSERT(ap != NULL);
26499 	}
26500 
26501 	/*
26502 	 * Save the outbound ill index. When the packet comes back
26503 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26504 	 * before sending it the accelerated packet.
26505 	 */
26506 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26507 		ill = ire_to_ill(ire);
26508 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26509 	}
26510 
26511 	/*
26512 	 * The order of processing is first insert a IP header if needed.
26513 	 * Then insert the ESP header and then the AH header.
26514 	 */
26515 	if ((io->ipsec_out_se_done == B_FALSE) &&
26516 	    (ap->ipa_want_se)) {
26517 		/*
26518 		 * First get the outer IP header before sending
26519 		 * it to ESP.
26520 		 */
26521 		ipha_t *oipha, *iipha;
26522 		mblk_t *outer_mp, *inner_mp;
26523 
26524 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26525 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26526 			    "ipsec_out_process: "
26527 			    "Self-Encapsulation failed: Out of memory\n");
26528 			freemsg(ipsec_mp);
26529 			if (ill != NULL) {
26530 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26531 			} else {
26532 				BUMP_MIB(&ipst->ips_ip_mib,
26533 				    ipIfStatsOutDiscards);
26534 			}
26535 			return;
26536 		}
26537 		inner_mp = ipsec_mp->b_cont;
26538 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26539 		oipha = (ipha_t *)outer_mp->b_rptr;
26540 		iipha = (ipha_t *)inner_mp->b_rptr;
26541 		*oipha = *iipha;
26542 		outer_mp->b_wptr += sizeof (ipha_t);
26543 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26544 		    sizeof (ipha_t));
26545 		oipha->ipha_protocol = IPPROTO_ENCAP;
26546 		oipha->ipha_version_and_hdr_length =
26547 		    IP_SIMPLE_HDR_VERSION;
26548 		oipha->ipha_hdr_checksum = 0;
26549 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26550 		outer_mp->b_cont = inner_mp;
26551 		ipsec_mp->b_cont = outer_mp;
26552 
26553 		io->ipsec_out_se_done = B_TRUE;
26554 		io->ipsec_out_tunnel = B_TRUE;
26555 	}
26556 
26557 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26558 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26559 	    !ipsec_out_select_sa(ipsec_mp))
26560 		return;
26561 
26562 	/*
26563 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26564 	 * to do the heavy lifting.
26565 	 */
26566 	zoneid = io->ipsec_out_zoneid;
26567 	ASSERT(zoneid != ALL_ZONES);
26568 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26569 		ASSERT(io->ipsec_out_esp_sa != NULL);
26570 		io->ipsec_out_esp_done = B_TRUE;
26571 		/*
26572 		 * Note that since hw accel can only apply one transform,
26573 		 * not two, we skip hw accel for ESP if we also have AH
26574 		 * This is an design limitation of the interface
26575 		 * which should be revisited.
26576 		 */
26577 		ASSERT(ire != NULL);
26578 		if (io->ipsec_out_ah_sa == NULL) {
26579 			ill = (ill_t *)ire->ire_stq->q_ptr;
26580 			ipsec_out_is_accelerated(ipsec_mp,
26581 			    io->ipsec_out_esp_sa, ill, ire);
26582 		}
26583 
26584 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26585 		switch (ipsec_rc) {
26586 		case IPSEC_STATUS_SUCCESS:
26587 			break;
26588 		case IPSEC_STATUS_FAILED:
26589 			if (ill != NULL) {
26590 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26591 			} else {
26592 				BUMP_MIB(&ipst->ips_ip_mib,
26593 				    ipIfStatsOutDiscards);
26594 			}
26595 			/* FALLTHRU */
26596 		case IPSEC_STATUS_PENDING:
26597 			return;
26598 		}
26599 	}
26600 
26601 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26602 		ASSERT(io->ipsec_out_ah_sa != NULL);
26603 		io->ipsec_out_ah_done = B_TRUE;
26604 		if (ire == NULL) {
26605 			int idx = io->ipsec_out_capab_ill_index;
26606 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26607 			    NULL, NULL, NULL, NULL, ipst);
26608 			ill_need_rele = B_TRUE;
26609 		} else {
26610 			ill = (ill_t *)ire->ire_stq->q_ptr;
26611 		}
26612 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26613 		    ire);
26614 
26615 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26616 		switch (ipsec_rc) {
26617 		case IPSEC_STATUS_SUCCESS:
26618 			break;
26619 		case IPSEC_STATUS_FAILED:
26620 			if (ill != NULL) {
26621 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26622 			} else {
26623 				BUMP_MIB(&ipst->ips_ip_mib,
26624 				    ipIfStatsOutDiscards);
26625 			}
26626 			/* FALLTHRU */
26627 		case IPSEC_STATUS_PENDING:
26628 			if (ill != NULL && ill_need_rele)
26629 				ill_refrele(ill);
26630 			return;
26631 		}
26632 	}
26633 	/*
26634 	 * We are done with IPsec processing. Send it over the wire.
26635 	 */
26636 done:
26637 	mp = ipsec_mp->b_cont;
26638 	ipha = (ipha_t *)mp->b_rptr;
26639 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26640 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26641 		    ire);
26642 	} else {
26643 		ip6h = (ip6_t *)ipha;
26644 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26645 		    ire);
26646 	}
26647 	if (ill != NULL && ill_need_rele)
26648 		ill_refrele(ill);
26649 }
26650 
26651 /* ARGSUSED */
26652 void
26653 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26654 {
26655 	opt_restart_t	*or;
26656 	int	err;
26657 	conn_t	*connp;
26658 	cred_t	*cr;
26659 
26660 	ASSERT(CONN_Q(q));
26661 	connp = Q_TO_CONN(q);
26662 
26663 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26664 	or = (opt_restart_t *)first_mp->b_rptr;
26665 	/*
26666 	 * We checked for a db_credp the first time svr4_optcom_req
26667 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26668 	 */
26669 	cr = msg_getcred(first_mp, NULL);
26670 	ASSERT(cr != NULL);
26671 
26672 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26673 		err = svr4_optcom_req(q, first_mp, cr,
26674 		    &ip_opt_obj, B_FALSE);
26675 	} else {
26676 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26677 		err = tpi_optcom_req(q, first_mp, cr,
26678 		    &ip_opt_obj, B_FALSE);
26679 	}
26680 	if (err != EINPROGRESS) {
26681 		/* operation is done */
26682 		CONN_OPER_PENDING_DONE(connp);
26683 	}
26684 }
26685 
26686 /*
26687  * ioctls that go through a down/up sequence may need to wait for the down
26688  * to complete. This involves waiting for the ire and ipif refcnts to go down
26689  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26690  */
26691 /* ARGSUSED */
26692 void
26693 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26694 {
26695 	struct iocblk *iocp;
26696 	mblk_t *mp1;
26697 	ip_ioctl_cmd_t *ipip;
26698 	int err;
26699 	sin_t	*sin;
26700 	struct lifreq *lifr;
26701 	struct ifreq *ifr;
26702 
26703 	iocp = (struct iocblk *)mp->b_rptr;
26704 	ASSERT(ipsq != NULL);
26705 	/* Existence of mp1 verified in ip_wput_nondata */
26706 	mp1 = mp->b_cont->b_cont;
26707 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26708 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26709 		/*
26710 		 * Special case where ipx_current_ipif is not set:
26711 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26712 		 * We are here as were not able to complete the operation in
26713 		 * ipif_set_values because we could not become exclusive on
26714 		 * the new ipsq.
26715 		 */
26716 		ill_t *ill = q->q_ptr;
26717 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26718 	}
26719 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26720 
26721 	if (ipip->ipi_cmd_type == IF_CMD) {
26722 		/* This a old style SIOC[GS]IF* command */
26723 		ifr = (struct ifreq *)mp1->b_rptr;
26724 		sin = (sin_t *)&ifr->ifr_addr;
26725 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26726 		/* This a new style SIOC[GS]LIF* command */
26727 		lifr = (struct lifreq *)mp1->b_rptr;
26728 		sin = (sin_t *)&lifr->lifr_addr;
26729 	} else {
26730 		sin = NULL;
26731 	}
26732 
26733 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26734 	    q, mp, ipip, mp1->b_rptr);
26735 
26736 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26737 }
26738 
26739 /*
26740  * ioctl processing
26741  *
26742  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26743  * the ioctl command in the ioctl tables, determines the copyin data size
26744  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26745  *
26746  * ioctl processing then continues when the M_IOCDATA makes its way down to
26747  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26748  * associated 'conn' is refheld till the end of the ioctl and the general
26749  * ioctl processing function ip_process_ioctl() is called to extract the
26750  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26751  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26752  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26753  * is used to extract the ioctl's arguments.
26754  *
26755  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26756  * so goes thru the serialization primitive ipsq_try_enter. Then the
26757  * appropriate function to handle the ioctl is called based on the entry in
26758  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26759  * which also refreleases the 'conn' that was refheld at the start of the
26760  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26761  *
26762  * Many exclusive ioctls go thru an internal down up sequence as part of
26763  * the operation. For example an attempt to change the IP address of an
26764  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26765  * does all the cleanup such as deleting all ires that use this address.
26766  * Then we need to wait till all references to the interface go away.
26767  */
26768 void
26769 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26770 {
26771 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26772 	ip_ioctl_cmd_t *ipip = arg;
26773 	ip_extract_func_t *extract_funcp;
26774 	cmd_info_t ci;
26775 	int err;
26776 	boolean_t entered_ipsq = B_FALSE;
26777 
26778 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26779 
26780 	if (ipip == NULL)
26781 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26782 
26783 	/*
26784 	 * SIOCLIFADDIF needs to go thru a special path since the
26785 	 * ill may not exist yet. This happens in the case of lo0
26786 	 * which is created using this ioctl.
26787 	 */
26788 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26789 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26790 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26791 		return;
26792 	}
26793 
26794 	ci.ci_ipif = NULL;
26795 	if (ipip->ipi_cmd_type == MISC_CMD) {
26796 		/*
26797 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26798 		 */
26799 		if (ipip->ipi_cmd == IF_UNITSEL) {
26800 			/* ioctl comes down the ill */
26801 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26802 			ipif_refhold(ci.ci_ipif);
26803 		}
26804 		err = 0;
26805 		ci.ci_sin = NULL;
26806 		ci.ci_sin6 = NULL;
26807 		ci.ci_lifr = NULL;
26808 	} else {
26809 		switch (ipip->ipi_cmd_type) {
26810 		case IF_CMD:
26811 		case LIF_CMD:
26812 			extract_funcp = ip_extract_lifreq;
26813 			break;
26814 
26815 		case ARP_CMD:
26816 		case XARP_CMD:
26817 			extract_funcp = ip_extract_arpreq;
26818 			break;
26819 
26820 		case MSFILT_CMD:
26821 			extract_funcp = ip_extract_msfilter;
26822 			break;
26823 
26824 		default:
26825 			ASSERT(0);
26826 		}
26827 
26828 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26829 		if (err != 0) {
26830 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26831 			return;
26832 		}
26833 
26834 		/*
26835 		 * All of the extraction functions return a refheld ipif.
26836 		 */
26837 		ASSERT(ci.ci_ipif != NULL);
26838 	}
26839 
26840 	if (!(ipip->ipi_flags & IPI_WR)) {
26841 		/*
26842 		 * A return value of EINPROGRESS means the ioctl is
26843 		 * either queued and waiting for some reason or has
26844 		 * already completed.
26845 		 */
26846 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26847 		    ci.ci_lifr);
26848 		if (ci.ci_ipif != NULL)
26849 			ipif_refrele(ci.ci_ipif);
26850 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26851 		return;
26852 	}
26853 
26854 	ASSERT(ci.ci_ipif != NULL);
26855 
26856 	/*
26857 	 * If ipsq is non-NULL, we are already being called exclusively.
26858 	 */
26859 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26860 	if (ipsq == NULL) {
26861 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26862 		    NEW_OP, B_TRUE);
26863 		if (ipsq == NULL) {
26864 			ipif_refrele(ci.ci_ipif);
26865 			return;
26866 		}
26867 		entered_ipsq = B_TRUE;
26868 	}
26869 
26870 	/*
26871 	 * Release the ipif so that ipif_down and friends that wait for
26872 	 * references to go away are not misled about the current ipif_refcnt
26873 	 * values. We are writer so we can access the ipif even after releasing
26874 	 * the ipif.
26875 	 */
26876 	ipif_refrele(ci.ci_ipif);
26877 
26878 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26879 
26880 	/*
26881 	 * A return value of EINPROGRESS means the ioctl is
26882 	 * either queued and waiting for some reason or has
26883 	 * already completed.
26884 	 */
26885 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26886 
26887 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26888 
26889 	if (entered_ipsq)
26890 		ipsq_exit(ipsq);
26891 }
26892 
26893 /*
26894  * Complete the ioctl. Typically ioctls use the mi package and need to
26895  * do mi_copyout/mi_copy_done.
26896  */
26897 void
26898 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26899 {
26900 	conn_t	*connp = NULL;
26901 
26902 	if (err == EINPROGRESS)
26903 		return;
26904 
26905 	if (CONN_Q(q)) {
26906 		connp = Q_TO_CONN(q);
26907 		ASSERT(connp->conn_ref >= 2);
26908 	}
26909 
26910 	switch (mode) {
26911 	case COPYOUT:
26912 		if (err == 0)
26913 			mi_copyout(q, mp);
26914 		else
26915 			mi_copy_done(q, mp, err);
26916 		break;
26917 
26918 	case NO_COPYOUT:
26919 		mi_copy_done(q, mp, err);
26920 		break;
26921 
26922 	default:
26923 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26924 		break;
26925 	}
26926 
26927 	/*
26928 	 * The refhold placed at the start of the ioctl is released here.
26929 	 */
26930 	if (connp != NULL)
26931 		CONN_OPER_PENDING_DONE(connp);
26932 
26933 	if (ipsq != NULL)
26934 		ipsq_current_finish(ipsq);
26935 }
26936 
26937 /* Called from ip_wput for all non data messages */
26938 /* ARGSUSED */
26939 void
26940 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26941 {
26942 	mblk_t		*mp1;
26943 	ire_t		*ire, *fake_ire;
26944 	ill_t		*ill;
26945 	struct iocblk	*iocp;
26946 	ip_ioctl_cmd_t	*ipip;
26947 	cred_t		*cr;
26948 	conn_t		*connp;
26949 	int		err;
26950 	nce_t		*nce;
26951 	ipif_t		*ipif;
26952 	ip_stack_t	*ipst;
26953 	char		*proto_str;
26954 
26955 	if (CONN_Q(q)) {
26956 		connp = Q_TO_CONN(q);
26957 		ipst = connp->conn_netstack->netstack_ip;
26958 	} else {
26959 		connp = NULL;
26960 		ipst = ILLQ_TO_IPST(q);
26961 	}
26962 
26963 	switch (DB_TYPE(mp)) {
26964 	case M_IOCTL:
26965 		/*
26966 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26967 		 * will arrange to copy in associated control structures.
26968 		 */
26969 		ip_sioctl_copyin_setup(q, mp);
26970 		return;
26971 	case M_IOCDATA:
26972 		/*
26973 		 * Ensure that this is associated with one of our trans-
26974 		 * parent ioctls.  If it's not ours, discard it if we're
26975 		 * running as a driver, or pass it on if we're a module.
26976 		 */
26977 		iocp = (struct iocblk *)mp->b_rptr;
26978 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26979 		if (ipip == NULL) {
26980 			if (q->q_next == NULL) {
26981 				goto nak;
26982 			} else {
26983 				putnext(q, mp);
26984 			}
26985 			return;
26986 		}
26987 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
26988 			/*
26989 			 * the ioctl is one we recognise, but is not
26990 			 * consumed by IP as a module, pass M_IOCDATA
26991 			 * for processing downstream, but only for
26992 			 * common Streams ioctls.
26993 			 */
26994 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26995 				putnext(q, mp);
26996 				return;
26997 			} else {
26998 				goto nak;
26999 			}
27000 		}
27001 
27002 		/* IOCTL continuation following copyin or copyout. */
27003 		if (mi_copy_state(q, mp, NULL) == -1) {
27004 			/*
27005 			 * The copy operation failed.  mi_copy_state already
27006 			 * cleaned up, so we're out of here.
27007 			 */
27008 			return;
27009 		}
27010 		/*
27011 		 * If we just completed a copy in, we become writer and
27012 		 * continue processing in ip_sioctl_copyin_done.  If it
27013 		 * was a copy out, we call mi_copyout again.  If there is
27014 		 * nothing more to copy out, it will complete the IOCTL.
27015 		 */
27016 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27017 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27018 				mi_copy_done(q, mp, EPROTO);
27019 				return;
27020 			}
27021 			/*
27022 			 * Check for cases that need more copying.  A return
27023 			 * value of 0 means a second copyin has been started,
27024 			 * so we return; a return value of 1 means no more
27025 			 * copying is needed, so we continue.
27026 			 */
27027 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27028 			    MI_COPY_COUNT(mp) == 1) {
27029 				if (ip_copyin_msfilter(q, mp) == 0)
27030 					return;
27031 			}
27032 			/*
27033 			 * Refhold the conn, till the ioctl completes. This is
27034 			 * needed in case the ioctl ends up in the pending mp
27035 			 * list. Every mp in the ill_pending_mp list and
27036 			 * the ipx_pending_mp must have a refhold on the conn
27037 			 * to resume processing. The refhold is released when
27038 			 * the ioctl completes. (normally or abnormally)
27039 			 * In all cases ip_ioctl_finish is called to finish
27040 			 * the ioctl.
27041 			 */
27042 			if (connp != NULL) {
27043 				/* This is not a reentry */
27044 				ASSERT(ipsq == NULL);
27045 				CONN_INC_REF(connp);
27046 			} else {
27047 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27048 					mi_copy_done(q, mp, EINVAL);
27049 					return;
27050 				}
27051 			}
27052 
27053 			ip_process_ioctl(ipsq, q, mp, ipip);
27054 
27055 		} else {
27056 			mi_copyout(q, mp);
27057 		}
27058 		return;
27059 nak:
27060 		iocp->ioc_error = EINVAL;
27061 		mp->b_datap->db_type = M_IOCNAK;
27062 		iocp->ioc_count = 0;
27063 		qreply(q, mp);
27064 		return;
27065 
27066 	case M_IOCNAK:
27067 		/*
27068 		 * The only way we could get here is if a resolver didn't like
27069 		 * an IOCTL we sent it.	 This shouldn't happen.
27070 		 */
27071 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27072 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27073 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27074 		freemsg(mp);
27075 		return;
27076 	case M_IOCACK:
27077 		/* /dev/ip shouldn't see this */
27078 		if (CONN_Q(q))
27079 			goto nak;
27080 
27081 		/*
27082 		 * Finish socket ioctls passed through to ARP.  We use the
27083 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27084 		 * we need to become writer before calling ip_sioctl_iocack().
27085 		 * Note that qwriter_ip() will release the refhold, and that a
27086 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27087 		 * ill stream.
27088 		 */
27089 		iocp = (struct iocblk *)mp->b_rptr;
27090 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27091 			ip_sioctl_iocack(NULL, q, mp, NULL);
27092 			return;
27093 		}
27094 
27095 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27096 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27097 		ill = q->q_ptr;
27098 		ill_refhold(ill);
27099 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27100 		return;
27101 	case M_FLUSH:
27102 		if (*mp->b_rptr & FLUSHW)
27103 			flushq(q, FLUSHALL);
27104 		if (q->q_next) {
27105 			putnext(q, mp);
27106 			return;
27107 		}
27108 		if (*mp->b_rptr & FLUSHR) {
27109 			*mp->b_rptr &= ~FLUSHW;
27110 			qreply(q, mp);
27111 			return;
27112 		}
27113 		freemsg(mp);
27114 		return;
27115 	case IRE_DB_REQ_TYPE:
27116 		if (connp == NULL) {
27117 			proto_str = "IRE_DB_REQ_TYPE";
27118 			goto protonak;
27119 		}
27120 		/* An Upper Level Protocol wants a copy of an IRE. */
27121 		ip_ire_req(q, mp);
27122 		return;
27123 	case M_CTL:
27124 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27125 			break;
27126 
27127 		/* M_CTL messages are used by ARP to tell us things. */
27128 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27129 			break;
27130 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27131 		case AR_ENTRY_SQUERY:
27132 			putnext(q, mp);
27133 			return;
27134 		case AR_CLIENT_NOTIFY:
27135 			ip_arp_news(q, mp);
27136 			return;
27137 		case AR_DLPIOP_DONE:
27138 			ASSERT(q->q_next != NULL);
27139 			ill = (ill_t *)q->q_ptr;
27140 			/* qwriter_ip releases the refhold */
27141 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27142 			ill_refhold(ill);
27143 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27144 			return;
27145 		case AR_ARP_CLOSING:
27146 			/*
27147 			 * ARP (above us) is closing. If no ARP bringup is
27148 			 * currently pending, ack the message so that ARP
27149 			 * can complete its close. Also mark ill_arp_closing
27150 			 * so that new ARP bringups will fail. If any
27151 			 * ARP bringup is currently in progress, we will
27152 			 * ack this when the current ARP bringup completes.
27153 			 */
27154 			ASSERT(q->q_next != NULL);
27155 			ill = (ill_t *)q->q_ptr;
27156 			mutex_enter(&ill->ill_lock);
27157 			ill->ill_arp_closing = 1;
27158 			if (!ill->ill_arp_bringup_pending) {
27159 				mutex_exit(&ill->ill_lock);
27160 				qreply(q, mp);
27161 			} else {
27162 				mutex_exit(&ill->ill_lock);
27163 				freemsg(mp);
27164 			}
27165 			return;
27166 		case AR_ARP_EXTEND:
27167 			/*
27168 			 * The ARP module above us is capable of duplicate
27169 			 * address detection.  Old ATM drivers will not send
27170 			 * this message.
27171 			 */
27172 			ASSERT(q->q_next != NULL);
27173 			ill = (ill_t *)q->q_ptr;
27174 			ill->ill_arp_extend = B_TRUE;
27175 			freemsg(mp);
27176 			return;
27177 		default:
27178 			break;
27179 		}
27180 		break;
27181 	case M_PROTO:
27182 	case M_PCPROTO:
27183 		/*
27184 		 * The only PROTO messages we expect are copies of option
27185 		 * negotiation acknowledgements, AH and ESP bind requests
27186 		 * are also expected.
27187 		 */
27188 		switch (((union T_primitives *)mp->b_rptr)->type) {
27189 		case O_T_BIND_REQ:
27190 		case T_BIND_REQ: {
27191 			/* Request can get queued in bind */
27192 			if (connp == NULL) {
27193 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27194 				goto protonak;
27195 			}
27196 			/*
27197 			 * The transports except SCTP call ip_bind_{v4,v6}()
27198 			 * directly instead of a a putnext. SCTP doesn't
27199 			 * generate any T_BIND_REQ since it has its own
27200 			 * fanout data structures. However, ESP and AH
27201 			 * come in for regular binds; all other cases are
27202 			 * bind retries.
27203 			 */
27204 			ASSERT(!IPCL_IS_SCTP(connp));
27205 
27206 			/* Don't increment refcnt if this is a re-entry */
27207 			if (ipsq == NULL)
27208 				CONN_INC_REF(connp);
27209 
27210 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27211 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27212 			ASSERT(mp != NULL);
27213 
27214 			ASSERT(!IPCL_IS_TCP(connp));
27215 			ASSERT(!IPCL_IS_UDP(connp));
27216 			ASSERT(!IPCL_IS_RAWIP(connp));
27217 			ASSERT(!IPCL_IS_IPTUN(connp));
27218 
27219 			/* The case of AH and ESP */
27220 			qreply(q, mp);
27221 			CONN_OPER_PENDING_DONE(connp);
27222 			return;
27223 		}
27224 		case T_SVR4_OPTMGMT_REQ:
27225 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27226 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27227 
27228 			if (connp == NULL) {
27229 				proto_str = "T_SVR4_OPTMGMT_REQ";
27230 				goto protonak;
27231 			}
27232 
27233 			/*
27234 			 * All Solaris components should pass a db_credp
27235 			 * for this TPI message, hence we ASSERT.
27236 			 * But in case there is some other M_PROTO that looks
27237 			 * like a TPI message sent by some other kernel
27238 			 * component, we check and return an error.
27239 			 */
27240 			cr = msg_getcred(mp, NULL);
27241 			ASSERT(cr != NULL);
27242 			if (cr == NULL) {
27243 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27244 				if (mp != NULL)
27245 					qreply(q, mp);
27246 				return;
27247 			}
27248 
27249 			if (!snmpcom_req(q, mp, ip_snmp_set,
27250 			    ip_snmp_get, cr)) {
27251 				/*
27252 				 * Call svr4_optcom_req so that it can
27253 				 * generate the ack. We don't come here
27254 				 * if this operation is being restarted.
27255 				 * ip_restart_optmgmt will drop the conn ref.
27256 				 * In the case of ipsec option after the ipsec
27257 				 * load is complete conn_restart_ipsec_waiter
27258 				 * drops the conn ref.
27259 				 */
27260 				ASSERT(ipsq == NULL);
27261 				CONN_INC_REF(connp);
27262 				if (ip_check_for_ipsec_opt(q, mp))
27263 					return;
27264 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27265 				    B_FALSE);
27266 				if (err != EINPROGRESS) {
27267 					/* Operation is done */
27268 					CONN_OPER_PENDING_DONE(connp);
27269 				}
27270 			}
27271 			return;
27272 		case T_OPTMGMT_REQ:
27273 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27274 			/*
27275 			 * Note: No snmpcom_req support through new
27276 			 * T_OPTMGMT_REQ.
27277 			 * Call tpi_optcom_req so that it can
27278 			 * generate the ack.
27279 			 */
27280 			if (connp == NULL) {
27281 				proto_str = "T_OPTMGMT_REQ";
27282 				goto protonak;
27283 			}
27284 
27285 			/*
27286 			 * All Solaris components should pass a db_credp
27287 			 * for this TPI message, hence we ASSERT.
27288 			 * But in case there is some other M_PROTO that looks
27289 			 * like a TPI message sent by some other kernel
27290 			 * component, we check and return an error.
27291 			 */
27292 			cr = msg_getcred(mp, NULL);
27293 			ASSERT(cr != NULL);
27294 			if (cr == NULL) {
27295 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27296 				if (mp != NULL)
27297 					qreply(q, mp);
27298 				return;
27299 			}
27300 			ASSERT(ipsq == NULL);
27301 			/*
27302 			 * We don't come here for restart. ip_restart_optmgmt
27303 			 * will drop the conn ref. In the case of ipsec option
27304 			 * after the ipsec load is complete
27305 			 * conn_restart_ipsec_waiter drops the conn ref.
27306 			 */
27307 			CONN_INC_REF(connp);
27308 			if (ip_check_for_ipsec_opt(q, mp))
27309 				return;
27310 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27311 			if (err != EINPROGRESS) {
27312 				/* Operation is done */
27313 				CONN_OPER_PENDING_DONE(connp);
27314 			}
27315 			return;
27316 		case T_UNBIND_REQ:
27317 			if (connp == NULL) {
27318 				proto_str = "T_UNBIND_REQ";
27319 				goto protonak;
27320 			}
27321 			ip_unbind(Q_TO_CONN(q));
27322 			mp = mi_tpi_ok_ack_alloc(mp);
27323 			qreply(q, mp);
27324 			return;
27325 		default:
27326 			/*
27327 			 * Have to drop any DLPI messages coming down from
27328 			 * arp (such as an info_req which would cause ip
27329 			 * to receive an extra info_ack if it was passed
27330 			 * through.
27331 			 */
27332 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27333 			    (int)*(uint_t *)mp->b_rptr));
27334 			freemsg(mp);
27335 			return;
27336 		}
27337 		/* NOTREACHED */
27338 	case IRE_DB_TYPE: {
27339 		nce_t		*nce;
27340 		ill_t		*ill;
27341 		in6_addr_t	gw_addr_v6;
27342 
27343 		/*
27344 		 * This is a response back from a resolver.  It
27345 		 * consists of a message chain containing:
27346 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27347 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27348 		 * The LL_HDR_MBLK is the DLPI header to use to get
27349 		 * the attached packet, and subsequent ones for the
27350 		 * same destination, transmitted.
27351 		 */
27352 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27353 			break;
27354 		/*
27355 		 * First, check to make sure the resolution succeeded.
27356 		 * If it failed, the second mblk will be empty.
27357 		 * If it is, free the chain, dropping the packet.
27358 		 * (We must ire_delete the ire; that frees the ire mblk)
27359 		 * We're doing this now to support PVCs for ATM; it's
27360 		 * a partial xresolv implementation. When we fully implement
27361 		 * xresolv interfaces, instead of freeing everything here
27362 		 * we'll initiate neighbor discovery.
27363 		 *
27364 		 * For v4 (ARP and other external resolvers) the resolver
27365 		 * frees the message, so no check is needed. This check
27366 		 * is required, though, for a full xresolve implementation.
27367 		 * Including this code here now both shows how external
27368 		 * resolvers can NACK a resolution request using an
27369 		 * existing design that has no specific provisions for NACKs,
27370 		 * and also takes into account that the current non-ARP
27371 		 * external resolver has been coded to use this method of
27372 		 * NACKing for all IPv6 (xresolv) cases,
27373 		 * whether our xresolv implementation is complete or not.
27374 		 *
27375 		 */
27376 		ire = (ire_t *)mp->b_rptr;
27377 		ill = ire_to_ill(ire);
27378 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27379 		if (mp1->b_rptr == mp1->b_wptr) {
27380 			if (ire->ire_ipversion == IPV6_VERSION) {
27381 				/*
27382 				 * XRESOLV interface.
27383 				 */
27384 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27385 				mutex_enter(&ire->ire_lock);
27386 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27387 				mutex_exit(&ire->ire_lock);
27388 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27389 					nce = ndp_lookup_v6(ill, B_FALSE,
27390 					    &ire->ire_addr_v6, B_FALSE);
27391 				} else {
27392 					nce = ndp_lookup_v6(ill, B_FALSE,
27393 					    &gw_addr_v6, B_FALSE);
27394 				}
27395 				if (nce != NULL) {
27396 					nce_resolv_failed(nce);
27397 					ndp_delete(nce);
27398 					NCE_REFRELE(nce);
27399 				}
27400 			}
27401 			mp->b_cont = NULL;
27402 			freemsg(mp1);		/* frees the pkt as well */
27403 			ASSERT(ire->ire_nce == NULL);
27404 			ire_delete((ire_t *)mp->b_rptr);
27405 			return;
27406 		}
27407 
27408 		/*
27409 		 * Split them into IRE_MBLK and pkt and feed it into
27410 		 * ire_add_then_send. Then in ire_add_then_send
27411 		 * the IRE will be added, and then the packet will be
27412 		 * run back through ip_wput. This time it will make
27413 		 * it to the wire.
27414 		 */
27415 		mp->b_cont = NULL;
27416 		mp = mp1->b_cont;		/* now, mp points to pkt */
27417 		mp1->b_cont = NULL;
27418 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27419 		if (ire->ire_ipversion == IPV6_VERSION) {
27420 			/*
27421 			 * XRESOLV interface. Find the nce and put a copy
27422 			 * of the dl_unitdata_req in nce_res_mp
27423 			 */
27424 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27425 			mutex_enter(&ire->ire_lock);
27426 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27427 			mutex_exit(&ire->ire_lock);
27428 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27429 				nce = ndp_lookup_v6(ill, B_FALSE,
27430 				    &ire->ire_addr_v6, B_FALSE);
27431 			} else {
27432 				nce = ndp_lookup_v6(ill, B_FALSE,
27433 				    &gw_addr_v6, B_FALSE);
27434 			}
27435 			if (nce != NULL) {
27436 				/*
27437 				 * We have to protect nce_res_mp here
27438 				 * from being accessed by other threads
27439 				 * while we change the mblk pointer.
27440 				 * Other functions will also lock the nce when
27441 				 * accessing nce_res_mp.
27442 				 *
27443 				 * The reason we change the mblk pointer
27444 				 * here rather than copying the resolved address
27445 				 * into the template is that, unlike with
27446 				 * ethernet, we have no guarantee that the
27447 				 * resolved address length will be
27448 				 * smaller than or equal to the lla length
27449 				 * with which the template was allocated,
27450 				 * (for ethernet, they're equal)
27451 				 * so we have to use the actual resolved
27452 				 * address mblk - which holds the real
27453 				 * dl_unitdata_req with the resolved address.
27454 				 *
27455 				 * Doing this is the same behavior as was
27456 				 * previously used in the v4 ARP case.
27457 				 */
27458 				mutex_enter(&nce->nce_lock);
27459 				if (nce->nce_res_mp != NULL)
27460 					freemsg(nce->nce_res_mp);
27461 				nce->nce_res_mp = mp1;
27462 				mutex_exit(&nce->nce_lock);
27463 				/*
27464 				 * We do a fastpath probe here because
27465 				 * we have resolved the address without
27466 				 * using Neighbor Discovery.
27467 				 * In the non-XRESOLV v6 case, the fastpath
27468 				 * probe is done right after neighbor
27469 				 * discovery completes.
27470 				 */
27471 				if (nce->nce_res_mp != NULL) {
27472 					int res;
27473 					nce_fastpath_list_add(nce);
27474 					res = ill_fastpath_probe(ill,
27475 					    nce->nce_res_mp);
27476 					if (res != 0 && res != EAGAIN)
27477 						nce_fastpath_list_delete(nce);
27478 				}
27479 
27480 				ire_add_then_send(q, ire, mp);
27481 				/*
27482 				 * Now we have to clean out any packets
27483 				 * that may have been queued on the nce
27484 				 * while it was waiting for address resolution
27485 				 * to complete.
27486 				 */
27487 				mutex_enter(&nce->nce_lock);
27488 				mp1 = nce->nce_qd_mp;
27489 				nce->nce_qd_mp = NULL;
27490 				mutex_exit(&nce->nce_lock);
27491 				while (mp1 != NULL) {
27492 					mblk_t *nxt_mp;
27493 					queue_t *fwdq = NULL;
27494 					ill_t   *inbound_ill;
27495 					uint_t ifindex;
27496 
27497 					nxt_mp = mp1->b_next;
27498 					mp1->b_next = NULL;
27499 					/*
27500 					 * Retrieve ifindex stored in
27501 					 * ip_rput_data_v6()
27502 					 */
27503 					ifindex =
27504 					    (uint_t)(uintptr_t)mp1->b_prev;
27505 					inbound_ill =
27506 					    ill_lookup_on_ifindex(ifindex,
27507 					    B_TRUE, NULL, NULL, NULL,
27508 					    NULL, ipst);
27509 					mp1->b_prev = NULL;
27510 					if (inbound_ill != NULL)
27511 						fwdq = inbound_ill->ill_rq;
27512 
27513 					if (fwdq != NULL) {
27514 						put(fwdq, mp1);
27515 						ill_refrele(inbound_ill);
27516 					} else
27517 						put(WR(ill->ill_rq), mp1);
27518 					mp1 = nxt_mp;
27519 				}
27520 				NCE_REFRELE(nce);
27521 			} else {	/* nce is NULL; clean up */
27522 				ire_delete(ire);
27523 				freemsg(mp);
27524 				freemsg(mp1);
27525 				return;
27526 			}
27527 		} else {
27528 			nce_t *arpce;
27529 			/*
27530 			 * Link layer resolution succeeded. Recompute the
27531 			 * ire_nce.
27532 			 */
27533 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27534 			if ((arpce = ndp_lookup_v4(ill,
27535 			    (ire->ire_gateway_addr != INADDR_ANY ?
27536 			    &ire->ire_gateway_addr : &ire->ire_addr),
27537 			    B_FALSE)) == NULL) {
27538 				freeb(ire->ire_mp);
27539 				freeb(mp1);
27540 				freemsg(mp);
27541 				return;
27542 			}
27543 			mutex_enter(&arpce->nce_lock);
27544 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27545 			if (arpce->nce_state == ND_REACHABLE) {
27546 				/*
27547 				 * Someone resolved this before us;
27548 				 * cleanup the res_mp. Since ire has
27549 				 * not been added yet, the call to ire_add_v4
27550 				 * from ire_add_then_send (when a dup is
27551 				 * detected) will clean up the ire.
27552 				 */
27553 				freeb(mp1);
27554 			} else {
27555 				ASSERT(arpce->nce_res_mp == NULL);
27556 				arpce->nce_res_mp = mp1;
27557 				arpce->nce_state = ND_REACHABLE;
27558 			}
27559 			mutex_exit(&arpce->nce_lock);
27560 			if (ire->ire_marks & IRE_MARK_NOADD) {
27561 				/*
27562 				 * this ire will not be added to the ire
27563 				 * cache table, so we can set the ire_nce
27564 				 * here, as there are no atomicity constraints.
27565 				 */
27566 				ire->ire_nce = arpce;
27567 				/*
27568 				 * We are associating this nce with the ire
27569 				 * so change the nce ref taken in
27570 				 * ndp_lookup_v4() from
27571 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27572 				 */
27573 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27574 			} else {
27575 				NCE_REFRELE(arpce);
27576 			}
27577 			ire_add_then_send(q, ire, mp);
27578 		}
27579 		return;	/* All is well, the packet has been sent. */
27580 	}
27581 	case IRE_ARPRESOLVE_TYPE: {
27582 
27583 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27584 			break;
27585 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27586 		mp->b_cont = NULL;
27587 		/*
27588 		 * First, check to make sure the resolution succeeded.
27589 		 * If it failed, the second mblk will be empty.
27590 		 */
27591 		if (mp1->b_rptr == mp1->b_wptr) {
27592 			/* cleanup  the incomplete ire, free queued packets */
27593 			freemsg(mp); /* fake ire */
27594 			freeb(mp1);  /* dl_unitdata response */
27595 			return;
27596 		}
27597 
27598 		/*
27599 		 * Update any incomplete nce_t found. We search the ctable
27600 		 * and find the nce from the ire->ire_nce because we need
27601 		 * to pass the ire to ip_xmit_v4 later, and can find both
27602 		 * ire and nce in one lookup.
27603 		 */
27604 		fake_ire = (ire_t *)mp->b_rptr;
27605 
27606 		/*
27607 		 * By the time we come back here from ARP the logical outgoing
27608 		 * interface of the incomplete ire we added in ire_forward()
27609 		 * could have disappeared, causing the incomplete ire to also
27610 		 * disappear.  So we need to retreive the proper ipif for the
27611 		 * ire before looking in ctable.  In the case of IPMP, the
27612 		 * ipif may be on the IPMP ill, so look it up based on the
27613 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27614 		 * Then, we can verify that ire_ipif_seqid still exists.
27615 		 */
27616 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27617 		    NULL, NULL, NULL, NULL, ipst);
27618 		if (ill == NULL) {
27619 			ip1dbg(("ill for incomplete ire vanished\n"));
27620 			freemsg(mp); /* fake ire */
27621 			freeb(mp1);  /* dl_unitdata response */
27622 			return;
27623 		}
27624 
27625 		/* Get the outgoing ipif */
27626 		mutex_enter(&ill->ill_lock);
27627 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27628 		if (ipif == NULL) {
27629 			mutex_exit(&ill->ill_lock);
27630 			ill_refrele(ill);
27631 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27632 			freemsg(mp); /* fake_ire */
27633 			freeb(mp1);  /* dl_unitdata response */
27634 			return;
27635 		}
27636 
27637 		ipif_refhold_locked(ipif);
27638 		mutex_exit(&ill->ill_lock);
27639 		ill_refrele(ill);
27640 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27641 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27642 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27643 		ipif_refrele(ipif);
27644 		if (ire == NULL) {
27645 			/*
27646 			 * no ire was found; check if there is an nce
27647 			 * for this lookup; if it has no ire's pointing at it
27648 			 * cleanup.
27649 			 */
27650 			if ((nce = ndp_lookup_v4(q->q_ptr,
27651 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27652 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27653 			    B_FALSE)) != NULL) {
27654 				/*
27655 				 * cleanup:
27656 				 * We check for refcnt 2 (one for the nce
27657 				 * hash list + 1 for the ref taken by
27658 				 * ndp_lookup_v4) to check that there are
27659 				 * no ire's pointing at the nce.
27660 				 */
27661 				if (nce->nce_refcnt == 2)
27662 					ndp_delete(nce);
27663 				NCE_REFRELE(nce);
27664 			}
27665 			freeb(mp1);  /* dl_unitdata response */
27666 			freemsg(mp); /* fake ire */
27667 			return;
27668 		}
27669 
27670 		nce = ire->ire_nce;
27671 		DTRACE_PROBE2(ire__arpresolve__type,
27672 		    ire_t *, ire, nce_t *, nce);
27673 		mutex_enter(&nce->nce_lock);
27674 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27675 		if (nce->nce_state == ND_REACHABLE) {
27676 			/*
27677 			 * Someone resolved this before us;
27678 			 * our response is not needed any more.
27679 			 */
27680 			mutex_exit(&nce->nce_lock);
27681 			freeb(mp1);  /* dl_unitdata response */
27682 		} else {
27683 			ASSERT(nce->nce_res_mp == NULL);
27684 			nce->nce_res_mp = mp1;
27685 			nce->nce_state = ND_REACHABLE;
27686 			mutex_exit(&nce->nce_lock);
27687 			nce_fastpath(nce);
27688 		}
27689 		/*
27690 		 * The cached nce_t has been updated to be reachable;
27691 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27692 		 */
27693 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27694 		freemsg(mp);
27695 		/*
27696 		 * send out queued packets.
27697 		 */
27698 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27699 
27700 		IRE_REFRELE(ire);
27701 		return;
27702 	}
27703 	default:
27704 		break;
27705 	}
27706 	if (q->q_next) {
27707 		putnext(q, mp);
27708 	} else
27709 		freemsg(mp);
27710 	return;
27711 
27712 protonak:
27713 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27714 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27715 		qreply(q, mp);
27716 }
27717 
27718 /*
27719  * Process IP options in an outbound packet.  Modify the destination if there
27720  * is a source route option.
27721  * Returns non-zero if something fails in which case an ICMP error has been
27722  * sent and mp freed.
27723  */
27724 static int
27725 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27726     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27727 {
27728 	ipoptp_t	opts;
27729 	uchar_t		*opt;
27730 	uint8_t		optval;
27731 	uint8_t		optlen;
27732 	ipaddr_t	dst;
27733 	intptr_t	code = 0;
27734 	mblk_t		*mp;
27735 	ire_t		*ire = NULL;
27736 
27737 	ip2dbg(("ip_wput_options\n"));
27738 	mp = ipsec_mp;
27739 	if (mctl_present) {
27740 		mp = ipsec_mp->b_cont;
27741 	}
27742 
27743 	dst = ipha->ipha_dst;
27744 	for (optval = ipoptp_first(&opts, ipha);
27745 	    optval != IPOPT_EOL;
27746 	    optval = ipoptp_next(&opts)) {
27747 		opt = opts.ipoptp_cur;
27748 		optlen = opts.ipoptp_len;
27749 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27750 		    optval, optlen));
27751 		switch (optval) {
27752 			uint32_t off;
27753 		case IPOPT_SSRR:
27754 		case IPOPT_LSRR:
27755 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27756 				ip1dbg((
27757 				    "ip_wput_options: bad option offset\n"));
27758 				code = (char *)&opt[IPOPT_OLEN] -
27759 				    (char *)ipha;
27760 				goto param_prob;
27761 			}
27762 			off = opt[IPOPT_OFFSET];
27763 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27764 			    ntohl(dst)));
27765 			/*
27766 			 * For strict: verify that dst is directly
27767 			 * reachable.
27768 			 */
27769 			if (optval == IPOPT_SSRR) {
27770 				ire = ire_ftable_lookup(dst, 0, 0,
27771 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27772 				    msg_getlabel(mp),
27773 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27774 				if (ire == NULL) {
27775 					ip1dbg(("ip_wput_options: SSRR not"
27776 					    " directly reachable: 0x%x\n",
27777 					    ntohl(dst)));
27778 					goto bad_src_route;
27779 				}
27780 				ire_refrele(ire);
27781 			}
27782 			break;
27783 		case IPOPT_RR:
27784 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27785 				ip1dbg((
27786 				    "ip_wput_options: bad option offset\n"));
27787 				code = (char *)&opt[IPOPT_OLEN] -
27788 				    (char *)ipha;
27789 				goto param_prob;
27790 			}
27791 			break;
27792 		case IPOPT_TS:
27793 			/*
27794 			 * Verify that length >=5 and that there is either
27795 			 * room for another timestamp or that the overflow
27796 			 * counter is not maxed out.
27797 			 */
27798 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27799 			if (optlen < IPOPT_MINLEN_IT) {
27800 				goto param_prob;
27801 			}
27802 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27803 				ip1dbg((
27804 				    "ip_wput_options: bad option offset\n"));
27805 				code = (char *)&opt[IPOPT_OFFSET] -
27806 				    (char *)ipha;
27807 				goto param_prob;
27808 			}
27809 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27810 			case IPOPT_TS_TSONLY:
27811 				off = IPOPT_TS_TIMELEN;
27812 				break;
27813 			case IPOPT_TS_TSANDADDR:
27814 			case IPOPT_TS_PRESPEC:
27815 			case IPOPT_TS_PRESPEC_RFC791:
27816 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27817 				break;
27818 			default:
27819 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27820 				    (char *)ipha;
27821 				goto param_prob;
27822 			}
27823 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27824 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27825 				/*
27826 				 * No room and the overflow counter is 15
27827 				 * already.
27828 				 */
27829 				goto param_prob;
27830 			}
27831 			break;
27832 		}
27833 	}
27834 
27835 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27836 		return (0);
27837 
27838 	ip1dbg(("ip_wput_options: error processing IP options."));
27839 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27840 
27841 param_prob:
27842 	/*
27843 	 * Since ip_wput() isn't close to finished, we fill
27844 	 * in enough of the header for credible error reporting.
27845 	 */
27846 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27847 		/* Failed */
27848 		freemsg(ipsec_mp);
27849 		return (-1);
27850 	}
27851 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27852 	return (-1);
27853 
27854 bad_src_route:
27855 	/*
27856 	 * Since ip_wput() isn't close to finished, we fill
27857 	 * in enough of the header for credible error reporting.
27858 	 */
27859 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27860 		/* Failed */
27861 		freemsg(ipsec_mp);
27862 		return (-1);
27863 	}
27864 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27865 	return (-1);
27866 }
27867 
27868 /*
27869  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27870  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27871  * thru /etc/system.
27872  */
27873 #define	CONN_MAXDRAINCNT	64
27874 
27875 static void
27876 conn_drain_init(ip_stack_t *ipst)
27877 {
27878 	int i, j;
27879 	idl_tx_list_t *itl_tx;
27880 
27881 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27882 
27883 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27884 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27885 		/*
27886 		 * Default value of the number of drainers is the
27887 		 * number of cpus, subject to maximum of 8 drainers.
27888 		 */
27889 		if (boot_max_ncpus != -1)
27890 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27891 		else
27892 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27893 	}
27894 
27895 	ipst->ips_idl_tx_list =
27896 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
27897 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27898 		itl_tx =  &ipst->ips_idl_tx_list[i];
27899 		itl_tx->txl_drain_list =
27900 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27901 		    sizeof (idl_t), KM_SLEEP);
27902 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
27903 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
27904 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
27905 			    MUTEX_DEFAULT, NULL);
27906 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
27907 		}
27908 	}
27909 }
27910 
27911 static void
27912 conn_drain_fini(ip_stack_t *ipst)
27913 {
27914 	int i;
27915 	idl_tx_list_t *itl_tx;
27916 
27917 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27918 		itl_tx =  &ipst->ips_idl_tx_list[i];
27919 		kmem_free(itl_tx->txl_drain_list,
27920 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27921 	}
27922 	kmem_free(ipst->ips_idl_tx_list,
27923 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
27924 	ipst->ips_idl_tx_list = NULL;
27925 }
27926 
27927 /*
27928  * Note: For an overview of how flowcontrol is handled in IP please see the
27929  * IP Flowcontrol notes at the top of this file.
27930  *
27931  * Flow control has blocked us from proceeding. Insert the given conn in one
27932  * of the conn drain lists. These conn wq's will be qenabled later on when
27933  * STREAMS flow control does a backenable. conn_walk_drain will enable
27934  * the first conn in each of these drain lists. Each of these qenabled conns
27935  * in turn enables the next in the list, after it runs, or when it closes,
27936  * thus sustaining the drain process.
27937  */
27938 void
27939 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
27940 {
27941 	idl_t	*idl = tx_list->txl_drain_list;
27942 	uint_t	index;
27943 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27944 
27945 	mutex_enter(&connp->conn_lock);
27946 	if (connp->conn_state_flags & CONN_CLOSING) {
27947 		/*
27948 		 * The conn is closing as a result of which CONN_CLOSING
27949 		 * is set. Return.
27950 		 */
27951 		mutex_exit(&connp->conn_lock);
27952 		return;
27953 	} else if (connp->conn_idl == NULL) {
27954 		/*
27955 		 * Assign the next drain list round robin. We dont' use
27956 		 * a lock, and thus it may not be strictly round robin.
27957 		 * Atomicity of load/stores is enough to make sure that
27958 		 * conn_drain_list_index is always within bounds.
27959 		 */
27960 		index = tx_list->txl_drain_index;
27961 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27962 		connp->conn_idl = &tx_list->txl_drain_list[index];
27963 		index++;
27964 		if (index == ipst->ips_conn_drain_list_cnt)
27965 			index = 0;
27966 		tx_list->txl_drain_index = index;
27967 	}
27968 	mutex_exit(&connp->conn_lock);
27969 
27970 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27971 	if ((connp->conn_drain_prev != NULL) ||
27972 	    (connp->conn_state_flags & CONN_CLOSING)) {
27973 		/*
27974 		 * The conn is already in the drain list, OR
27975 		 * the conn is closing. We need to check again for
27976 		 * the closing case again since close can happen
27977 		 * after we drop the conn_lock, and before we
27978 		 * acquire the CONN_DRAIN_LIST_LOCK.
27979 		 */
27980 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27981 		return;
27982 	} else {
27983 		idl = connp->conn_idl;
27984 	}
27985 
27986 	/*
27987 	 * The conn is not in the drain list. Insert it at the
27988 	 * tail of the drain list. The drain list is circular
27989 	 * and doubly linked. idl_conn points to the 1st element
27990 	 * in the list.
27991 	 */
27992 	if (idl->idl_conn == NULL) {
27993 		idl->idl_conn = connp;
27994 		connp->conn_drain_next = connp;
27995 		connp->conn_drain_prev = connp;
27996 	} else {
27997 		conn_t *head = idl->idl_conn;
27998 
27999 		connp->conn_drain_next = head;
28000 		connp->conn_drain_prev = head->conn_drain_prev;
28001 		head->conn_drain_prev->conn_drain_next = connp;
28002 		head->conn_drain_prev = connp;
28003 	}
28004 	/*
28005 	 * For non streams based sockets assert flow control.
28006 	 */
28007 	if (IPCL_IS_NONSTR(connp)) {
28008 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28009 		(*connp->conn_upcalls->su_txq_full)
28010 		    (connp->conn_upper_handle, B_TRUE);
28011 	} else {
28012 		conn_setqfull(connp);
28013 		noenable(connp->conn_wq);
28014 	}
28015 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28016 }
28017 
28018 /*
28019  * This conn is closing, and we are called from ip_close. OR
28020  * This conn has been serviced by ip_wsrv, and we need to do the tail
28021  * processing.
28022  * If this conn is part of the drain list, we may need to sustain the drain
28023  * process by qenabling the next conn in the drain list. We may also need to
28024  * remove this conn from the list, if it is done.
28025  */
28026 static void
28027 conn_drain_tail(conn_t *connp, boolean_t closing)
28028 {
28029 	idl_t *idl;
28030 
28031 	/*
28032 	 * connp->conn_idl is stable at this point, and no lock is needed
28033 	 * to check it. If we are called from ip_close, close has already
28034 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28035 	 * called us only because conn_idl is non-null. If we are called thru
28036 	 * service, conn_idl could be null, but it cannot change because
28037 	 * service is single-threaded per queue, and there cannot be another
28038 	 * instance of service trying to call conn_drain_insert on this conn
28039 	 * now.
28040 	 */
28041 	ASSERT(!closing || (connp->conn_idl != NULL));
28042 
28043 	/*
28044 	 * If connp->conn_idl is null, the conn has not been inserted into any
28045 	 * drain list even once since creation of the conn. Just return.
28046 	 */
28047 	if (connp->conn_idl == NULL)
28048 		return;
28049 
28050 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28051 
28052 	if (connp->conn_drain_prev == NULL) {
28053 		/* This conn is currently not in the drain list.  */
28054 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28055 		return;
28056 	}
28057 	idl = connp->conn_idl;
28058 	if (idl->idl_conn_draining == connp) {
28059 		/*
28060 		 * This conn is the current drainer. If this is the last conn
28061 		 * in the drain list, we need to do more checks, in the 'if'
28062 		 * below. Otherwwise we need to just qenable the next conn,
28063 		 * to sustain the draining, and is handled in the 'else'
28064 		 * below.
28065 		 */
28066 		if (connp->conn_drain_next == idl->idl_conn) {
28067 			/*
28068 			 * This conn is the last in this list. This round
28069 			 * of draining is complete. If idl_repeat is set,
28070 			 * it means another flow enabling has happened from
28071 			 * the driver/streams and we need to another round
28072 			 * of draining.
28073 			 * If there are more than 2 conns in the drain list,
28074 			 * do a left rotate by 1, so that all conns except the
28075 			 * conn at the head move towards the head by 1, and the
28076 			 * the conn at the head goes to the tail. This attempts
28077 			 * a more even share for all queues that are being
28078 			 * drained.
28079 			 */
28080 			if ((connp->conn_drain_next != connp) &&
28081 			    (idl->idl_conn->conn_drain_next != connp)) {
28082 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28083 			}
28084 			if (idl->idl_repeat) {
28085 				qenable(idl->idl_conn->conn_wq);
28086 				idl->idl_conn_draining = idl->idl_conn;
28087 				idl->idl_repeat = 0;
28088 			} else {
28089 				idl->idl_conn_draining = NULL;
28090 			}
28091 		} else {
28092 			/*
28093 			 * If the next queue that we are now qenable'ing,
28094 			 * is closing, it will remove itself from this list
28095 			 * and qenable the subsequent queue in ip_close().
28096 			 * Serialization is acheived thru idl_lock.
28097 			 */
28098 			qenable(connp->conn_drain_next->conn_wq);
28099 			idl->idl_conn_draining = connp->conn_drain_next;
28100 		}
28101 	}
28102 	if (!connp->conn_did_putbq || closing) {
28103 		/*
28104 		 * Remove ourself from the drain list, if we did not do
28105 		 * a putbq, or if the conn is closing.
28106 		 * Note: It is possible that q->q_first is non-null. It means
28107 		 * that these messages landed after we did a enableok() in
28108 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28109 		 * service them.
28110 		 */
28111 		if (connp->conn_drain_next == connp) {
28112 			/* Singleton in the list */
28113 			ASSERT(connp->conn_drain_prev == connp);
28114 			idl->idl_conn = NULL;
28115 			idl->idl_conn_draining = NULL;
28116 		} else {
28117 			connp->conn_drain_prev->conn_drain_next =
28118 			    connp->conn_drain_next;
28119 			connp->conn_drain_next->conn_drain_prev =
28120 			    connp->conn_drain_prev;
28121 			if (idl->idl_conn == connp)
28122 				idl->idl_conn = connp->conn_drain_next;
28123 			ASSERT(idl->idl_conn_draining != connp);
28124 
28125 		}
28126 		connp->conn_drain_next = NULL;
28127 		connp->conn_drain_prev = NULL;
28128 
28129 		/*
28130 		 * For non streams based sockets open up flow control.
28131 		 */
28132 		if (IPCL_IS_NONSTR(connp)) {
28133 			(*connp->conn_upcalls->su_txq_full)
28134 			    (connp->conn_upper_handle, B_FALSE);
28135 		} else {
28136 			conn_clrqfull(connp);
28137 			enableok(connp->conn_wq);
28138 		}
28139 	}
28140 
28141 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28142 }
28143 
28144 /*
28145  * Write service routine. Shared perimeter entry point.
28146  * ip_wsrv can be called in any of the following ways.
28147  * 1. The device queue's messages has fallen below the low water mark
28148  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28149  *    the drain lists and backenable the first conn in each list.
28150  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28151  *    qenabled non-tcp upper layers. We start dequeing messages and call
28152  *    ip_wput for each message.
28153  */
28154 
28155 void
28156 ip_wsrv(queue_t *q)
28157 {
28158 	conn_t	*connp;
28159 	ill_t	*ill;
28160 	mblk_t	*mp;
28161 
28162 	if (q->q_next) {
28163 		ill = (ill_t *)q->q_ptr;
28164 		if (ill->ill_state_flags == 0) {
28165 			ip_stack_t *ipst = ill->ill_ipst;
28166 
28167 			/*
28168 			 * The device flow control has opened up.
28169 			 * Walk through conn drain lists and qenable the
28170 			 * first conn in each list. This makes sense only
28171 			 * if the stream is fully plumbed and setup.
28172 			 * Hence the if check above.
28173 			 */
28174 			ip1dbg(("ip_wsrv: walking\n"));
28175 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28176 		}
28177 		return;
28178 	}
28179 
28180 	connp = Q_TO_CONN(q);
28181 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28182 
28183 	/*
28184 	 * 1. Set conn_draining flag to signal that service is active.
28185 	 *
28186 	 * 2. ip_output determines whether it has been called from service,
28187 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28188 	 *    has been called from service.
28189 	 *
28190 	 * 3. Message ordering is preserved by the following logic.
28191 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28192 	 *    the message at the tail, if conn_draining is set (i.e. service
28193 	 *    is running) or if q->q_first is non-null.
28194 	 *
28195 	 *    ii. If ip_output is called from service, and if ip_output cannot
28196 	 *    putnext due to flow control, it does a putbq.
28197 	 *
28198 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28199 	 *    (causing an infinite loop).
28200 	 */
28201 	ASSERT(!connp->conn_did_putbq);
28202 
28203 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28204 		connp->conn_draining = 1;
28205 		noenable(q);
28206 		while ((mp = getq(q)) != NULL) {
28207 			ASSERT(CONN_Q(q));
28208 
28209 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28210 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28211 			if (connp->conn_did_putbq) {
28212 				/* ip_wput did a putbq */
28213 				break;
28214 			}
28215 		}
28216 		/*
28217 		 * At this point, a thread coming down from top, calling
28218 		 * ip_wput, may end up queueing the message. We have not yet
28219 		 * enabled the queue, so ip_wsrv won't be called again.
28220 		 * To avoid this race, check q->q_first again (in the loop)
28221 		 * If the other thread queued the message before we call
28222 		 * enableok(), we will catch it in the q->q_first check.
28223 		 * If the other thread queues the message after we call
28224 		 * enableok(), ip_wsrv will be called again by STREAMS.
28225 		 */
28226 		connp->conn_draining = 0;
28227 		enableok(q);
28228 	}
28229 
28230 	/* Enable the next conn for draining */
28231 	conn_drain_tail(connp, B_FALSE);
28232 
28233 	/*
28234 	 * conn_direct_blocked is used to indicate blocked
28235 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28236 	 * This is the only place where it is set without
28237 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28238 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28239 	 */
28240 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28241 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28242 		connp->conn_direct_blocked = B_FALSE;
28243 	}
28244 
28245 	connp->conn_did_putbq = 0;
28246 }
28247 
28248 /*
28249  * Callback to disable flow control in IP.
28250  *
28251  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28252  * is enabled.
28253  *
28254  * When MAC_TX() is not able to send any more packets, dld sets its queue
28255  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28256  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28257  * function and wakes up corresponding mac worker threads, which in turn
28258  * calls this callback function, and disables flow control.
28259  */
28260 void
28261 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28262 {
28263 	ill_t *ill = (ill_t *)arg;
28264 	ip_stack_t *ipst = ill->ill_ipst;
28265 	idl_tx_list_t *idl_txl;
28266 
28267 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28268 	mutex_enter(&idl_txl->txl_lock);
28269 	/* add code to to set a flag to indicate idl_txl is enabled */
28270 	conn_walk_drain(ipst, idl_txl);
28271 	mutex_exit(&idl_txl->txl_lock);
28272 }
28273 
28274 /*
28275  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28276  * of conns that need to be drained, check if drain is already in progress.
28277  * If so set the idl_repeat bit, indicating that the last conn in the list
28278  * needs to reinitiate the drain once again, for the list. If drain is not
28279  * in progress for the list, initiate the draining, by qenabling the 1st
28280  * conn in the list. The drain is self-sustaining, each qenabled conn will
28281  * in turn qenable the next conn, when it is done/blocked/closing.
28282  */
28283 static void
28284 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28285 {
28286 	int i;
28287 	idl_t *idl;
28288 
28289 	IP_STAT(ipst, ip_conn_walk_drain);
28290 
28291 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28292 		idl = &tx_list->txl_drain_list[i];
28293 		mutex_enter(&idl->idl_lock);
28294 		if (idl->idl_conn == NULL) {
28295 			mutex_exit(&idl->idl_lock);
28296 			continue;
28297 		}
28298 		/*
28299 		 * If this list is not being drained currently by
28300 		 * an ip_wsrv thread, start the process.
28301 		 */
28302 		if (idl->idl_conn_draining == NULL) {
28303 			ASSERT(idl->idl_repeat == 0);
28304 			qenable(idl->idl_conn->conn_wq);
28305 			idl->idl_conn_draining = idl->idl_conn;
28306 		} else {
28307 			idl->idl_repeat = 1;
28308 		}
28309 		mutex_exit(&idl->idl_lock);
28310 	}
28311 }
28312 
28313 /*
28314  * Determine if the ill and multicast aspects of that packets
28315  * "matches" the conn.
28316  */
28317 boolean_t
28318 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28319     zoneid_t zoneid)
28320 {
28321 	ill_t *bound_ill;
28322 	boolean_t found;
28323 	ipif_t *ipif;
28324 	ire_t *ire;
28325 	ipaddr_t dst, src;
28326 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28327 
28328 	dst = ipha->ipha_dst;
28329 	src = ipha->ipha_src;
28330 
28331 	/*
28332 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28333 	 * unicast, broadcast and multicast reception to
28334 	 * conn_incoming_ill. conn_wantpacket itself is called
28335 	 * only for BROADCAST and multicast.
28336 	 */
28337 	bound_ill = connp->conn_incoming_ill;
28338 	if (bound_ill != NULL) {
28339 		if (IS_IPMP(bound_ill)) {
28340 			if (bound_ill->ill_grp != ill->ill_grp)
28341 				return (B_FALSE);
28342 		} else {
28343 			if (bound_ill != ill)
28344 				return (B_FALSE);
28345 		}
28346 	}
28347 
28348 	if (!CLASSD(dst)) {
28349 		if (IPCL_ZONE_MATCH(connp, zoneid))
28350 			return (B_TRUE);
28351 		/*
28352 		 * The conn is in a different zone; we need to check that this
28353 		 * broadcast address is configured in the application's zone.
28354 		 */
28355 		ipif = ipif_get_next_ipif(NULL, ill);
28356 		if (ipif == NULL)
28357 			return (B_FALSE);
28358 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28359 		    connp->conn_zoneid, NULL,
28360 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28361 		ipif_refrele(ipif);
28362 		if (ire != NULL) {
28363 			ire_refrele(ire);
28364 			return (B_TRUE);
28365 		} else {
28366 			return (B_FALSE);
28367 		}
28368 	}
28369 
28370 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28371 	    connp->conn_zoneid == zoneid) {
28372 		/*
28373 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28374 		 * disabled, therefore we don't dispatch the multicast packet to
28375 		 * the sending zone.
28376 		 */
28377 		return (B_FALSE);
28378 	}
28379 
28380 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28381 		/*
28382 		 * Multicast packet on the loopback interface: we only match
28383 		 * conns who joined the group in the specified zone.
28384 		 */
28385 		return (B_FALSE);
28386 	}
28387 
28388 	if (connp->conn_multi_router) {
28389 		/* multicast packet and multicast router socket: send up */
28390 		return (B_TRUE);
28391 	}
28392 
28393 	mutex_enter(&connp->conn_lock);
28394 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28395 	mutex_exit(&connp->conn_lock);
28396 	return (found);
28397 }
28398 
28399 static void
28400 conn_setqfull(conn_t *connp)
28401 {
28402 	queue_t *q = connp->conn_wq;
28403 
28404 	if (!(q->q_flag & QFULL)) {
28405 		mutex_enter(QLOCK(q));
28406 		if (!(q->q_flag & QFULL)) {
28407 			/* still need to set QFULL */
28408 			q->q_flag |= QFULL;
28409 			mutex_exit(QLOCK(q));
28410 		} else {
28411 			mutex_exit(QLOCK(q));
28412 		}
28413 	}
28414 }
28415 
28416 static void
28417 conn_clrqfull(conn_t *connp)
28418 {
28419 	queue_t *q = connp->conn_wq;
28420 
28421 	if (q->q_flag & QFULL) {
28422 		mutex_enter(QLOCK(q));
28423 		if (q->q_flag & QFULL) {
28424 			q->q_flag &= ~QFULL;
28425 			mutex_exit(QLOCK(q));
28426 			if (q->q_flag & QWANTW)
28427 				qbackenable(q, 0);
28428 		} else {
28429 			mutex_exit(QLOCK(q));
28430 		}
28431 	}
28432 }
28433 
28434 /*
28435  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28436  */
28437 /* ARGSUSED */
28438 static void
28439 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28440 {
28441 	ill_t *ill = (ill_t *)q->q_ptr;
28442 	mblk_t	*mp1, *mp2;
28443 	ipif_t  *ipif;
28444 	int err = 0;
28445 	conn_t *connp = NULL;
28446 	ipsq_t	*ipsq;
28447 	arc_t	*arc;
28448 
28449 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28450 
28451 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28452 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28453 
28454 	ASSERT(IAM_WRITER_ILL(ill));
28455 	mp2 = mp->b_cont;
28456 	mp->b_cont = NULL;
28457 
28458 	/*
28459 	 * We have now received the arp bringup completion message
28460 	 * from ARP. Mark the arp bringup as done. Also if the arp
28461 	 * stream has already started closing, send up the AR_ARP_CLOSING
28462 	 * ack now since ARP is waiting in close for this ack.
28463 	 */
28464 	mutex_enter(&ill->ill_lock);
28465 	ill->ill_arp_bringup_pending = 0;
28466 	if (ill->ill_arp_closing) {
28467 		mutex_exit(&ill->ill_lock);
28468 		/* Let's reuse the mp for sending the ack */
28469 		arc = (arc_t *)mp->b_rptr;
28470 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28471 		arc->arc_cmd = AR_ARP_CLOSING;
28472 		qreply(q, mp);
28473 	} else {
28474 		mutex_exit(&ill->ill_lock);
28475 		freeb(mp);
28476 	}
28477 
28478 	ipsq = ill->ill_phyint->phyint_ipsq;
28479 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28480 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28481 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28482 	if (mp1 == NULL) {
28483 		/* bringup was aborted by the user */
28484 		freemsg(mp2);
28485 		return;
28486 	}
28487 
28488 	/*
28489 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28490 	 * must have an associated conn_t.  Otherwise, we're bringing this
28491 	 * interface back up as part of handling an asynchronous event (e.g.,
28492 	 * physical address change).
28493 	 */
28494 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28495 		ASSERT(connp != NULL);
28496 		q = CONNP_TO_WQ(connp);
28497 	} else {
28498 		ASSERT(connp == NULL);
28499 		q = ill->ill_rq;
28500 	}
28501 
28502 	/*
28503 	 * If the DL_BIND_REQ fails, it is noted
28504 	 * in arc_name_offset.
28505 	 */
28506 	err = *((int *)mp2->b_rptr);
28507 	if (err == 0) {
28508 		if (ipif->ipif_isv6) {
28509 			if ((err = ipif_up_done_v6(ipif)) != 0)
28510 				ip0dbg(("ip_arp_done: init failed\n"));
28511 		} else {
28512 			if ((err = ipif_up_done(ipif)) != 0)
28513 				ip0dbg(("ip_arp_done: init failed\n"));
28514 		}
28515 	} else {
28516 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28517 	}
28518 
28519 	freemsg(mp2);
28520 
28521 	if ((err == 0) && (ill->ill_up_ipifs)) {
28522 		err = ill_up_ipifs(ill, q, mp1);
28523 		if (err == EINPROGRESS)
28524 			return;
28525 	}
28526 
28527 	/*
28528 	 * If we have a moved ipif to bring up, and everything has succeeded
28529 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28530 	 * down -- the admin can try to bring it up by hand if need be.
28531 	 */
28532 	if (ill->ill_move_ipif != NULL) {
28533 		ipif = ill->ill_move_ipif;
28534 		ill->ill_move_ipif = NULL;
28535 		if (err == 0) {
28536 			err = ipif_up(ipif, q, mp1);
28537 			if (err == EINPROGRESS)
28538 				return;
28539 		}
28540 	}
28541 
28542 	/*
28543 	 * The operation must complete without EINPROGRESS since
28544 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28545 	 * operation will be stuck forever in the ipsq.
28546 	 */
28547 	ASSERT(err != EINPROGRESS);
28548 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28549 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28550 	else
28551 		ipsq_current_finish(ipsq);
28552 }
28553 
28554 /* Allocate the private structure */
28555 static int
28556 ip_priv_alloc(void **bufp)
28557 {
28558 	void	*buf;
28559 
28560 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28561 		return (ENOMEM);
28562 
28563 	*bufp = buf;
28564 	return (0);
28565 }
28566 
28567 /* Function to delete the private structure */
28568 void
28569 ip_priv_free(void *buf)
28570 {
28571 	ASSERT(buf != NULL);
28572 	kmem_free(buf, sizeof (ip_priv_t));
28573 }
28574 
28575 /*
28576  * The entry point for IPPF processing.
28577  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28578  * routine just returns.
28579  *
28580  * When called, ip_process generates an ipp_packet_t structure
28581  * which holds the state information for this packet and invokes the
28582  * the classifier (via ipp_packet_process). The classification, depending on
28583  * configured filters, results in a list of actions for this packet. Invoking
28584  * an action may cause the packet to be dropped, in which case the resulting
28585  * mblk (*mpp) is NULL. proc indicates the callout position for
28586  * this packet and ill_index is the interface this packet on or will leave
28587  * on (inbound and outbound resp.).
28588  */
28589 void
28590 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28591 {
28592 	mblk_t		*mp;
28593 	ip_priv_t	*priv;
28594 	ipp_action_id_t	aid;
28595 	int		rc = 0;
28596 	ipp_packet_t	*pp;
28597 #define	IP_CLASS	"ip"
28598 
28599 	/* If the classifier is not loaded, return  */
28600 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28601 		return;
28602 	}
28603 
28604 	mp = *mpp;
28605 	ASSERT(mp != NULL);
28606 
28607 	/* Allocate the packet structure */
28608 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28609 	if (rc != 0) {
28610 		*mpp = NULL;
28611 		freemsg(mp);
28612 		return;
28613 	}
28614 
28615 	/* Allocate the private structure */
28616 	rc = ip_priv_alloc((void **)&priv);
28617 	if (rc != 0) {
28618 		*mpp = NULL;
28619 		freemsg(mp);
28620 		ipp_packet_free(pp);
28621 		return;
28622 	}
28623 	priv->proc = proc;
28624 	priv->ill_index = ill_index;
28625 	ipp_packet_set_private(pp, priv, ip_priv_free);
28626 	ipp_packet_set_data(pp, mp);
28627 
28628 	/* Invoke the classifier */
28629 	rc = ipp_packet_process(&pp);
28630 	if (pp != NULL) {
28631 		mp = ipp_packet_get_data(pp);
28632 		ipp_packet_free(pp);
28633 		if (rc != 0) {
28634 			freemsg(mp);
28635 			*mpp = NULL;
28636 		}
28637 	} else {
28638 		*mpp = NULL;
28639 	}
28640 #undef	IP_CLASS
28641 }
28642 
28643 /*
28644  * Propagate a multicast group membership operation (add/drop) on
28645  * all the interfaces crossed by the related multirt routes.
28646  * The call is considered successful if the operation succeeds
28647  * on at least one interface.
28648  */
28649 static int
28650 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28651     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28652     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28653     mblk_t *first_mp)
28654 {
28655 	ire_t		*ire_gw;
28656 	irb_t		*irb;
28657 	int		error = 0;
28658 	opt_restart_t	*or;
28659 	ip_stack_t	*ipst = ire->ire_ipst;
28660 
28661 	irb = ire->ire_bucket;
28662 	ASSERT(irb != NULL);
28663 
28664 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28665 
28666 	or = (opt_restart_t *)first_mp->b_rptr;
28667 	IRB_REFHOLD(irb);
28668 	for (; ire != NULL; ire = ire->ire_next) {
28669 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28670 			continue;
28671 		if (ire->ire_addr != group)
28672 			continue;
28673 
28674 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28675 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28676 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28677 		/* No resolver exists for the gateway; skip this ire. */
28678 		if (ire_gw == NULL)
28679 			continue;
28680 
28681 		/*
28682 		 * This function can return EINPROGRESS. If so the operation
28683 		 * will be restarted from ip_restart_optmgmt which will
28684 		 * call ip_opt_set and option processing will restart for
28685 		 * this option. So we may end up calling 'fn' more than once.
28686 		 * This requires that 'fn' is idempotent except for the
28687 		 * return value. The operation is considered a success if
28688 		 * it succeeds at least once on any one interface.
28689 		 */
28690 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28691 		    NULL, fmode, src, first_mp);
28692 		if (error == 0)
28693 			or->or_private = CGTP_MCAST_SUCCESS;
28694 
28695 		if (ip_debug > 0) {
28696 			ulong_t	off;
28697 			char	*ksym;
28698 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28699 			ip2dbg(("ip_multirt_apply_membership: "
28700 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28701 			    "error %d [success %u]\n",
28702 			    ksym ? ksym : "?",
28703 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28704 			    error, or->or_private));
28705 		}
28706 
28707 		ire_refrele(ire_gw);
28708 		if (error == EINPROGRESS) {
28709 			IRB_REFRELE(irb);
28710 			return (error);
28711 		}
28712 	}
28713 	IRB_REFRELE(irb);
28714 	/*
28715 	 * Consider the call as successful if we succeeded on at least
28716 	 * one interface. Otherwise, return the last encountered error.
28717 	 */
28718 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28719 }
28720 
28721 /*
28722  * Issue a warning regarding a route crossing an interface with an
28723  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28724  * amount of time is logged.
28725  */
28726 static void
28727 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28728 {
28729 	hrtime_t	current = gethrtime();
28730 	char		buf[INET_ADDRSTRLEN];
28731 	ip_stack_t	*ipst = ire->ire_ipst;
28732 
28733 	/* Convert interval in ms to hrtime in ns */
28734 	if (ipst->ips_multirt_bad_mtu_last_time +
28735 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28736 	    current) {
28737 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28738 		    "to %s, incorrect MTU %u (expected %u)\n",
28739 		    ip_dot_addr(ire->ire_addr, buf),
28740 		    ire->ire_max_frag, max_frag);
28741 
28742 		ipst->ips_multirt_bad_mtu_last_time = current;
28743 	}
28744 }
28745 
28746 /*
28747  * Get the CGTP (multirouting) filtering status.
28748  * If 0, the CGTP hooks are transparent.
28749  */
28750 /* ARGSUSED */
28751 static int
28752 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28753 {
28754 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28755 
28756 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28757 	return (0);
28758 }
28759 
28760 /*
28761  * Set the CGTP (multirouting) filtering status.
28762  * If the status is changed from active to transparent
28763  * or from transparent to active, forward the new status
28764  * to the filtering module (if loaded).
28765  */
28766 /* ARGSUSED */
28767 static int
28768 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28769     cred_t *ioc_cr)
28770 {
28771 	long		new_value;
28772 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28773 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28774 
28775 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28776 		return (EPERM);
28777 
28778 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28779 	    new_value < 0 || new_value > 1) {
28780 		return (EINVAL);
28781 	}
28782 
28783 	if ((!*ip_cgtp_filter_value) && new_value) {
28784 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28785 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28786 		    " (module not loaded)" : "");
28787 	}
28788 	if (*ip_cgtp_filter_value && (!new_value)) {
28789 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28790 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28791 		    " (module not loaded)" : "");
28792 	}
28793 
28794 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28795 		int	res;
28796 		netstackid_t stackid;
28797 
28798 		stackid = ipst->ips_netstack->netstack_stackid;
28799 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28800 		    new_value);
28801 		if (res)
28802 			return (res);
28803 	}
28804 
28805 	*ip_cgtp_filter_value = (boolean_t)new_value;
28806 
28807 	return (0);
28808 }
28809 
28810 /*
28811  * Return the expected CGTP hooks version number.
28812  */
28813 int
28814 ip_cgtp_filter_supported(void)
28815 {
28816 	return (ip_cgtp_filter_rev);
28817 }
28818 
28819 /*
28820  * CGTP hooks can be registered by invoking this function.
28821  * Checks that the version number matches.
28822  */
28823 int
28824 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28825 {
28826 	netstack_t *ns;
28827 	ip_stack_t *ipst;
28828 
28829 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28830 		return (ENOTSUP);
28831 
28832 	ns = netstack_find_by_stackid(stackid);
28833 	if (ns == NULL)
28834 		return (EINVAL);
28835 	ipst = ns->netstack_ip;
28836 	ASSERT(ipst != NULL);
28837 
28838 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28839 		netstack_rele(ns);
28840 		return (EALREADY);
28841 	}
28842 
28843 	ipst->ips_ip_cgtp_filter_ops = ops;
28844 	netstack_rele(ns);
28845 	return (0);
28846 }
28847 
28848 /*
28849  * CGTP hooks can be unregistered by invoking this function.
28850  * Returns ENXIO if there was no registration.
28851  * Returns EBUSY if the ndd variable has not been turned off.
28852  */
28853 int
28854 ip_cgtp_filter_unregister(netstackid_t stackid)
28855 {
28856 	netstack_t *ns;
28857 	ip_stack_t *ipst;
28858 
28859 	ns = netstack_find_by_stackid(stackid);
28860 	if (ns == NULL)
28861 		return (EINVAL);
28862 	ipst = ns->netstack_ip;
28863 	ASSERT(ipst != NULL);
28864 
28865 	if (ipst->ips_ip_cgtp_filter) {
28866 		netstack_rele(ns);
28867 		return (EBUSY);
28868 	}
28869 
28870 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28871 		netstack_rele(ns);
28872 		return (ENXIO);
28873 	}
28874 	ipst->ips_ip_cgtp_filter_ops = NULL;
28875 	netstack_rele(ns);
28876 	return (0);
28877 }
28878 
28879 /*
28880  * Check whether there is a CGTP filter registration.
28881  * Returns non-zero if there is a registration, otherwise returns zero.
28882  * Note: returns zero if bad stackid.
28883  */
28884 int
28885 ip_cgtp_filter_is_registered(netstackid_t stackid)
28886 {
28887 	netstack_t *ns;
28888 	ip_stack_t *ipst;
28889 	int ret;
28890 
28891 	ns = netstack_find_by_stackid(stackid);
28892 	if (ns == NULL)
28893 		return (0);
28894 	ipst = ns->netstack_ip;
28895 	ASSERT(ipst != NULL);
28896 
28897 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28898 		ret = 1;
28899 	else
28900 		ret = 0;
28901 
28902 	netstack_rele(ns);
28903 	return (ret);
28904 }
28905 
28906 static int
28907 ip_squeue_switch(int val)
28908 {
28909 	int rval = SQ_FILL;
28910 
28911 	switch (val) {
28912 	case IP_SQUEUE_ENTER_NODRAIN:
28913 		rval = SQ_NODRAIN;
28914 		break;
28915 	case IP_SQUEUE_ENTER:
28916 		rval = SQ_PROCESS;
28917 		break;
28918 	default:
28919 		break;
28920 	}
28921 	return (rval);
28922 }
28923 
28924 /* ARGSUSED */
28925 static int
28926 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28927     caddr_t addr, cred_t *cr)
28928 {
28929 	int *v = (int *)addr;
28930 	long new_value;
28931 
28932 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28933 		return (EPERM);
28934 
28935 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28936 		return (EINVAL);
28937 
28938 	ip_squeue_flag = ip_squeue_switch(new_value);
28939 	*v = new_value;
28940 	return (0);
28941 }
28942 
28943 /*
28944  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
28945  * ip_debug.
28946  */
28947 /* ARGSUSED */
28948 static int
28949 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28950     caddr_t addr, cred_t *cr)
28951 {
28952 	int *v = (int *)addr;
28953 	long new_value;
28954 
28955 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28956 		return (EPERM);
28957 
28958 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28959 		return (EINVAL);
28960 
28961 	*v = new_value;
28962 	return (0);
28963 }
28964 
28965 static void *
28966 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
28967 {
28968 	kstat_t *ksp;
28969 
28970 	ip_stat_t template = {
28971 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
28972 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
28973 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
28974 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
28975 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
28976 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
28977 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
28978 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
28979 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
28980 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
28981 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
28982 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
28983 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
28984 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
28985 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
28986 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
28987 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
28988 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
28989 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
28990 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
28991 		{ "ip_opt",			KSTAT_DATA_UINT64 },
28992 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
28993 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
28994 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
28995 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
28996 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
28997 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
28998 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
28999 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29000 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29001 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29002 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29003 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29004 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29005 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29006 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29007 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29008 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29009 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29010 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29011 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29012 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29013 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29014 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29015 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29016 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29017 	};
29018 
29019 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29020 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29021 	    KSTAT_FLAG_VIRTUAL, stackid);
29022 
29023 	if (ksp == NULL)
29024 		return (NULL);
29025 
29026 	bcopy(&template, ip_statisticsp, sizeof (template));
29027 	ksp->ks_data = (void *)ip_statisticsp;
29028 	ksp->ks_private = (void *)(uintptr_t)stackid;
29029 
29030 	kstat_install(ksp);
29031 	return (ksp);
29032 }
29033 
29034 static void
29035 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29036 {
29037 	if (ksp != NULL) {
29038 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29039 		kstat_delete_netstack(ksp, stackid);
29040 	}
29041 }
29042 
29043 static void *
29044 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29045 {
29046 	kstat_t	*ksp;
29047 
29048 	ip_named_kstat_t template = {
29049 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29050 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29051 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29052 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29053 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29054 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29055 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29056 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29057 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29058 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29059 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29060 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29061 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29062 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29063 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29064 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29065 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29066 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29067 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29068 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29069 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29070 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29071 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29072 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29073 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29074 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29075 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29076 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29077 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29078 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29079 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29080 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29081 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29082 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29083 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29084 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29085 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29086 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29087 	};
29088 
29089 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29090 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29091 	if (ksp == NULL || ksp->ks_data == NULL)
29092 		return (NULL);
29093 
29094 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29095 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29096 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29097 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29098 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29099 
29100 	template.netToMediaEntrySize.value.i32 =
29101 	    sizeof (mib2_ipNetToMediaEntry_t);
29102 
29103 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29104 
29105 	bcopy(&template, ksp->ks_data, sizeof (template));
29106 	ksp->ks_update = ip_kstat_update;
29107 	ksp->ks_private = (void *)(uintptr_t)stackid;
29108 
29109 	kstat_install(ksp);
29110 	return (ksp);
29111 }
29112 
29113 static void
29114 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29115 {
29116 	if (ksp != NULL) {
29117 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29118 		kstat_delete_netstack(ksp, stackid);
29119 	}
29120 }
29121 
29122 static int
29123 ip_kstat_update(kstat_t *kp, int rw)
29124 {
29125 	ip_named_kstat_t *ipkp;
29126 	mib2_ipIfStatsEntry_t ipmib;
29127 	ill_walk_context_t ctx;
29128 	ill_t *ill;
29129 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29130 	netstack_t	*ns;
29131 	ip_stack_t	*ipst;
29132 
29133 	if (kp == NULL || kp->ks_data == NULL)
29134 		return (EIO);
29135 
29136 	if (rw == KSTAT_WRITE)
29137 		return (EACCES);
29138 
29139 	ns = netstack_find_by_stackid(stackid);
29140 	if (ns == NULL)
29141 		return (-1);
29142 	ipst = ns->netstack_ip;
29143 	if (ipst == NULL) {
29144 		netstack_rele(ns);
29145 		return (-1);
29146 	}
29147 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29148 
29149 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29150 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29151 	ill = ILL_START_WALK_V4(&ctx, ipst);
29152 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29153 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29154 	rw_exit(&ipst->ips_ill_g_lock);
29155 
29156 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29157 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29158 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29159 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29160 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29161 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29162 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29163 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29164 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29165 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29166 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29167 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29168 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29169 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29170 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29171 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29172 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29173 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29174 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29175 
29176 	ipkp->routingDiscards.value.ui32 =	0;
29177 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29178 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29179 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29180 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29181 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29182 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29183 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29184 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29185 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29186 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29187 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29188 
29189 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29190 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29191 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29192 
29193 	netstack_rele(ns);
29194 
29195 	return (0);
29196 }
29197 
29198 static void *
29199 icmp_kstat_init(netstackid_t stackid)
29200 {
29201 	kstat_t	*ksp;
29202 
29203 	icmp_named_kstat_t template = {
29204 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29205 		{ "inErrors",		KSTAT_DATA_UINT32 },
29206 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29207 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29208 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29209 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29210 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29211 		{ "inEchos",		KSTAT_DATA_UINT32 },
29212 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29213 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29214 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29215 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29216 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29217 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29218 		{ "outErrors",		KSTAT_DATA_UINT32 },
29219 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29220 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29221 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29222 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29223 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29224 		{ "outEchos",		KSTAT_DATA_UINT32 },
29225 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29226 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29227 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29228 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29229 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29230 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29231 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29232 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29233 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29234 		{ "outDrops",		KSTAT_DATA_UINT32 },
29235 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29236 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29237 	};
29238 
29239 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29240 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29241 	if (ksp == NULL || ksp->ks_data == NULL)
29242 		return (NULL);
29243 
29244 	bcopy(&template, ksp->ks_data, sizeof (template));
29245 
29246 	ksp->ks_update = icmp_kstat_update;
29247 	ksp->ks_private = (void *)(uintptr_t)stackid;
29248 
29249 	kstat_install(ksp);
29250 	return (ksp);
29251 }
29252 
29253 static void
29254 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29255 {
29256 	if (ksp != NULL) {
29257 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29258 		kstat_delete_netstack(ksp, stackid);
29259 	}
29260 }
29261 
29262 static int
29263 icmp_kstat_update(kstat_t *kp, int rw)
29264 {
29265 	icmp_named_kstat_t *icmpkp;
29266 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29267 	netstack_t	*ns;
29268 	ip_stack_t	*ipst;
29269 
29270 	if ((kp == NULL) || (kp->ks_data == NULL))
29271 		return (EIO);
29272 
29273 	if (rw == KSTAT_WRITE)
29274 		return (EACCES);
29275 
29276 	ns = netstack_find_by_stackid(stackid);
29277 	if (ns == NULL)
29278 		return (-1);
29279 	ipst = ns->netstack_ip;
29280 	if (ipst == NULL) {
29281 		netstack_rele(ns);
29282 		return (-1);
29283 	}
29284 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29285 
29286 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29287 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29288 	icmpkp->inDestUnreachs.value.ui32 =
29289 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29290 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29291 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29292 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29293 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29294 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29295 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29296 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29297 	icmpkp->inTimestampReps.value.ui32 =
29298 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29299 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29300 	icmpkp->inAddrMaskReps.value.ui32 =
29301 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29302 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29303 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29304 	icmpkp->outDestUnreachs.value.ui32 =
29305 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29306 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29307 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29308 	icmpkp->outSrcQuenchs.value.ui32 =
29309 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29310 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29311 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29312 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29313 	icmpkp->outTimestamps.value.ui32 =
29314 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29315 	icmpkp->outTimestampReps.value.ui32 =
29316 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29317 	icmpkp->outAddrMasks.value.ui32 =
29318 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29319 	icmpkp->outAddrMaskReps.value.ui32 =
29320 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29321 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29322 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29323 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29324 	icmpkp->outFragNeeded.value.ui32 =
29325 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29326 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29327 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29328 	icmpkp->inBadRedirects.value.ui32 =
29329 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29330 
29331 	netstack_rele(ns);
29332 	return (0);
29333 }
29334 
29335 /*
29336  * This is the fanout function for raw socket opened for SCTP.  Note
29337  * that it is called after SCTP checks that there is no socket which
29338  * wants a packet.  Then before SCTP handles this out of the blue packet,
29339  * this function is called to see if there is any raw socket for SCTP.
29340  * If there is and it is bound to the correct address, the packet will
29341  * be sent to that socket.  Note that only one raw socket can be bound to
29342  * a port.  This is assured in ipcl_sctp_hash_insert();
29343  */
29344 void
29345 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29346     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29347     zoneid_t zoneid)
29348 {
29349 	conn_t		*connp;
29350 	queue_t		*rq;
29351 	mblk_t		*first_mp;
29352 	boolean_t	secure;
29353 	ip6_t		*ip6h;
29354 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29355 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29356 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29357 	boolean_t	sctp_csum_err = B_FALSE;
29358 
29359 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29360 		sctp_csum_err = B_TRUE;
29361 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29362 	}
29363 
29364 	first_mp = mp;
29365 	if (mctl_present) {
29366 		mp = first_mp->b_cont;
29367 		secure = ipsec_in_is_secure(first_mp);
29368 		ASSERT(mp != NULL);
29369 	} else {
29370 		secure = B_FALSE;
29371 	}
29372 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29373 
29374 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29375 	if (connp == NULL) {
29376 		/*
29377 		 * Although raw sctp is not summed, OOB chunks must be.
29378 		 * Drop the packet here if the sctp checksum failed.
29379 		 */
29380 		if (sctp_csum_err) {
29381 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29382 			freemsg(first_mp);
29383 			return;
29384 		}
29385 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29386 		return;
29387 	}
29388 	rq = connp->conn_rq;
29389 	if (!canputnext(rq)) {
29390 		CONN_DEC_REF(connp);
29391 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29392 		freemsg(first_mp);
29393 		return;
29394 	}
29395 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29396 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29397 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29398 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29399 		if (first_mp == NULL) {
29400 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29401 			CONN_DEC_REF(connp);
29402 			return;
29403 		}
29404 	}
29405 	/*
29406 	 * We probably should not send M_CTL message up to
29407 	 * raw socket.
29408 	 */
29409 	if (mctl_present)
29410 		freeb(first_mp);
29411 
29412 	/* Initiate IPPF processing here if needed. */
29413 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29414 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29415 		ip_process(IPP_LOCAL_IN, &mp,
29416 		    recv_ill->ill_phyint->phyint_ifindex);
29417 		if (mp == NULL) {
29418 			CONN_DEC_REF(connp);
29419 			return;
29420 		}
29421 	}
29422 
29423 	if (connp->conn_recvif || connp->conn_recvslla ||
29424 	    ((connp->conn_ip_recvpktinfo ||
29425 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29426 	    (flags & IP_FF_IPINFO))) {
29427 		int in_flags = 0;
29428 
29429 		/*
29430 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29431 		 * IPF_RECVIF.
29432 		 */
29433 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29434 			in_flags = IPF_RECVIF;
29435 		}
29436 		if (connp->conn_recvslla) {
29437 			in_flags |= IPF_RECVSLLA;
29438 		}
29439 		if (isv4) {
29440 			mp = ip_add_info(mp, recv_ill, in_flags,
29441 			    IPCL_ZONEID(connp), ipst);
29442 		} else {
29443 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29444 			if (mp == NULL) {
29445 				BUMP_MIB(recv_ill->ill_ip_mib,
29446 				    ipIfStatsInDiscards);
29447 				CONN_DEC_REF(connp);
29448 				return;
29449 			}
29450 		}
29451 	}
29452 
29453 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29454 	/*
29455 	 * We are sending the IPSEC_IN message also up. Refer
29456 	 * to comments above this function.
29457 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29458 	 */
29459 	(connp->conn_recv)(connp, mp, NULL);
29460 	CONN_DEC_REF(connp);
29461 }
29462 
29463 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29464 {									\
29465 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29466 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29467 }
29468 /*
29469  * This function should be called only if all packet processing
29470  * including fragmentation is complete. Callers of this function
29471  * must set mp->b_prev to one of these values:
29472  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29473  * prior to handing over the mp as first argument to this function.
29474  *
29475  * If the ire passed by caller is incomplete, this function
29476  * queues the packet and if necessary, sends ARP request and bails.
29477  * If the ire passed is fully resolved, we simply prepend
29478  * the link-layer header to the packet, do ipsec hw acceleration
29479  * work if necessary, and send the packet out on the wire.
29480  *
29481  * NOTE: IPsec will only call this function with fully resolved
29482  * ires if hw acceleration is involved.
29483  * TODO list :
29484  * 	a Handle M_MULTIDATA so that
29485  *	  tcp_multisend->tcp_multisend_data can
29486  *	  call ip_xmit_v4 directly
29487  *	b Handle post-ARP work for fragments so that
29488  *	  ip_wput_frag can call this function.
29489  */
29490 ipxmit_state_t
29491 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29492     boolean_t flow_ctl_enabled, conn_t *connp)
29493 {
29494 	nce_t		*arpce;
29495 	ipha_t		*ipha;
29496 	queue_t		*q;
29497 	int		ill_index;
29498 	mblk_t		*nxt_mp, *first_mp;
29499 	boolean_t	xmit_drop = B_FALSE;
29500 	ip_proc_t	proc;
29501 	ill_t		*out_ill;
29502 	int		pkt_len;
29503 
29504 	arpce = ire->ire_nce;
29505 	ASSERT(arpce != NULL);
29506 
29507 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29508 
29509 	mutex_enter(&arpce->nce_lock);
29510 	switch (arpce->nce_state) {
29511 	case ND_REACHABLE:
29512 		/* If there are other queued packets, queue this packet */
29513 		if (arpce->nce_qd_mp != NULL) {
29514 			if (mp != NULL)
29515 				nce_queue_mp_common(arpce, mp, B_FALSE);
29516 			mp = arpce->nce_qd_mp;
29517 		}
29518 		arpce->nce_qd_mp = NULL;
29519 		mutex_exit(&arpce->nce_lock);
29520 
29521 		/*
29522 		 * Flush the queue.  In the common case, where the
29523 		 * ARP is already resolved,  it will go through the
29524 		 * while loop only once.
29525 		 */
29526 		while (mp != NULL) {
29527 
29528 			nxt_mp = mp->b_next;
29529 			mp->b_next = NULL;
29530 			ASSERT(mp->b_datap->db_type != M_CTL);
29531 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29532 			/*
29533 			 * This info is needed for IPQOS to do COS marking
29534 			 * in ip_wput_attach_llhdr->ip_process.
29535 			 */
29536 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29537 			mp->b_prev = NULL;
29538 
29539 			/* set up ill index for outbound qos processing */
29540 			out_ill = ire_to_ill(ire);
29541 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29542 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29543 			    ill_index, &ipha);
29544 			if (first_mp == NULL) {
29545 				xmit_drop = B_TRUE;
29546 				BUMP_MIB(out_ill->ill_ip_mib,
29547 				    ipIfStatsOutDiscards);
29548 				goto next_mp;
29549 			}
29550 
29551 			/* non-ipsec hw accel case */
29552 			if (io == NULL || !io->ipsec_out_accelerated) {
29553 				/* send it */
29554 				q = ire->ire_stq;
29555 				if (proc == IPP_FWD_OUT) {
29556 					UPDATE_IB_PKT_COUNT(ire);
29557 				} else {
29558 					UPDATE_OB_PKT_COUNT(ire);
29559 				}
29560 				ire->ire_last_used_time = lbolt;
29561 
29562 				if (flow_ctl_enabled || canputnext(q)) {
29563 					if (proc == IPP_FWD_OUT) {
29564 
29565 					BUMP_MIB(out_ill->ill_ip_mib,
29566 					    ipIfStatsHCOutForwDatagrams);
29567 
29568 					}
29569 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29570 					    pkt_len);
29571 
29572 					DTRACE_IP7(send, mblk_t *, first_mp,
29573 					    conn_t *, NULL, void_ip_t *, ipha,
29574 					    __dtrace_ipsr_ill_t *, out_ill,
29575 					    ipha_t *, ipha, ip6_t *, NULL, int,
29576 					    0);
29577 
29578 					ILL_SEND_TX(out_ill,
29579 					    ire, connp, first_mp, 0, connp);
29580 				} else {
29581 					BUMP_MIB(out_ill->ill_ip_mib,
29582 					    ipIfStatsOutDiscards);
29583 					xmit_drop = B_TRUE;
29584 					freemsg(first_mp);
29585 				}
29586 			} else {
29587 				/*
29588 				 * Safety Pup says: make sure this
29589 				 *  is going to the right interface!
29590 				 */
29591 				ill_t *ill1 =
29592 				    (ill_t *)ire->ire_stq->q_ptr;
29593 				int ifindex =
29594 				    ill1->ill_phyint->phyint_ifindex;
29595 				if (ifindex !=
29596 				    io->ipsec_out_capab_ill_index) {
29597 					xmit_drop = B_TRUE;
29598 					freemsg(mp);
29599 				} else {
29600 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29601 					    pkt_len);
29602 
29603 					DTRACE_IP7(send, mblk_t *, first_mp,
29604 					    conn_t *, NULL, void_ip_t *, ipha,
29605 					    __dtrace_ipsr_ill_t *, ill1,
29606 					    ipha_t *, ipha, ip6_t *, NULL,
29607 					    int, 0);
29608 
29609 					ipsec_hw_putnext(ire->ire_stq, mp);
29610 				}
29611 			}
29612 next_mp:
29613 			mp = nxt_mp;
29614 		} /* while (mp != NULL) */
29615 		if (xmit_drop)
29616 			return (SEND_FAILED);
29617 		else
29618 			return (SEND_PASSED);
29619 
29620 	case ND_INITIAL:
29621 	case ND_INCOMPLETE:
29622 
29623 		/*
29624 		 * While we do send off packets to dests that
29625 		 * use fully-resolved CGTP routes, we do not
29626 		 * handle unresolved CGTP routes.
29627 		 */
29628 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29629 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29630 
29631 		if (mp != NULL) {
29632 			/* queue the packet */
29633 			nce_queue_mp_common(arpce, mp, B_FALSE);
29634 		}
29635 
29636 		if (arpce->nce_state == ND_INCOMPLETE) {
29637 			mutex_exit(&arpce->nce_lock);
29638 			DTRACE_PROBE3(ip__xmit__incomplete,
29639 			    (ire_t *), ire, (mblk_t *), mp,
29640 			    (ipsec_out_t *), io);
29641 			return (LOOKUP_IN_PROGRESS);
29642 		}
29643 
29644 		arpce->nce_state = ND_INCOMPLETE;
29645 		mutex_exit(&arpce->nce_lock);
29646 
29647 		/*
29648 		 * Note that ire_add() (called from ire_forward())
29649 		 * holds a ref on the ire until ARP is completed.
29650 		 */
29651 		ire_arpresolve(ire);
29652 		return (LOOKUP_IN_PROGRESS);
29653 	default:
29654 		ASSERT(0);
29655 		mutex_exit(&arpce->nce_lock);
29656 		return (LLHDR_RESLV_FAILED);
29657 	}
29658 }
29659 
29660 #undef	UPDATE_IP_MIB_OB_COUNTERS
29661 
29662 /*
29663  * Return B_TRUE if the buffers differ in length or content.
29664  * This is used for comparing extension header buffers.
29665  * Note that an extension header would be declared different
29666  * even if all that changed was the next header value in that header i.e.
29667  * what really changed is the next extension header.
29668  */
29669 boolean_t
29670 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29671     uint_t blen)
29672 {
29673 	if (!b_valid)
29674 		blen = 0;
29675 
29676 	if (alen != blen)
29677 		return (B_TRUE);
29678 	if (alen == 0)
29679 		return (B_FALSE);	/* Both zero length */
29680 	return (bcmp(abuf, bbuf, alen));
29681 }
29682 
29683 /*
29684  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29685  * Return B_FALSE if memory allocation fails - don't change any state!
29686  */
29687 boolean_t
29688 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29689     const void *src, uint_t srclen)
29690 {
29691 	void *dst;
29692 
29693 	if (!src_valid)
29694 		srclen = 0;
29695 
29696 	ASSERT(*dstlenp == 0);
29697 	if (src != NULL && srclen != 0) {
29698 		dst = mi_alloc(srclen, BPRI_MED);
29699 		if (dst == NULL)
29700 			return (B_FALSE);
29701 	} else {
29702 		dst = NULL;
29703 	}
29704 	if (*dstp != NULL)
29705 		mi_free(*dstp);
29706 	*dstp = dst;
29707 	*dstlenp = dst == NULL ? 0 : srclen;
29708 	return (B_TRUE);
29709 }
29710 
29711 /*
29712  * Replace what is in *dst, *dstlen with the source.
29713  * Assumes ip_allocbuf has already been called.
29714  */
29715 void
29716 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29717     const void *src, uint_t srclen)
29718 {
29719 	if (!src_valid)
29720 		srclen = 0;
29721 
29722 	ASSERT(*dstlenp == srclen);
29723 	if (src != NULL && srclen != 0)
29724 		bcopy(src, *dstp, srclen);
29725 }
29726 
29727 /*
29728  * Free the storage pointed to by the members of an ip6_pkt_t.
29729  */
29730 void
29731 ip6_pkt_free(ip6_pkt_t *ipp)
29732 {
29733 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29734 
29735 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29736 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29737 		ipp->ipp_hopopts = NULL;
29738 		ipp->ipp_hopoptslen = 0;
29739 	}
29740 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29741 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29742 		ipp->ipp_rtdstopts = NULL;
29743 		ipp->ipp_rtdstoptslen = 0;
29744 	}
29745 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29746 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29747 		ipp->ipp_dstopts = NULL;
29748 		ipp->ipp_dstoptslen = 0;
29749 	}
29750 	if (ipp->ipp_fields & IPPF_RTHDR) {
29751 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29752 		ipp->ipp_rthdr = NULL;
29753 		ipp->ipp_rthdrlen = 0;
29754 	}
29755 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29756 	    IPPF_RTHDR);
29757 }
29758 
29759 zoneid_t
29760 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29761     zoneid_t lookup_zoneid)
29762 {
29763 	ire_t		*ire;
29764 	int		ire_flags = MATCH_IRE_TYPE;
29765 	zoneid_t	zoneid = ALL_ZONES;
29766 
29767 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29768 		return (ALL_ZONES);
29769 
29770 	if (lookup_zoneid != ALL_ZONES)
29771 		ire_flags |= MATCH_IRE_ZONEONLY;
29772 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29773 	    lookup_zoneid, NULL, ire_flags, ipst);
29774 	if (ire != NULL) {
29775 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29776 		ire_refrele(ire);
29777 	}
29778 	return (zoneid);
29779 }
29780 
29781 zoneid_t
29782 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29783     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29784 {
29785 	ire_t		*ire;
29786 	int		ire_flags = MATCH_IRE_TYPE;
29787 	zoneid_t	zoneid = ALL_ZONES;
29788 	ipif_t		*ipif_arg = NULL;
29789 
29790 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29791 		return (ALL_ZONES);
29792 
29793 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29794 		ire_flags |= MATCH_IRE_ILL;
29795 		ipif_arg = ill->ill_ipif;
29796 	}
29797 	if (lookup_zoneid != ALL_ZONES)
29798 		ire_flags |= MATCH_IRE_ZONEONLY;
29799 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29800 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29801 	if (ire != NULL) {
29802 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29803 		ire_refrele(ire);
29804 	}
29805 	return (zoneid);
29806 }
29807 
29808 /*
29809  * IP obserability hook support functions.
29810  */
29811 static void
29812 ipobs_init(ip_stack_t *ipst)
29813 {
29814 	netid_t id;
29815 
29816 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
29817 
29818 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
29819 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
29820 
29821 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
29822 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
29823 }
29824 
29825 static void
29826 ipobs_fini(ip_stack_t *ipst)
29827 {
29828 
29829 	net_protocol_release(ipst->ips_ip4_observe_pr);
29830 	net_protocol_release(ipst->ips_ip6_observe_pr);
29831 }
29832 
29833 /*
29834  * hook_pkt_observe_t is composed in network byte order so that the
29835  * entire mblk_t chain handed into hook_run can be used as-is.
29836  * The caveat is that use of the fields, such as the zone fields,
29837  * requires conversion into host byte order first.
29838  */
29839 void
29840 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
29841     const ill_t *ill, ip_stack_t *ipst)
29842 {
29843 	hook_pkt_observe_t *hdr;
29844 	uint64_t grifindex;
29845 	mblk_t *imp;
29846 
29847 	imp = allocb(sizeof (*hdr), BPRI_HI);
29848 	if (imp == NULL)
29849 		return;
29850 
29851 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
29852 	/*
29853 	 * b_wptr is set to make the apparent size of the data in the mblk_t
29854 	 * to exclude the pointers at the end of hook_pkt_observer_t.
29855 	 */
29856 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
29857 	imp->b_cont = mp;
29858 
29859 	ASSERT(DB_TYPE(mp) == M_DATA);
29860 
29861 	if (IS_UNDER_IPMP(ill))
29862 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
29863 	else
29864 		grifindex = 0;
29865 
29866 	hdr->hpo_version = 1;
29867 	hdr->hpo_htype = htype;
29868 	hdr->hpo_pktlen = htons((ushort_t)msgdsize(mp));
29869 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
29870 	hdr->hpo_grifindex = htonl(grifindex);
29871 	hdr->hpo_zsrc = htonl(zsrc);
29872 	hdr->hpo_zdst = htonl(zdst);
29873 	hdr->hpo_pkt = imp;
29874 	hdr->hpo_ctx = ipst->ips_netstack;
29875 
29876 	if (ill->ill_isv6) {
29877 		hdr->hpo_family = AF_INET6;
29878 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
29879 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
29880 	} else {
29881 		hdr->hpo_family = AF_INET;
29882 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
29883 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
29884 	}
29885 
29886 	imp->b_cont = NULL;
29887 	freemsg(imp);
29888 }
29889