xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 1dbc1fed8be6e82e676ff3f124628dc470058bfb)
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 	if (!ipsec_in_to_out(first_mp, ipha, NULL, zoneid)) {
2060 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2061 		return;
2062 	}
2063 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2064 	put(WR(q), first_mp);
2065 }
2066 
2067 static ipaddr_t
2068 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2069 {
2070 	conn_t *connp;
2071 	connf_t *connfp;
2072 	ipaddr_t nexthop_addr = INADDR_ANY;
2073 	int hdr_length = IPH_HDR_LENGTH(ipha);
2074 	uint16_t *up;
2075 	uint32_t ports;
2076 	ip_stack_t *ipst = ill->ill_ipst;
2077 
2078 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2079 	switch (ipha->ipha_protocol) {
2080 		case IPPROTO_TCP:
2081 		{
2082 			tcph_t *tcph;
2083 
2084 			/* do a reverse lookup */
2085 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2086 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2087 			    TCPS_LISTEN, ipst);
2088 			break;
2089 		}
2090 		case IPPROTO_UDP:
2091 		{
2092 			uint32_t dstport, srcport;
2093 
2094 			((uint16_t *)&ports)[0] = up[1];
2095 			((uint16_t *)&ports)[1] = up[0];
2096 
2097 			/* Extract ports in net byte order */
2098 			dstport = htons(ntohl(ports) & 0xFFFF);
2099 			srcport = htons(ntohl(ports) >> 16);
2100 
2101 			connfp = &ipst->ips_ipcl_udp_fanout[
2102 			    IPCL_UDP_HASH(dstport, ipst)];
2103 			mutex_enter(&connfp->connf_lock);
2104 			connp = connfp->connf_head;
2105 
2106 			/* do a reverse lookup */
2107 			while ((connp != NULL) &&
2108 			    (!IPCL_UDP_MATCH(connp, dstport,
2109 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2110 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2111 				connp = connp->conn_next;
2112 			}
2113 			if (connp != NULL)
2114 				CONN_INC_REF(connp);
2115 			mutex_exit(&connfp->connf_lock);
2116 			break;
2117 		}
2118 		case IPPROTO_SCTP:
2119 		{
2120 			in6_addr_t map_src, map_dst;
2121 
2122 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2123 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2124 			((uint16_t *)&ports)[0] = up[1];
2125 			((uint16_t *)&ports)[1] = up[0];
2126 
2127 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2128 			    zoneid, ipst->ips_netstack->netstack_sctp);
2129 			if (connp == NULL) {
2130 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2131 				    zoneid, ports, ipha, ipst);
2132 			} else {
2133 				CONN_INC_REF(connp);
2134 				SCTP_REFRELE(CONN2SCTP(connp));
2135 			}
2136 			break;
2137 		}
2138 		default:
2139 		{
2140 			ipha_t ripha;
2141 
2142 			ripha.ipha_src = ipha->ipha_dst;
2143 			ripha.ipha_dst = ipha->ipha_src;
2144 			ripha.ipha_protocol = ipha->ipha_protocol;
2145 
2146 			connfp = &ipst->ips_ipcl_proto_fanout[
2147 			    ipha->ipha_protocol];
2148 			mutex_enter(&connfp->connf_lock);
2149 			connp = connfp->connf_head;
2150 			for (connp = connfp->connf_head; connp != NULL;
2151 			    connp = connp->conn_next) {
2152 				if (IPCL_PROTO_MATCH(connp,
2153 				    ipha->ipha_protocol, &ripha, ill,
2154 				    0, zoneid)) {
2155 					CONN_INC_REF(connp);
2156 					break;
2157 				}
2158 			}
2159 			mutex_exit(&connfp->connf_lock);
2160 		}
2161 	}
2162 	if (connp != NULL) {
2163 		if (connp->conn_nexthop_set)
2164 			nexthop_addr = connp->conn_nexthop_v4;
2165 		CONN_DEC_REF(connp);
2166 	}
2167 	return (nexthop_addr);
2168 }
2169 
2170 /* Table from RFC 1191 */
2171 static int icmp_frag_size_table[] =
2172 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2173 
2174 /*
2175  * Process received ICMP Packet too big.
2176  * After updating any IRE it does the fanout to any matching transport streams.
2177  * Assumes the message has been pulled up till the IP header that caused
2178  * the error.
2179  *
2180  * Returns B_FALSE on failure and B_TRUE on success.
2181  */
2182 static boolean_t
2183 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2184     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2185     ip_stack_t *ipst)
2186 {
2187 	ire_t	*ire, *first_ire;
2188 	int	mtu, orig_mtu;
2189 	int	hdr_length;
2190 	ipaddr_t nexthop_addr;
2191 	boolean_t disable_pmtud;
2192 
2193 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2194 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2195 	ASSERT(ill != NULL);
2196 
2197 	hdr_length = IPH_HDR_LENGTH(ipha);
2198 
2199 	/* Drop if the original packet contained a source route */
2200 	if (ip_source_route_included(ipha)) {
2201 		return (B_FALSE);
2202 	}
2203 	/*
2204 	 * Verify we have at least ICMP_MIN_TP_HDR_LENGTH bytes of transport
2205 	 * header.
2206 	 */
2207 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2208 	    mp->b_wptr) {
2209 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2210 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2211 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2212 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2213 			return (B_FALSE);
2214 		}
2215 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2216 		ipha = (ipha_t *)&icmph[1];
2217 	}
2218 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2219 	if (nexthop_addr != INADDR_ANY) {
2220 		/* nexthop set */
2221 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2222 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2223 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2224 	} else {
2225 		/* nexthop not set */
2226 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2227 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2228 	}
2229 
2230 	if (!first_ire) {
2231 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2232 		    ntohl(ipha->ipha_dst)));
2233 		return (B_FALSE);
2234 	}
2235 
2236 	/* Check for MTU discovery advice as described in RFC 1191 */
2237 	mtu = ntohs(icmph->icmph_du_mtu);
2238 	orig_mtu = mtu;
2239 	disable_pmtud = B_FALSE;
2240 
2241 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2242 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2243 	    ire = ire->ire_next) {
2244 		/*
2245 		 * Look for the connection to which this ICMP message is
2246 		 * directed. If it has the IP_NEXTHOP option set, then the
2247 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2248 		 * option. Else the search is limited to regular IREs.
2249 		 */
2250 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2251 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2252 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2253 		    (nexthop_addr != INADDR_ANY)))
2254 			continue;
2255 
2256 		mutex_enter(&ire->ire_lock);
2257 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2258 			uint32_t length;
2259 			int	i;
2260 
2261 			/*
2262 			 * Use the table from RFC 1191 to figure out
2263 			 * the next "plateau" based on the length in
2264 			 * the original IP packet.
2265 			 */
2266 			length = ntohs(ipha->ipha_length);
2267 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2268 			    uint32_t, length);
2269 			if (ire->ire_max_frag <= length &&
2270 			    ire->ire_max_frag >= length - hdr_length) {
2271 				/*
2272 				 * Handle broken BSD 4.2 systems that
2273 				 * return the wrong iph_length in ICMP
2274 				 * errors.
2275 				 */
2276 				length -= hdr_length;
2277 			}
2278 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2279 				if (length > icmp_frag_size_table[i])
2280 					break;
2281 			}
2282 			if (i == A_CNT(icmp_frag_size_table)) {
2283 				/* Smaller than 68! */
2284 				disable_pmtud = B_TRUE;
2285 				mtu = ipst->ips_ip_pmtu_min;
2286 			} else {
2287 				mtu = icmp_frag_size_table[i];
2288 				if (mtu < ipst->ips_ip_pmtu_min) {
2289 					mtu = ipst->ips_ip_pmtu_min;
2290 					disable_pmtud = B_TRUE;
2291 				}
2292 			}
2293 			/* Fool the ULP into believing our guessed PMTU. */
2294 			icmph->icmph_du_zero = 0;
2295 			icmph->icmph_du_mtu = htons(mtu);
2296 		}
2297 		if (disable_pmtud)
2298 			ire->ire_frag_flag = 0;
2299 		/* Reduce the IRE max frag value as advised. */
2300 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2301 		if (ire->ire_max_frag == mtu) {
2302 			/* Decreased it */
2303 			ire->ire_marks |= IRE_MARK_PMTU;
2304 		}
2305 		mutex_exit(&ire->ire_lock);
2306 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2307 		    ire, int, orig_mtu, int, mtu);
2308 	}
2309 	rw_exit(&first_ire->ire_bucket->irb_lock);
2310 	ire_refrele(first_ire);
2311 	return (B_TRUE);
2312 }
2313 
2314 /*
2315  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2316  * calls this function.
2317  */
2318 static mblk_t *
2319 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2320 {
2321 	ipha_t *ipha;
2322 	icmph_t *icmph;
2323 	ipha_t *in_ipha;
2324 	int length;
2325 
2326 	ASSERT(mp->b_datap->db_type == M_DATA);
2327 
2328 	/*
2329 	 * For Self-encapsulated packets, we added an extra IP header
2330 	 * without the options. Inner IP header is the one from which
2331 	 * the outer IP header was formed. Thus, we need to remove the
2332 	 * outer IP header. To do this, we pullup the whole message
2333 	 * and overlay whatever follows the outer IP header over the
2334 	 * outer IP header.
2335 	 */
2336 
2337 	if (!pullupmsg(mp, -1))
2338 		return (NULL);
2339 
2340 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2341 	ipha = (ipha_t *)&icmph[1];
2342 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2343 
2344 	/*
2345 	 * The length that we want to overlay is following the inner
2346 	 * IP header. Subtracting the IP header + icmp header + outer
2347 	 * IP header's length should give us the length that we want to
2348 	 * overlay.
2349 	 */
2350 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2351 	    hdr_length;
2352 	/*
2353 	 * Overlay whatever follows the inner header over the
2354 	 * outer header.
2355 	 */
2356 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2357 
2358 	/* Set the wptr to account for the outer header */
2359 	mp->b_wptr -= hdr_length;
2360 	return (mp);
2361 }
2362 
2363 /*
2364  * Fanout for ICMP errors containing IP-in-IPv4 packets.  Returns B_TRUE if a
2365  * tunnel consumed the message, and B_FALSE otherwise.
2366  */
2367 static boolean_t
2368 icmp_inbound_iptun_fanout(mblk_t *first_mp, ipha_t *ripha, ill_t *ill,
2369     ip_stack_t *ipst)
2370 {
2371 	conn_t	*connp;
2372 
2373 	if ((connp = ipcl_iptun_classify_v4(&ripha->ipha_src, &ripha->ipha_dst,
2374 	    ipst)) == NULL)
2375 		return (B_FALSE);
2376 
2377 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
2378 	connp->conn_recv(connp, first_mp, NULL);
2379 	CONN_DEC_REF(connp);
2380 	return (B_TRUE);
2381 }
2382 
2383 /*
2384  * Try to pass the ICMP message upstream in case the ULP cares.
2385  *
2386  * If the packet that caused the ICMP error is secure, we send
2387  * it to AH/ESP to make sure that the attached packet has a
2388  * valid association. ipha in the code below points to the
2389  * IP header of the packet that caused the error.
2390  *
2391  * For IPsec cases, we let the next-layer-up (which has access to
2392  * cached policy on the conn_t, or can query the SPD directly)
2393  * subtract out any IPsec overhead if they must.  We therefore make no
2394  * adjustments here for IPsec overhead.
2395  *
2396  * IFN could have been generated locally or by some router.
2397  *
2398  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2399  *	    This happens because IP adjusted its value of MTU on an
2400  *	    earlier IFN message and could not tell the upper layer,
2401  *	    the new adjusted value of MTU e.g. Packet was encrypted
2402  *	    or there was not enough information to fanout to upper
2403  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2404  *	    generates the IFN, where IPsec processing has *not* been
2405  *	    done.
2406  *
2407  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2408  *	    could have generated this. This happens because ire_max_frag
2409  *	    value in IP was set to a new value, while the IPsec processing
2410  *	    was being done and after we made the fragmentation check in
2411  *	    ip_wput_ire. Thus on return from IPsec processing,
2412  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2413  *	    and generates the IFN. As IPsec processing is over, we fanout
2414  *	    to AH/ESP to remove the header.
2415  *
2416  *	    In both these cases, ipsec_in_loopback will be set indicating
2417  *	    that IFN was generated locally.
2418  *
2419  * ROUTER : IFN could be secure or non-secure.
2420  *
2421  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2422  *	      packet in error has AH/ESP headers to validate the AH/ESP
2423  *	      headers. AH/ESP will verify whether there is a valid SA or
2424  *	      not and send it back. We will fanout again if we have more
2425  *	      data in the packet.
2426  *
2427  *	      If the packet in error does not have AH/ESP, we handle it
2428  *	      like any other case.
2429  *
2430  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2431  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2432  *	      for validation. AH/ESP will verify whether there is a
2433  *	      valid SA or not and send it back. We will fanout again if
2434  *	      we have more data in the packet.
2435  *
2436  *	      If the packet in error does not have AH/ESP, we handle it
2437  *	      like any other case.
2438  */
2439 static void
2440 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2441     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2442     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2443     zoneid_t zoneid)
2444 {
2445 	uint16_t *up;	/* Pointer to ports in ULP header */
2446 	uint32_t ports;	/* reversed ports for fanout */
2447 	ipha_t ripha;	/* With reversed addresses */
2448 	mblk_t *first_mp;
2449 	ipsec_in_t *ii;
2450 	tcph_t	*tcph;
2451 	conn_t	*connp;
2452 	ip_stack_t *ipst;
2453 
2454 	ASSERT(ill != NULL);
2455 
2456 	ASSERT(recv_ill != NULL);
2457 	ipst = recv_ill->ill_ipst;
2458 
2459 	first_mp = mp;
2460 	if (mctl_present) {
2461 		mp = first_mp->b_cont;
2462 		ASSERT(mp != NULL);
2463 
2464 		ii = (ipsec_in_t *)first_mp->b_rptr;
2465 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2466 	} else {
2467 		ii = NULL;
2468 	}
2469 
2470 	/*
2471 	 * We need a separate IP header with the source and destination
2472 	 * addresses reversed to do fanout/classification because the ipha in
2473 	 * the ICMP error is in the form we sent it out.
2474 	 */
2475 	ripha.ipha_src = ipha->ipha_dst;
2476 	ripha.ipha_dst = ipha->ipha_src;
2477 	ripha.ipha_protocol = ipha->ipha_protocol;
2478 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2479 
2480 	ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2481 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2482 	    ntohl(ipha->ipha_dst),
2483 	    icmph->icmph_type, icmph->icmph_code));
2484 
2485 	switch (ipha->ipha_protocol) {
2486 	case IPPROTO_UDP:
2487 		/*
2488 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2489 		 * transport header.
2490 		 */
2491 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2492 		    mp->b_wptr) {
2493 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2494 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2495 				goto discard_pkt;
2496 			}
2497 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2498 			ipha = (ipha_t *)&icmph[1];
2499 		}
2500 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2501 
2502 		/* Attempt to find a client stream based on port. */
2503 		((uint16_t *)&ports)[0] = up[1];
2504 		((uint16_t *)&ports)[1] = up[0];
2505 		ip2dbg(("icmp_inbound_error: UDP ports %d to %d\n",
2506 		    ntohs(up[0]), ntohs(up[1])));
2507 
2508 		/* Have to change db_type after any pullupmsg */
2509 		DB_TYPE(mp) = M_CTL;
2510 
2511 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2512 		    mctl_present, ip_policy, recv_ill, zoneid);
2513 		return;
2514 
2515 	case IPPROTO_TCP:
2516 		/*
2517 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2518 		 * transport header.
2519 		 */
2520 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2521 		    mp->b_wptr) {
2522 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2523 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2524 				goto discard_pkt;
2525 			}
2526 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2527 			ipha = (ipha_t *)&icmph[1];
2528 		}
2529 		/*
2530 		 * Find a TCP client stream for this packet.
2531 		 * Note that we do a reverse lookup since the header is
2532 		 * in the form we sent it out.
2533 		 */
2534 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2535 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2536 		    ipst);
2537 		if (connp == NULL)
2538 			goto discard_pkt;
2539 
2540 		/* Have to change db_type after any pullupmsg */
2541 		DB_TYPE(mp) = M_CTL;
2542 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2543 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2544 		return;
2545 
2546 	case IPPROTO_SCTP:
2547 		/*
2548 		 * Verify we have at least ICMP_MIN_SCTP_HDR_LEN bytes of
2549 		 * transport header, in the first mp.
2550 		 */
2551 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_SCTP_HDR_LEN >
2552 		    mp->b_wptr) {
2553 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2554 			    ICMP_MIN_SCTP_HDR_LEN - mp->b_rptr)) {
2555 				goto discard_pkt;
2556 			}
2557 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2558 			ipha = (ipha_t *)&icmph[1];
2559 		}
2560 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2561 		/* Find a SCTP client stream for this packet. */
2562 		((uint16_t *)&ports)[0] = up[1];
2563 		((uint16_t *)&ports)[1] = up[0];
2564 
2565 		/* Have to change db_type after any pullupmsg */
2566 		DB_TYPE(mp) = M_CTL;
2567 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2568 		    mctl_present, ip_policy, zoneid);
2569 		return;
2570 
2571 	case IPPROTO_ESP:
2572 	case IPPROTO_AH: {
2573 		int ipsec_rc;
2574 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2575 
2576 		/*
2577 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2578 		 * We will re-use the IPSEC_IN if it is already present as
2579 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2580 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2581 		 * one and attach it in the front.
2582 		 */
2583 		if (ii != NULL) {
2584 			/*
2585 			 * ip_fanout_proto_again converts the ICMP errors
2586 			 * that come back from AH/ESP to M_DATA so that
2587 			 * if it is non-AH/ESP and we do a pullupmsg in
2588 			 * this function, it would work. Convert it back
2589 			 * to M_CTL before we send up as this is a ICMP
2590 			 * error. This could have been generated locally or
2591 			 * by some router. Validate the inner IPsec
2592 			 * headers.
2593 			 *
2594 			 * NOTE : ill_index is used by ip_fanout_proto_again
2595 			 * to locate the ill.
2596 			 */
2597 			ASSERT(ill != NULL);
2598 			ii->ipsec_in_ill_index =
2599 			    ill->ill_phyint->phyint_ifindex;
2600 			ii->ipsec_in_rill_index =
2601 			    recv_ill->ill_phyint->phyint_ifindex;
2602 			DB_TYPE(first_mp->b_cont) = M_CTL;
2603 		} else {
2604 			/*
2605 			 * IPSEC_IN is not present. We attach a ipsec_in
2606 			 * message and send up to IPsec for validating
2607 			 * and removing the IPsec headers. Clear
2608 			 * ipsec_in_secure so that when we return
2609 			 * from IPsec, we don't mistakenly think that this
2610 			 * is a secure packet came from the network.
2611 			 *
2612 			 * NOTE : ill_index is used by ip_fanout_proto_again
2613 			 * to locate the ill.
2614 			 */
2615 			ASSERT(first_mp == mp);
2616 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2617 			if (first_mp == NULL) {
2618 				freemsg(mp);
2619 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2620 				return;
2621 			}
2622 			ii = (ipsec_in_t *)first_mp->b_rptr;
2623 
2624 			/* This is not a secure packet */
2625 			ii->ipsec_in_secure = B_FALSE;
2626 			first_mp->b_cont = mp;
2627 			DB_TYPE(mp) = M_CTL;
2628 			ASSERT(ill != NULL);
2629 			ii->ipsec_in_ill_index =
2630 			    ill->ill_phyint->phyint_ifindex;
2631 			ii->ipsec_in_rill_index =
2632 			    recv_ill->ill_phyint->phyint_ifindex;
2633 		}
2634 
2635 		if (!ipsec_loaded(ipss)) {
2636 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2637 			return;
2638 		}
2639 
2640 		if (ipha->ipha_protocol == IPPROTO_ESP)
2641 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2642 		else
2643 			ipsec_rc = ipsecah_icmp_error(first_mp);
2644 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2645 			return;
2646 
2647 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2648 		return;
2649 	}
2650 	case IPPROTO_ENCAP:
2651 	case IPPROTO_IPV6:
2652 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2653 			ipha_t *in_ipha;
2654 
2655 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2656 			    mp->b_wptr) {
2657 				if (!pullupmsg(mp, (uchar_t *)ipha +
2658 				    hdr_length + sizeof (ipha_t) -
2659 				    mp->b_rptr)) {
2660 					goto discard_pkt;
2661 				}
2662 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2663 				ipha = (ipha_t *)&icmph[1];
2664 			}
2665 			/*
2666 			 * Caller has verified that length has to be
2667 			 * at least the size of IP header.
2668 			 */
2669 			ASSERT(hdr_length >= sizeof (ipha_t));
2670 			/*
2671 			 * Check the sanity of the inner IP header like
2672 			 * we did for the outer header.
2673 			 */
2674 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2675 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION) ||
2676 			    IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t))
2677 				goto discard_pkt;
2678 			/* Check for Self-encapsulated tunnels */
2679 			if (in_ipha->ipha_src == ipha->ipha_src &&
2680 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2681 
2682 				mp = icmp_inbound_self_encap_error(mp,
2683 				    iph_hdr_length, hdr_length);
2684 				if (mp == NULL)
2685 					goto discard_pkt;
2686 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2687 				ipha = (ipha_t *)&icmph[1];
2688 				hdr_length = IPH_HDR_LENGTH(ipha);
2689 				/*
2690 				 * The packet in error is self-encapsualted.
2691 				 * And we are finding it further encapsulated
2692 				 * which we could not have possibly generated.
2693 				 */
2694 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2695 					goto discard_pkt;
2696 				}
2697 				icmp_inbound_error_fanout(q, ill, first_mp,
2698 				    icmph, ipha, iph_hdr_length, hdr_length,
2699 				    mctl_present, ip_policy, recv_ill, zoneid);
2700 				return;
2701 			}
2702 		}
2703 
2704 		DB_TYPE(mp) = M_CTL;
2705 		if (icmp_inbound_iptun_fanout(first_mp, &ripha, ill, ipst))
2706 			return;
2707 		/*
2708 		 * No IP tunnel is interested, fallthrough and see
2709 		 * if a raw socket will want it.
2710 		 */
2711 		/* FALLTHRU */
2712 	default:
2713 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2714 		    ip_policy, recv_ill, zoneid);
2715 		return;
2716 	}
2717 	/* NOTREACHED */
2718 discard_pkt:
2719 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2720 drop_pkt:;
2721 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2722 	freemsg(first_mp);
2723 }
2724 
2725 /*
2726  * Common IP options parser.
2727  *
2728  * Setup routine: fill in *optp with options-parsing state, then
2729  * tail-call ipoptp_next to return the first option.
2730  */
2731 uint8_t
2732 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2733 {
2734 	uint32_t totallen; /* total length of all options */
2735 
2736 	totallen = ipha->ipha_version_and_hdr_length -
2737 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2738 	totallen <<= 2;
2739 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2740 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2741 	optp->ipoptp_flags = 0;
2742 	return (ipoptp_next(optp));
2743 }
2744 
2745 /*
2746  * Common IP options parser: extract next option.
2747  */
2748 uint8_t
2749 ipoptp_next(ipoptp_t *optp)
2750 {
2751 	uint8_t *end = optp->ipoptp_end;
2752 	uint8_t *cur = optp->ipoptp_next;
2753 	uint8_t opt, len, pointer;
2754 
2755 	/*
2756 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2757 	 * has been corrupted.
2758 	 */
2759 	ASSERT(cur <= end);
2760 
2761 	if (cur == end)
2762 		return (IPOPT_EOL);
2763 
2764 	opt = cur[IPOPT_OPTVAL];
2765 
2766 	/*
2767 	 * Skip any NOP options.
2768 	 */
2769 	while (opt == IPOPT_NOP) {
2770 		cur++;
2771 		if (cur == end)
2772 			return (IPOPT_EOL);
2773 		opt = cur[IPOPT_OPTVAL];
2774 	}
2775 
2776 	if (opt == IPOPT_EOL)
2777 		return (IPOPT_EOL);
2778 
2779 	/*
2780 	 * Option requiring a length.
2781 	 */
2782 	if ((cur + 1) >= end) {
2783 		optp->ipoptp_flags |= IPOPTP_ERROR;
2784 		return (IPOPT_EOL);
2785 	}
2786 	len = cur[IPOPT_OLEN];
2787 	if (len < 2) {
2788 		optp->ipoptp_flags |= IPOPTP_ERROR;
2789 		return (IPOPT_EOL);
2790 	}
2791 	optp->ipoptp_cur = cur;
2792 	optp->ipoptp_len = len;
2793 	optp->ipoptp_next = cur + len;
2794 	if (cur + len > end) {
2795 		optp->ipoptp_flags |= IPOPTP_ERROR;
2796 		return (IPOPT_EOL);
2797 	}
2798 
2799 	/*
2800 	 * For the options which require a pointer field, make sure
2801 	 * its there, and make sure it points to either something
2802 	 * inside this option, or the end of the option.
2803 	 */
2804 	switch (opt) {
2805 	case IPOPT_RR:
2806 	case IPOPT_TS:
2807 	case IPOPT_LSRR:
2808 	case IPOPT_SSRR:
2809 		if (len <= IPOPT_OFFSET) {
2810 			optp->ipoptp_flags |= IPOPTP_ERROR;
2811 			return (opt);
2812 		}
2813 		pointer = cur[IPOPT_OFFSET];
2814 		if (pointer - 1 > len) {
2815 			optp->ipoptp_flags |= IPOPTP_ERROR;
2816 			return (opt);
2817 		}
2818 		break;
2819 	}
2820 
2821 	/*
2822 	 * Sanity check the pointer field based on the type of the
2823 	 * option.
2824 	 */
2825 	switch (opt) {
2826 	case IPOPT_RR:
2827 	case IPOPT_SSRR:
2828 	case IPOPT_LSRR:
2829 		if (pointer < IPOPT_MINOFF_SR)
2830 			optp->ipoptp_flags |= IPOPTP_ERROR;
2831 		break;
2832 	case IPOPT_TS:
2833 		if (pointer < IPOPT_MINOFF_IT)
2834 			optp->ipoptp_flags |= IPOPTP_ERROR;
2835 		/*
2836 		 * Note that the Internet Timestamp option also
2837 		 * contains two four bit fields (the Overflow field,
2838 		 * and the Flag field), which follow the pointer
2839 		 * field.  We don't need to check that these fields
2840 		 * fall within the length of the option because this
2841 		 * was implicitely done above.  We've checked that the
2842 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2843 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2844 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2845 		 */
2846 		ASSERT(len > IPOPT_POS_OV_FLG);
2847 		break;
2848 	}
2849 
2850 	return (opt);
2851 }
2852 
2853 /*
2854  * Use the outgoing IP header to create an IP_OPTIONS option the way
2855  * it was passed down from the application.
2856  */
2857 int
2858 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2859 {
2860 	ipoptp_t	opts;
2861 	const uchar_t	*opt;
2862 	uint8_t		optval;
2863 	uint8_t		optlen;
2864 	uint32_t	len = 0;
2865 	uchar_t	*buf1 = buf;
2866 
2867 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2868 	len += IP_ADDR_LEN;
2869 	bzero(buf1, IP_ADDR_LEN);
2870 
2871 	/*
2872 	 * OK to cast away const here, as we don't store through the returned
2873 	 * opts.ipoptp_cur pointer.
2874 	 */
2875 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2876 	    optval != IPOPT_EOL;
2877 	    optval = ipoptp_next(&opts)) {
2878 		int	off;
2879 
2880 		opt = opts.ipoptp_cur;
2881 		optlen = opts.ipoptp_len;
2882 		switch (optval) {
2883 		case IPOPT_SSRR:
2884 		case IPOPT_LSRR:
2885 
2886 			/*
2887 			 * Insert ipha_dst as the first entry in the source
2888 			 * route and move down the entries on step.
2889 			 * The last entry gets placed at buf1.
2890 			 */
2891 			buf[IPOPT_OPTVAL] = optval;
2892 			buf[IPOPT_OLEN] = optlen;
2893 			buf[IPOPT_OFFSET] = optlen;
2894 
2895 			off = optlen - IP_ADDR_LEN;
2896 			if (off < 0) {
2897 				/* No entries in source route */
2898 				break;
2899 			}
2900 			/* Last entry in source route */
2901 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2902 			off -= IP_ADDR_LEN;
2903 
2904 			while (off > 0) {
2905 				bcopy(opt + off,
2906 				    buf + off + IP_ADDR_LEN,
2907 				    IP_ADDR_LEN);
2908 				off -= IP_ADDR_LEN;
2909 			}
2910 			/* ipha_dst into first slot */
2911 			bcopy(&ipha->ipha_dst,
2912 			    buf + off + IP_ADDR_LEN,
2913 			    IP_ADDR_LEN);
2914 			buf += optlen;
2915 			len += optlen;
2916 			break;
2917 
2918 		case IPOPT_COMSEC:
2919 		case IPOPT_SECURITY:
2920 			/* if passing up a label is not ok, then remove */
2921 			if (is_system_labeled())
2922 				break;
2923 			/* FALLTHROUGH */
2924 		default:
2925 			bcopy(opt, buf, optlen);
2926 			buf += optlen;
2927 			len += optlen;
2928 			break;
2929 		}
2930 	}
2931 done:
2932 	/* Pad the resulting options */
2933 	while (len & 0x3) {
2934 		*buf++ = IPOPT_EOL;
2935 		len++;
2936 	}
2937 	return (len);
2938 }
2939 
2940 /*
2941  * Update any record route or timestamp options to include this host.
2942  * Reverse any source route option.
2943  * This routine assumes that the options are well formed i.e. that they
2944  * have already been checked.
2945  */
2946 static void
2947 icmp_options_update(ipha_t *ipha)
2948 {
2949 	ipoptp_t	opts;
2950 	uchar_t		*opt;
2951 	uint8_t		optval;
2952 	ipaddr_t	src;		/* Our local address */
2953 	ipaddr_t	dst;
2954 
2955 	ip2dbg(("icmp_options_update\n"));
2956 	src = ipha->ipha_src;
2957 	dst = ipha->ipha_dst;
2958 
2959 	for (optval = ipoptp_first(&opts, ipha);
2960 	    optval != IPOPT_EOL;
2961 	    optval = ipoptp_next(&opts)) {
2962 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2963 		opt = opts.ipoptp_cur;
2964 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2965 		    optval, opts.ipoptp_len));
2966 		switch (optval) {
2967 			int off1, off2;
2968 		case IPOPT_SSRR:
2969 		case IPOPT_LSRR:
2970 			/*
2971 			 * Reverse the source route.  The first entry
2972 			 * should be the next to last one in the current
2973 			 * source route (the last entry is our address).
2974 			 * The last entry should be the final destination.
2975 			 */
2976 			off1 = IPOPT_MINOFF_SR - 1;
2977 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2978 			if (off2 < 0) {
2979 				/* No entries in source route */
2980 				ip1dbg((
2981 				    "icmp_options_update: bad src route\n"));
2982 				break;
2983 			}
2984 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2985 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2986 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2987 			off2 -= IP_ADDR_LEN;
2988 
2989 			while (off1 < off2) {
2990 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2991 				bcopy((char *)opt + off2, (char *)opt + off1,
2992 				    IP_ADDR_LEN);
2993 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2994 				off1 += IP_ADDR_LEN;
2995 				off2 -= IP_ADDR_LEN;
2996 			}
2997 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2998 			break;
2999 		}
3000 	}
3001 }
3002 
3003 /*
3004  * Process received ICMP Redirect messages.
3005  */
3006 static void
3007 icmp_redirect(ill_t *ill, mblk_t *mp)
3008 {
3009 	ipha_t	*ipha;
3010 	int	iph_hdr_length;
3011 	icmph_t	*icmph;
3012 	ipha_t	*ipha_err;
3013 	ire_t	*ire;
3014 	ire_t	*prev_ire;
3015 	ire_t	*save_ire;
3016 	ipaddr_t  src, dst, gateway;
3017 	iulp_t	ulp_info = { 0 };
3018 	int	error;
3019 	ip_stack_t *ipst;
3020 
3021 	ASSERT(ill != NULL);
3022 	ipst = ill->ill_ipst;
3023 
3024 	ipha = (ipha_t *)mp->b_rptr;
3025 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3026 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3027 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3028 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3029 		freemsg(mp);
3030 		return;
3031 	}
3032 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3033 	ipha_err = (ipha_t *)&icmph[1];
3034 	src = ipha->ipha_src;
3035 	dst = ipha_err->ipha_dst;
3036 	gateway = icmph->icmph_rd_gateway;
3037 	/* Make sure the new gateway is reachable somehow. */
3038 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3039 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3040 	/*
3041 	 * Make sure we had a route for the dest in question and that
3042 	 * that route was pointing to the old gateway (the source of the
3043 	 * redirect packet.)
3044 	 */
3045 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3046 	    NULL, MATCH_IRE_GW, ipst);
3047 	/*
3048 	 * Check that
3049 	 *	the redirect was not from ourselves
3050 	 *	the new gateway and the old gateway are directly reachable
3051 	 */
3052 	if (!prev_ire ||
3053 	    !ire ||
3054 	    ire->ire_type == IRE_LOCAL) {
3055 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3056 		freemsg(mp);
3057 		if (ire != NULL)
3058 			ire_refrele(ire);
3059 		if (prev_ire != NULL)
3060 			ire_refrele(prev_ire);
3061 		return;
3062 	}
3063 
3064 	/*
3065 	 * Should we use the old ULP info to create the new gateway?  From
3066 	 * a user's perspective, we should inherit the info so that it
3067 	 * is a "smooth" transition.  If we do not do that, then new
3068 	 * connections going thru the new gateway will have no route metrics,
3069 	 * which is counter-intuitive to user.  From a network point of
3070 	 * view, this may or may not make sense even though the new gateway
3071 	 * is still directly connected to us so the route metrics should not
3072 	 * change much.
3073 	 *
3074 	 * But if the old ire_uinfo is not initialized, we do another
3075 	 * recursive lookup on the dest using the new gateway.  There may
3076 	 * be a route to that.  If so, use it to initialize the redirect
3077 	 * route.
3078 	 */
3079 	if (prev_ire->ire_uinfo.iulp_set) {
3080 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3081 	} else {
3082 		ire_t *tmp_ire;
3083 		ire_t *sire;
3084 
3085 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3086 		    ALL_ZONES, 0, NULL,
3087 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3088 		    ipst);
3089 		if (sire != NULL) {
3090 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3091 			/*
3092 			 * If sire != NULL, ire_ftable_lookup() should not
3093 			 * return a NULL value.
3094 			 */
3095 			ASSERT(tmp_ire != NULL);
3096 			ire_refrele(tmp_ire);
3097 			ire_refrele(sire);
3098 		} else if (tmp_ire != NULL) {
3099 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3100 			    sizeof (iulp_t));
3101 			ire_refrele(tmp_ire);
3102 		}
3103 	}
3104 	if (prev_ire->ire_type == IRE_CACHE)
3105 		ire_delete(prev_ire);
3106 	ire_refrele(prev_ire);
3107 	/*
3108 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3109 	 * require TOS routing
3110 	 */
3111 	switch (icmph->icmph_code) {
3112 	case 0:
3113 	case 1:
3114 		/* TODO: TOS specificity for cases 2 and 3 */
3115 	case 2:
3116 	case 3:
3117 		break;
3118 	default:
3119 		freemsg(mp);
3120 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3121 		ire_refrele(ire);
3122 		return;
3123 	}
3124 	/*
3125 	 * Create a Route Association.  This will allow us to remember that
3126 	 * someone we believe told us to use the particular gateway.
3127 	 */
3128 	save_ire = ire;
3129 	ire = ire_create(
3130 	    (uchar_t *)&dst,			/* dest addr */
3131 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3132 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3133 	    (uchar_t *)&gateway,		/* gateway addr */
3134 	    &save_ire->ire_max_frag,		/* max frag */
3135 	    NULL,				/* no src nce */
3136 	    NULL,				/* no rfq */
3137 	    NULL,				/* no stq */
3138 	    IRE_HOST,
3139 	    NULL,				/* ipif */
3140 	    0,					/* cmask */
3141 	    0,					/* phandle */
3142 	    0,					/* ihandle */
3143 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3144 	    &ulp_info,
3145 	    NULL,				/* tsol_gc_t */
3146 	    NULL,				/* gcgrp */
3147 	    ipst);
3148 
3149 	if (ire == NULL) {
3150 		freemsg(mp);
3151 		ire_refrele(save_ire);
3152 		return;
3153 	}
3154 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3155 	ire_refrele(save_ire);
3156 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3157 
3158 	if (error == 0) {
3159 		ire_refrele(ire);		/* Held in ire_add_v4 */
3160 		/* tell routing sockets that we received a redirect */
3161 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3162 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3163 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3164 	}
3165 
3166 	/*
3167 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3168 	 * This together with the added IRE has the effect of
3169 	 * modifying an existing redirect.
3170 	 */
3171 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3172 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3173 	if (prev_ire != NULL) {
3174 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3175 			ire_delete(prev_ire);
3176 		ire_refrele(prev_ire);
3177 	}
3178 
3179 	freemsg(mp);
3180 }
3181 
3182 /*
3183  * Generate an ICMP parameter problem message.
3184  */
3185 static void
3186 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3187 	ip_stack_t *ipst)
3188 {
3189 	icmph_t	icmph;
3190 	boolean_t mctl_present;
3191 	mblk_t *first_mp;
3192 
3193 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3194 
3195 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3196 		if (mctl_present)
3197 			freeb(first_mp);
3198 		return;
3199 	}
3200 
3201 	bzero(&icmph, sizeof (icmph_t));
3202 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3203 	icmph.icmph_pp_ptr = ptr;
3204 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3205 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3206 	    ipst);
3207 }
3208 
3209 /*
3210  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3211  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3212  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3213  * an icmp error packet can be sent.
3214  * Assigns an appropriate source address to the packet. If ipha_dst is
3215  * one of our addresses use it for source. Otherwise pick a source based
3216  * on a route lookup back to ipha_src.
3217  * Note that ipha_src must be set here since the
3218  * packet is likely to arrive on an ill queue in ip_wput() which will
3219  * not set a source address.
3220  */
3221 static void
3222 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3223     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3224 {
3225 	ipaddr_t dst;
3226 	icmph_t	*icmph;
3227 	ipha_t	*ipha;
3228 	uint_t	len_needed;
3229 	size_t	msg_len;
3230 	mblk_t	*mp1;
3231 	ipaddr_t src;
3232 	ire_t	*ire;
3233 	mblk_t *ipsec_mp;
3234 	ipsec_out_t	*io = NULL;
3235 
3236 	if (mctl_present) {
3237 		/*
3238 		 * If it is :
3239 		 *
3240 		 * 1) a IPSEC_OUT, then this is caused by outbound
3241 		 *    datagram originating on this host. IPsec processing
3242 		 *    may or may not have been done. Refer to comments above
3243 		 *    icmp_inbound_error_fanout for details.
3244 		 *
3245 		 * 2) a IPSEC_IN if we are generating a icmp_message
3246 		 *    for an incoming datagram destined for us i.e called
3247 		 *    from ip_fanout_send_icmp.
3248 		 */
3249 		ipsec_info_t *in;
3250 		ipsec_mp = mp;
3251 		mp = ipsec_mp->b_cont;
3252 
3253 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3254 		ipha = (ipha_t *)mp->b_rptr;
3255 
3256 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3257 		    in->ipsec_info_type == IPSEC_IN);
3258 
3259 		if (in->ipsec_info_type == IPSEC_IN) {
3260 			/*
3261 			 * Convert the IPSEC_IN to IPSEC_OUT.
3262 			 */
3263 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL, zoneid)) {
3264 				BUMP_MIB(&ipst->ips_ip_mib,
3265 				    ipIfStatsOutDiscards);
3266 				return;
3267 			}
3268 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3269 		} else {
3270 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3271 			io = (ipsec_out_t *)in;
3272 			/*
3273 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3274 			 * ire lookup.
3275 			 */
3276 			io->ipsec_out_proc_begin = B_FALSE;
3277 		}
3278 		ASSERT(zoneid != ALL_ZONES);
3279 		/*
3280 		 * The IPSEC_IN (now an IPSEC_OUT) didn't have its zoneid
3281 		 * initialized.  We need to do that now.
3282 		 */
3283 		io->ipsec_out_zoneid = zoneid;
3284 	} else {
3285 		/*
3286 		 * This is in clear. The icmp message we are building
3287 		 * here should go out in clear.
3288 		 *
3289 		 * Pardon the convolution of it all, but it's easier to
3290 		 * allocate a "use cleartext" IPSEC_IN message and convert
3291 		 * it than it is to allocate a new one.
3292 		 */
3293 		ipsec_in_t *ii;
3294 		ASSERT(DB_TYPE(mp) == M_DATA);
3295 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3296 		if (ipsec_mp == NULL) {
3297 			freemsg(mp);
3298 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3299 			return;
3300 		}
3301 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3302 
3303 		/* This is not a secure packet */
3304 		ii->ipsec_in_secure = B_FALSE;
3305 		ipsec_mp->b_cont = mp;
3306 		ipha = (ipha_t *)mp->b_rptr;
3307 		/*
3308 		 * Convert the IPSEC_IN to IPSEC_OUT.
3309 		 */
3310 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL, zoneid)) {
3311 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3312 			return;
3313 		}
3314 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3315 	}
3316 
3317 	/* Remember our eventual destination */
3318 	dst = ipha->ipha_src;
3319 
3320 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3321 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3322 	if (ire != NULL &&
3323 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3324 		src = ipha->ipha_dst;
3325 	} else {
3326 		if (ire != NULL)
3327 			ire_refrele(ire);
3328 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3329 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3330 		    ipst);
3331 		if (ire == NULL) {
3332 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3333 			freemsg(ipsec_mp);
3334 			return;
3335 		}
3336 		src = ire->ire_src_addr;
3337 	}
3338 
3339 	if (ire != NULL)
3340 		ire_refrele(ire);
3341 
3342 	/*
3343 	 * Check if we can send back more then 8 bytes in addition to
3344 	 * the IP header.  We try to send 64 bytes of data and the internal
3345 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3346 	 */
3347 	len_needed = IPH_HDR_LENGTH(ipha);
3348 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3349 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3350 
3351 		if (!pullupmsg(mp, -1)) {
3352 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3353 			freemsg(ipsec_mp);
3354 			return;
3355 		}
3356 		ipha = (ipha_t *)mp->b_rptr;
3357 
3358 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3359 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3360 			    len_needed));
3361 		} else {
3362 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3363 
3364 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3365 			len_needed += ip_hdr_length_v6(mp, ip6h);
3366 		}
3367 	}
3368 	len_needed += ipst->ips_ip_icmp_return;
3369 	msg_len = msgdsize(mp);
3370 	if (msg_len > len_needed) {
3371 		(void) adjmsg(mp, len_needed - msg_len);
3372 		msg_len = len_needed;
3373 	}
3374 	/* Make sure we propagate the cred/label for TX */
3375 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3376 	if (mp1 == NULL) {
3377 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3378 		freemsg(ipsec_mp);
3379 		return;
3380 	}
3381 	mp1->b_cont = mp;
3382 	mp = mp1;
3383 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3384 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3385 	    io->ipsec_out_type == IPSEC_OUT);
3386 	ipsec_mp->b_cont = mp;
3387 
3388 	/*
3389 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3390 	 * node generates be accepted in peace by all on-host destinations.
3391 	 * If we do NOT assume that all on-host destinations trust
3392 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3393 	 * (Look for ipsec_out_icmp_loopback).
3394 	 */
3395 	io->ipsec_out_icmp_loopback = B_TRUE;
3396 
3397 	ipha = (ipha_t *)mp->b_rptr;
3398 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3399 	*ipha = icmp_ipha;
3400 	ipha->ipha_src = src;
3401 	ipha->ipha_dst = dst;
3402 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3403 	msg_len += sizeof (icmp_ipha) + len;
3404 	if (msg_len > IP_MAXPACKET) {
3405 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3406 		msg_len = IP_MAXPACKET;
3407 	}
3408 	ipha->ipha_length = htons((uint16_t)msg_len);
3409 	icmph = (icmph_t *)&ipha[1];
3410 	bcopy(stuff, icmph, len);
3411 	icmph->icmph_checksum = 0;
3412 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3413 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3414 	put(q, ipsec_mp);
3415 }
3416 
3417 /*
3418  * Determine if an ICMP error packet can be sent given the rate limit.
3419  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3420  * in milliseconds) and a burst size. Burst size number of packets can
3421  * be sent arbitrarely closely spaced.
3422  * The state is tracked using two variables to implement an approximate
3423  * token bucket filter:
3424  *	icmp_pkt_err_last - lbolt value when the last burst started
3425  *	icmp_pkt_err_sent - number of packets sent in current burst
3426  */
3427 boolean_t
3428 icmp_err_rate_limit(ip_stack_t *ipst)
3429 {
3430 	clock_t now = TICK_TO_MSEC(lbolt);
3431 	uint_t refilled; /* Number of packets refilled in tbf since last */
3432 	/* Guard against changes by loading into local variable */
3433 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3434 
3435 	if (err_interval == 0)
3436 		return (B_FALSE);
3437 
3438 	if (ipst->ips_icmp_pkt_err_last > now) {
3439 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3440 		ipst->ips_icmp_pkt_err_last = 0;
3441 		ipst->ips_icmp_pkt_err_sent = 0;
3442 	}
3443 	/*
3444 	 * If we are in a burst update the token bucket filter.
3445 	 * Update the "last" time to be close to "now" but make sure
3446 	 * we don't loose precision.
3447 	 */
3448 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3449 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3450 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3451 			ipst->ips_icmp_pkt_err_sent = 0;
3452 		} else {
3453 			ipst->ips_icmp_pkt_err_sent -= refilled;
3454 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3455 		}
3456 	}
3457 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3458 		/* Start of new burst */
3459 		ipst->ips_icmp_pkt_err_last = now;
3460 	}
3461 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3462 		ipst->ips_icmp_pkt_err_sent++;
3463 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3464 		    ipst->ips_icmp_pkt_err_sent));
3465 		return (B_FALSE);
3466 	}
3467 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3468 	return (B_TRUE);
3469 }
3470 
3471 /*
3472  * Check if it is ok to send an IPv4 ICMP error packet in
3473  * response to the IPv4 packet in mp.
3474  * Free the message and return null if no
3475  * ICMP error packet should be sent.
3476  */
3477 static mblk_t *
3478 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3479 {
3480 	icmph_t	*icmph;
3481 	ipha_t	*ipha;
3482 	uint_t	len_needed;
3483 	ire_t	*src_ire;
3484 	ire_t	*dst_ire;
3485 
3486 	if (!mp)
3487 		return (NULL);
3488 	ipha = (ipha_t *)mp->b_rptr;
3489 	if (ip_csum_hdr(ipha)) {
3490 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3491 		freemsg(mp);
3492 		return (NULL);
3493 	}
3494 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3495 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3496 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3497 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3498 	if (src_ire != NULL || dst_ire != NULL ||
3499 	    CLASSD(ipha->ipha_dst) ||
3500 	    CLASSD(ipha->ipha_src) ||
3501 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3502 		/* Note: only errors to the fragment with offset 0 */
3503 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3504 		freemsg(mp);
3505 		if (src_ire != NULL)
3506 			ire_refrele(src_ire);
3507 		if (dst_ire != NULL)
3508 			ire_refrele(dst_ire);
3509 		return (NULL);
3510 	}
3511 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3512 		/*
3513 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3514 		 * errors in response to any ICMP errors.
3515 		 */
3516 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3517 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3518 			if (!pullupmsg(mp, len_needed)) {
3519 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3520 				freemsg(mp);
3521 				return (NULL);
3522 			}
3523 			ipha = (ipha_t *)mp->b_rptr;
3524 		}
3525 		icmph = (icmph_t *)
3526 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3527 		switch (icmph->icmph_type) {
3528 		case ICMP_DEST_UNREACHABLE:
3529 		case ICMP_SOURCE_QUENCH:
3530 		case ICMP_TIME_EXCEEDED:
3531 		case ICMP_PARAM_PROBLEM:
3532 		case ICMP_REDIRECT:
3533 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3534 			freemsg(mp);
3535 			return (NULL);
3536 		default:
3537 			break;
3538 		}
3539 	}
3540 	/*
3541 	 * If this is a labeled system, then check to see if we're allowed to
3542 	 * send a response to this particular sender.  If not, then just drop.
3543 	 */
3544 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3545 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3546 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3547 		freemsg(mp);
3548 		return (NULL);
3549 	}
3550 	if (icmp_err_rate_limit(ipst)) {
3551 		/*
3552 		 * Only send ICMP error packets every so often.
3553 		 * This should be done on a per port/source basis,
3554 		 * but for now this will suffice.
3555 		 */
3556 		freemsg(mp);
3557 		return (NULL);
3558 	}
3559 	return (mp);
3560 }
3561 
3562 /*
3563  * Generate an ICMP redirect message.
3564  */
3565 static void
3566 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3567 {
3568 	icmph_t	icmph;
3569 
3570 	/*
3571 	 * We are called from ip_rput where we could
3572 	 * not have attached an IPSEC_IN.
3573 	 */
3574 	ASSERT(mp->b_datap->db_type == M_DATA);
3575 
3576 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3577 		return;
3578 	}
3579 
3580 	bzero(&icmph, sizeof (icmph_t));
3581 	icmph.icmph_type = ICMP_REDIRECT;
3582 	icmph.icmph_code = 1;
3583 	icmph.icmph_rd_gateway = gateway;
3584 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3585 	/* Redirects sent by router, and router is global zone */
3586 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3587 }
3588 
3589 /*
3590  * Generate an ICMP time exceeded message.
3591  */
3592 void
3593 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3594     ip_stack_t *ipst)
3595 {
3596 	icmph_t	icmph;
3597 	boolean_t mctl_present;
3598 	mblk_t *first_mp;
3599 
3600 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3601 
3602 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3603 		if (mctl_present)
3604 			freeb(first_mp);
3605 		return;
3606 	}
3607 
3608 	bzero(&icmph, sizeof (icmph_t));
3609 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3610 	icmph.icmph_code = code;
3611 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3612 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3613 	    ipst);
3614 }
3615 
3616 /*
3617  * Generate an ICMP unreachable message.
3618  */
3619 void
3620 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3621     ip_stack_t *ipst)
3622 {
3623 	icmph_t	icmph;
3624 	mblk_t *first_mp;
3625 	boolean_t mctl_present;
3626 
3627 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3628 
3629 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3630 		if (mctl_present)
3631 			freeb(first_mp);
3632 		return;
3633 	}
3634 
3635 	bzero(&icmph, sizeof (icmph_t));
3636 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3637 	icmph.icmph_code = code;
3638 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3639 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3640 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3641 	    zoneid, ipst);
3642 }
3643 
3644 /*
3645  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3646  * duplicate.  As long as someone else holds the address, the interface will
3647  * stay down.  When that conflict goes away, the interface is brought back up.
3648  * This is done so that accidental shutdowns of addresses aren't made
3649  * permanent.  Your server will recover from a failure.
3650  *
3651  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3652  * user space process (dhcpagent).
3653  *
3654  * Recovery completes if ARP reports that the address is now ours (via
3655  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3656  *
3657  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3658  */
3659 static void
3660 ipif_dup_recovery(void *arg)
3661 {
3662 	ipif_t *ipif = arg;
3663 	ill_t *ill = ipif->ipif_ill;
3664 	mblk_t *arp_add_mp;
3665 	mblk_t *arp_del_mp;
3666 	ip_stack_t *ipst = ill->ill_ipst;
3667 
3668 	ipif->ipif_recovery_id = 0;
3669 
3670 	/*
3671 	 * No lock needed for moving or condemned check, as this is just an
3672 	 * optimization.
3673 	 */
3674 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3675 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3676 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3677 		/* No reason to try to bring this address back. */
3678 		return;
3679 	}
3680 
3681 	/* ACE_F_UNVERIFIED restarts DAD */
3682 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3683 		goto alloc_fail;
3684 
3685 	if (ipif->ipif_arp_del_mp == NULL) {
3686 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3687 			goto alloc_fail;
3688 		ipif->ipif_arp_del_mp = arp_del_mp;
3689 	}
3690 
3691 	putnext(ill->ill_rq, arp_add_mp);
3692 	return;
3693 
3694 alloc_fail:
3695 	/*
3696 	 * On allocation failure, just restart the timer.  Note that the ipif
3697 	 * is down here, so no other thread could be trying to start a recovery
3698 	 * timer.  The ill_lock protects the condemned flag and the recovery
3699 	 * timer ID.
3700 	 */
3701 	freemsg(arp_add_mp);
3702 	mutex_enter(&ill->ill_lock);
3703 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3704 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3705 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3706 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3707 	}
3708 	mutex_exit(&ill->ill_lock);
3709 }
3710 
3711 /*
3712  * This is for exclusive changes due to ARP.  Either tear down an interface due
3713  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3714  */
3715 /* ARGSUSED */
3716 static void
3717 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3718 {
3719 	ill_t	*ill = rq->q_ptr;
3720 	arh_t *arh;
3721 	ipaddr_t src;
3722 	ipif_t	*ipif;
3723 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3724 	char hbuf[MAC_STR_LEN];
3725 	char sbuf[INET_ADDRSTRLEN];
3726 	const char *failtype;
3727 	boolean_t bring_up;
3728 	ip_stack_t *ipst = ill->ill_ipst;
3729 
3730 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3731 	case AR_CN_READY:
3732 		failtype = NULL;
3733 		bring_up = B_TRUE;
3734 		break;
3735 	case AR_CN_FAILED:
3736 		failtype = "in use";
3737 		bring_up = B_FALSE;
3738 		break;
3739 	default:
3740 		failtype = "claimed";
3741 		bring_up = B_FALSE;
3742 		break;
3743 	}
3744 
3745 	arh = (arh_t *)mp->b_cont->b_rptr;
3746 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3747 
3748 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3749 	    sizeof (hbuf));
3750 	(void) ip_dot_addr(src, sbuf);
3751 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3752 
3753 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3754 		    ipif->ipif_lcl_addr != src) {
3755 			continue;
3756 		}
3757 
3758 		/*
3759 		 * If we failed on a recovery probe, then restart the timer to
3760 		 * try again later.
3761 		 */
3762 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3763 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3764 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3765 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3766 		    ipst->ips_ip_dup_recovery > 0 &&
3767 		    ipif->ipif_recovery_id == 0) {
3768 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3769 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3770 			continue;
3771 		}
3772 
3773 		/*
3774 		 * If what we're trying to do has already been done, then do
3775 		 * nothing.
3776 		 */
3777 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3778 			continue;
3779 
3780 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3781 
3782 		if (failtype == NULL) {
3783 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3784 			    ibuf);
3785 		} else {
3786 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3787 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3788 		}
3789 
3790 		if (bring_up) {
3791 			ASSERT(ill->ill_dl_up);
3792 			/*
3793 			 * Free up the ARP delete message so we can allocate
3794 			 * a fresh one through the normal path.
3795 			 */
3796 			freemsg(ipif->ipif_arp_del_mp);
3797 			ipif->ipif_arp_del_mp = NULL;
3798 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3799 			    EINPROGRESS) {
3800 				ipif->ipif_addr_ready = 1;
3801 				(void) ipif_up_done(ipif);
3802 				ASSERT(ill->ill_move_ipif == NULL);
3803 			}
3804 			continue;
3805 		}
3806 
3807 		mutex_enter(&ill->ill_lock);
3808 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3809 		ipif->ipif_flags |= IPIF_DUPLICATE;
3810 		ill->ill_ipif_dup_count++;
3811 		mutex_exit(&ill->ill_lock);
3812 		/*
3813 		 * Already exclusive on the ill; no need to handle deferred
3814 		 * processing here.
3815 		 */
3816 		(void) ipif_down(ipif, NULL, NULL);
3817 		ipif_down_tail(ipif);
3818 		mutex_enter(&ill->ill_lock);
3819 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3820 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3821 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3822 		    ipst->ips_ip_dup_recovery > 0) {
3823 			ASSERT(ipif->ipif_recovery_id == 0);
3824 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3825 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3826 		}
3827 		mutex_exit(&ill->ill_lock);
3828 	}
3829 	freemsg(mp);
3830 }
3831 
3832 /* ARGSUSED */
3833 static void
3834 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3835 {
3836 	ill_t	*ill = rq->q_ptr;
3837 	arh_t *arh;
3838 	ipaddr_t src;
3839 	ipif_t	*ipif;
3840 
3841 	arh = (arh_t *)mp->b_cont->b_rptr;
3842 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3843 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3844 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3845 			(void) ipif_resolver_up(ipif, Res_act_defend);
3846 	}
3847 	freemsg(mp);
3848 }
3849 
3850 /*
3851  * News from ARP.  ARP sends notification of interesting events down
3852  * to its clients using M_CTL messages with the interesting ARP packet
3853  * attached via b_cont.
3854  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3855  * queue as opposed to ARP sending the message to all the clients, i.e. all
3856  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3857  * table if a cache IRE is found to delete all the entries for the address in
3858  * the packet.
3859  */
3860 static void
3861 ip_arp_news(queue_t *q, mblk_t *mp)
3862 {
3863 	arcn_t		*arcn;
3864 	arh_t		*arh;
3865 	ire_t		*ire = NULL;
3866 	char		hbuf[MAC_STR_LEN];
3867 	char		sbuf[INET_ADDRSTRLEN];
3868 	ipaddr_t	src;
3869 	in6_addr_t	v6src;
3870 	boolean_t	isv6 = B_FALSE;
3871 	ipif_t		*ipif;
3872 	ill_t		*ill;
3873 	ip_stack_t	*ipst;
3874 
3875 	if (CONN_Q(q)) {
3876 		conn_t *connp = Q_TO_CONN(q);
3877 
3878 		ipst = connp->conn_netstack->netstack_ip;
3879 	} else {
3880 		ill_t *ill = (ill_t *)q->q_ptr;
3881 
3882 		ipst = ill->ill_ipst;
3883 	}
3884 
3885 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3886 		if (q->q_next) {
3887 			putnext(q, mp);
3888 		} else
3889 			freemsg(mp);
3890 		return;
3891 	}
3892 	arh = (arh_t *)mp->b_cont->b_rptr;
3893 	/* Is it one we are interested in? */
3894 	if (BE16_TO_U16(arh->arh_proto) == ETHERTYPE_IPV6) {
3895 		isv6 = B_TRUE;
3896 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3897 		    IPV6_ADDR_LEN);
3898 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3899 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3900 		    IP_ADDR_LEN);
3901 	} else {
3902 		freemsg(mp);
3903 		return;
3904 	}
3905 
3906 	ill = q->q_ptr;
3907 
3908 	arcn = (arcn_t *)mp->b_rptr;
3909 	switch (arcn->arcn_code) {
3910 	case AR_CN_BOGON:
3911 		/*
3912 		 * Someone is sending ARP packets with a source protocol
3913 		 * address that we have published and for which we believe our
3914 		 * entry is authoritative and (when ill_arp_extend is set)
3915 		 * verified to be unique on the network.
3916 		 *
3917 		 * The ARP module internally handles the cases where the sender
3918 		 * is just probing (for DAD) and where the hardware address of
3919 		 * a non-authoritative entry has changed.  Thus, these are the
3920 		 * real conflicts, and we have to do resolution.
3921 		 *
3922 		 * We back away quickly from the address if it's from DHCP or
3923 		 * otherwise temporary and hasn't been used recently (or at
3924 		 * all).  We'd like to include "deprecated" addresses here as
3925 		 * well (as there's no real reason to defend something we're
3926 		 * discarding), but IPMP "reuses" this flag to mean something
3927 		 * other than the standard meaning.
3928 		 *
3929 		 * If the ARP module above is not extended (meaning that it
3930 		 * doesn't know how to defend the address), then we just log
3931 		 * the problem as we always did and continue on.  It's not
3932 		 * right, but there's little else we can do, and those old ATM
3933 		 * users are going away anyway.
3934 		 */
3935 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3936 		    hbuf, sizeof (hbuf));
3937 		(void) ip_dot_addr(src, sbuf);
3938 		if (isv6) {
3939 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3940 			    ipst);
3941 		} else {
3942 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3943 		}
3944 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3945 			uint32_t now;
3946 			uint32_t maxage;
3947 			clock_t lused;
3948 			uint_t maxdefense;
3949 			uint_t defs;
3950 
3951 			/*
3952 			 * First, figure out if this address hasn't been used
3953 			 * in a while.  If it hasn't, then it's a better
3954 			 * candidate for abandoning.
3955 			 */
3956 			ipif = ire->ire_ipif;
3957 			ASSERT(ipif != NULL);
3958 			now = gethrestime_sec();
3959 			maxage = now - ire->ire_create_time;
3960 			if (maxage > ipst->ips_ip_max_temp_idle)
3961 				maxage = ipst->ips_ip_max_temp_idle;
3962 			lused = drv_hztousec(ddi_get_lbolt() -
3963 			    ire->ire_last_used_time) / MICROSEC + 1;
3964 			if (lused >= maxage && (ipif->ipif_flags &
3965 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3966 				maxdefense = ipst->ips_ip_max_temp_defend;
3967 			else
3968 				maxdefense = ipst->ips_ip_max_defend;
3969 
3970 			/*
3971 			 * Now figure out how many times we've defended
3972 			 * ourselves.  Ignore defenses that happened long in
3973 			 * the past.
3974 			 */
3975 			mutex_enter(&ire->ire_lock);
3976 			if ((defs = ire->ire_defense_count) > 0 &&
3977 			    now - ire->ire_defense_time >
3978 			    ipst->ips_ip_defend_interval) {
3979 				ire->ire_defense_count = defs = 0;
3980 			}
3981 			ire->ire_defense_count++;
3982 			ire->ire_defense_time = now;
3983 			mutex_exit(&ire->ire_lock);
3984 			ill_refhold(ill);
3985 			ire_refrele(ire);
3986 
3987 			/*
3988 			 * If we've defended ourselves too many times already,
3989 			 * then give up and tear down the interface(s) using
3990 			 * this address.  Otherwise, defend by sending out a
3991 			 * gratuitous ARP.
3992 			 */
3993 			if (defs >= maxdefense && ill->ill_arp_extend) {
3994 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
3995 				    B_FALSE);
3996 			} else {
3997 				cmn_err(CE_WARN,
3998 				    "node %s is using our IP address %s on %s",
3999 				    hbuf, sbuf, ill->ill_name);
4000 				/*
4001 				 * If this is an old (ATM) ARP module, then
4002 				 * don't try to defend the address.  Remain
4003 				 * compatible with the old behavior.  Defend
4004 				 * only with new ARP.
4005 				 */
4006 				if (ill->ill_arp_extend) {
4007 					qwriter_ip(ill, q, mp, ip_arp_defend,
4008 					    NEW_OP, B_FALSE);
4009 				} else {
4010 					ill_refrele(ill);
4011 				}
4012 			}
4013 			return;
4014 		}
4015 		cmn_err(CE_WARN,
4016 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4017 		    hbuf, sbuf, ill->ill_name);
4018 		if (ire != NULL)
4019 			ire_refrele(ire);
4020 		break;
4021 	case AR_CN_ANNOUNCE:
4022 		if (isv6) {
4023 			/*
4024 			 * For XRESOLV interfaces.
4025 			 * Delete the IRE cache entry and NCE for this
4026 			 * v6 address
4027 			 */
4028 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4029 			/*
4030 			 * If v6src is a non-zero, it's a router address
4031 			 * as below. Do the same sort of thing to clean
4032 			 * out off-net IRE_CACHE entries that go through
4033 			 * the router.
4034 			 */
4035 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4036 				ire_walk_v6(ire_delete_cache_gw_v6,
4037 				    (char *)&v6src, ALL_ZONES, ipst);
4038 			}
4039 		} else {
4040 			nce_hw_map_t hwm;
4041 
4042 			/*
4043 			 * ARP gives us a copy of any packet where it thinks
4044 			 * the address has changed, so that we can update our
4045 			 * caches.  We're responsible for caching known answers
4046 			 * in the current design.  We check whether the
4047 			 * hardware address really has changed in all of our
4048 			 * entries that have cached this mapping, and if so, we
4049 			 * blow them away.  This way we will immediately pick
4050 			 * up the rare case of a host changing hardware
4051 			 * address.
4052 			 */
4053 			if (src == 0)
4054 				break;
4055 			hwm.hwm_addr = src;
4056 			hwm.hwm_hwlen = arh->arh_hlen;
4057 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4058 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4059 			ndp_walk_common(ipst->ips_ndp4, NULL,
4060 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4061 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4062 		}
4063 		break;
4064 	case AR_CN_READY:
4065 		/* No external v6 resolver has a contract to use this */
4066 		if (isv6)
4067 			break;
4068 		/* If the link is down, we'll retry this later */
4069 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4070 			break;
4071 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4072 		    NULL, NULL, ipst);
4073 		if (ipif != NULL) {
4074 			/*
4075 			 * If this is a duplicate recovery, then we now need to
4076 			 * go exclusive to bring this thing back up.
4077 			 */
4078 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4079 			    IPIF_DUPLICATE) {
4080 				ipif_refrele(ipif);
4081 				ill_refhold(ill);
4082 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4083 				    B_FALSE);
4084 				return;
4085 			}
4086 			/*
4087 			 * If this is the first notice that this address is
4088 			 * ready, then let the user know now.
4089 			 */
4090 			if ((ipif->ipif_flags & IPIF_UP) &&
4091 			    !ipif->ipif_addr_ready) {
4092 				ipif_mask_reply(ipif);
4093 				ipif_up_notify(ipif);
4094 			}
4095 			ipif->ipif_addr_ready = 1;
4096 			ipif_refrele(ipif);
4097 		}
4098 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4099 		if (ire != NULL) {
4100 			ire->ire_defense_count = 0;
4101 			ire_refrele(ire);
4102 		}
4103 		break;
4104 	case AR_CN_FAILED:
4105 		/* No external v6 resolver has a contract to use this */
4106 		if (isv6)
4107 			break;
4108 		if (!ill->ill_arp_extend) {
4109 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4110 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4111 			(void) ip_dot_addr(src, sbuf);
4112 
4113 			cmn_err(CE_WARN,
4114 			    "node %s is using our IP address %s on %s",
4115 			    hbuf, sbuf, ill->ill_name);
4116 			break;
4117 		}
4118 		ill_refhold(ill);
4119 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4120 		return;
4121 	}
4122 	freemsg(mp);
4123 }
4124 
4125 /*
4126  * Create a mblk suitable for carrying the interface index and/or source link
4127  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4128  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4129  * application.
4130  */
4131 mblk_t *
4132 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4133     ip_stack_t *ipst)
4134 {
4135 	mblk_t		*mp;
4136 	ip_pktinfo_t	*pinfo;
4137 	ipha_t 		*ipha;
4138 	struct ether_header *pether;
4139 	boolean_t	ipmp_ill_held = B_FALSE;
4140 
4141 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4142 	if (mp == NULL) {
4143 		ip1dbg(("ip_add_info: allocation failure.\n"));
4144 		return (data_mp);
4145 	}
4146 
4147 	ipha = (ipha_t *)data_mp->b_rptr;
4148 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4149 	bzero(pinfo, sizeof (ip_pktinfo_t));
4150 	pinfo->ip_pkt_flags = (uchar_t)flags;
4151 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4152 
4153 	pether = (struct ether_header *)((char *)ipha
4154 	    - sizeof (struct ether_header));
4155 
4156 	/*
4157 	 * Make sure the interface is an ethernet type, since this option
4158 	 * is currently supported only on this type of interface. Also make
4159 	 * sure we are pointing correctly above db_base.
4160 	 */
4161 	if ((flags & IPF_RECVSLLA) &&
4162 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4163 	    (ill->ill_type == IFT_ETHER) &&
4164 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4165 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4166 		bcopy(pether->ether_shost.ether_addr_octet,
4167 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4168 	} else {
4169 		/*
4170 		 * Clear the bit. Indicate to upper layer that IP is not
4171 		 * sending this ancillary info.
4172 		 */
4173 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4174 	}
4175 
4176 	/*
4177 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4178 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4179 	 * IPF_RECVADDR support on test addresses is not needed.)
4180 	 *
4181 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4182 	 * processing a packet looped back to an IPMP data address
4183 	 * (since those IRE_LOCALs are tied to IPMP ills).
4184 	 */
4185 	if (IS_UNDER_IPMP(ill)) {
4186 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4187 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4188 			freemsg(mp);
4189 			return (data_mp);
4190 		}
4191 		ipmp_ill_held = B_TRUE;
4192 	}
4193 
4194 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4195 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4196 	if (flags & IPF_RECVADDR) {
4197 		ipif_t	*ipif;
4198 		ire_t	*ire;
4199 
4200 		/*
4201 		 * Only valid for V4
4202 		 */
4203 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4204 		    (IPV4_VERSION << 4));
4205 
4206 		ipif = ipif_get_next_ipif(NULL, ill);
4207 		if (ipif != NULL) {
4208 			/*
4209 			 * Since a decision has already been made to deliver the
4210 			 * packet, there is no need to test for SECATTR and
4211 			 * ZONEONLY.
4212 			 * When a multicast packet is transmitted
4213 			 * a cache entry is created for the multicast address.
4214 			 * When delivering a copy of the packet or when new
4215 			 * packets are received we do not want to match on the
4216 			 * cached entry so explicitly match on
4217 			 * IRE_LOCAL and IRE_LOOPBACK
4218 			 */
4219 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4220 			    IRE_LOCAL | IRE_LOOPBACK,
4221 			    ipif, zoneid, NULL,
4222 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4223 			if (ire == NULL) {
4224 				/*
4225 				 * packet must have come on a different
4226 				 * interface.
4227 				 * Since a decision has already been made to
4228 				 * deliver the packet, there is no need to test
4229 				 * for SECATTR and ZONEONLY.
4230 				 * Only match on local and broadcast ire's.
4231 				 * See detailed comment above.
4232 				 */
4233 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4234 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4235 				    NULL, MATCH_IRE_TYPE, ipst);
4236 			}
4237 
4238 			if (ire == NULL) {
4239 				/*
4240 				 * This is either a multicast packet or
4241 				 * the address has been removed since
4242 				 * the packet was received.
4243 				 * Return INADDR_ANY so that normal source
4244 				 * selection occurs for the response.
4245 				 */
4246 
4247 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4248 			} else {
4249 				pinfo->ip_pkt_match_addr.s_addr =
4250 				    ire->ire_src_addr;
4251 				ire_refrele(ire);
4252 			}
4253 			ipif_refrele(ipif);
4254 		} else {
4255 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4256 		}
4257 	}
4258 
4259 	if (ipmp_ill_held)
4260 		ill_refrele(ill);
4261 
4262 	mp->b_datap->db_type = M_CTL;
4263 	mp->b_wptr += sizeof (ip_pktinfo_t);
4264 	mp->b_cont = data_mp;
4265 
4266 	return (mp);
4267 }
4268 
4269 /*
4270  * Used to determine the most accurate cred_t to use for TX.
4271  * First priority is SCM_UCRED having set the label in the message,
4272  * which is used for MLP on UDP. Second priority is the open credentials
4273  * with the peer's label (aka conn_effective_cred), which is needed for
4274  * MLP on TCP/SCTP and for MAC-Exempt. Last priority is the open credentials.
4275  */
4276 cred_t *
4277 ip_best_cred(mblk_t *mp, conn_t *connp, pid_t *pidp)
4278 {
4279 	cred_t *cr;
4280 
4281 	cr = msg_getcred(mp, pidp);
4282 	if (cr != NULL && crgetlabel(cr) != NULL)
4283 		return (cr);
4284 	*pidp = NOPID;
4285 	return (CONN_CRED(connp));
4286 }
4287 
4288 /*
4289  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4290  * part of the bind request.
4291  */
4292 
4293 boolean_t
4294 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4295 {
4296 	ipsec_in_t *ii;
4297 
4298 	ASSERT(policy_mp != NULL);
4299 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4300 
4301 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4302 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4303 
4304 	connp->conn_policy = ii->ipsec_in_policy;
4305 	ii->ipsec_in_policy = NULL;
4306 
4307 	if (ii->ipsec_in_action != NULL) {
4308 		if (connp->conn_latch == NULL) {
4309 			connp->conn_latch = iplatch_create();
4310 			if (connp->conn_latch == NULL)
4311 				return (B_FALSE);
4312 		}
4313 		ipsec_latch_inbound(connp->conn_latch, ii);
4314 	}
4315 	return (B_TRUE);
4316 }
4317 
4318 /*
4319  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4320  * and to arrange for power-fanout assist.  The ULP is identified by
4321  * adding a single byte at the end of the original bind message.
4322  * A ULP other than UDP or TCP that wishes to be recognized passes
4323  * down a bind with a zero length address.
4324  *
4325  * The binding works as follows:
4326  * - A zero byte address means just bind to the protocol.
4327  * - A four byte address is treated as a request to validate
4328  *   that the address is a valid local address, appropriate for
4329  *   an application to bind to. This does not affect any fanout
4330  *   information in IP.
4331  * - A sizeof sin_t byte address is used to bind to only the local address
4332  *   and port.
4333  * - A sizeof ipa_conn_t byte address contains complete fanout information
4334  *   consisting of local and remote addresses and ports.  In
4335  *   this case, the addresses are both validated as appropriate
4336  *   for this operation, and, if so, the information is retained
4337  *   for use in the inbound fanout.
4338  *
4339  * The ULP (except in the zero-length bind) can append an
4340  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4341  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4342  * a copy of the source or destination IRE (source for local bind;
4343  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4344  * policy information contained should be copied on to the conn.
4345  *
4346  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4347  */
4348 mblk_t *
4349 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4350 {
4351 	ssize_t		len;
4352 	struct T_bind_req	*tbr;
4353 	sin_t		*sin;
4354 	ipa_conn_t	*ac;
4355 	uchar_t		*ucp;
4356 	int		error = 0;
4357 	int		protocol;
4358 	ipa_conn_x_t	*acx;
4359 	cred_t		*cr;
4360 
4361 	/*
4362 	 * All Solaris components should pass a db_credp
4363 	 * for this TPI message, hence we ASSERT.
4364 	 * But in case there is some other M_PROTO that looks
4365 	 * like a TPI message sent by some other kernel
4366 	 * component, we check and return an error.
4367 	 */
4368 	cr = msg_getcred(mp, NULL);
4369 	ASSERT(cr != NULL);
4370 	if (cr == NULL) {
4371 		error = EINVAL;
4372 		goto bad_addr;
4373 	}
4374 
4375 	ASSERT(!connp->conn_af_isv6);
4376 	connp->conn_pkt_isv6 = B_FALSE;
4377 
4378 	len = MBLKL(mp);
4379 	if (len < (sizeof (*tbr) + 1)) {
4380 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4381 		    "ip_bind: bogus msg, len %ld", len);
4382 		/* XXX: Need to return something better */
4383 		goto bad_addr;
4384 	}
4385 	/* Back up and extract the protocol identifier. */
4386 	mp->b_wptr--;
4387 	protocol = *mp->b_wptr & 0xFF;
4388 	tbr = (struct T_bind_req *)mp->b_rptr;
4389 	/* Reset the message type in preparation for shipping it back. */
4390 	DB_TYPE(mp) = M_PCPROTO;
4391 
4392 	connp->conn_ulp = (uint8_t)protocol;
4393 
4394 	/*
4395 	 * Check for a zero length address.  This is from a protocol that
4396 	 * wants to register to receive all packets of its type.
4397 	 */
4398 	if (tbr->ADDR_length == 0) {
4399 		/*
4400 		 * These protocols are now intercepted in ip_bind_v6().
4401 		 * Reject protocol-level binds here for now.
4402 		 *
4403 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4404 		 * so that the protocol type cannot be SCTP.
4405 		 */
4406 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4407 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4408 			goto bad_addr;
4409 		}
4410 
4411 		/*
4412 		 *
4413 		 * The udp module never sends down a zero-length address,
4414 		 * and allowing this on a labeled system will break MLP
4415 		 * functionality.
4416 		 */
4417 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4418 			goto bad_addr;
4419 
4420 		if (connp->conn_mac_mode != CONN_MAC_DEFAULT)
4421 			goto bad_addr;
4422 
4423 		/* No hash here really.  The table is big enough. */
4424 		connp->conn_srcv6 = ipv6_all_zeros;
4425 
4426 		ipcl_proto_insert(connp, protocol);
4427 
4428 		tbr->PRIM_type = T_BIND_ACK;
4429 		return (mp);
4430 	}
4431 
4432 	/* Extract the address pointer from the message. */
4433 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4434 	    tbr->ADDR_length);
4435 	if (ucp == NULL) {
4436 		ip1dbg(("ip_bind: no address\n"));
4437 		goto bad_addr;
4438 	}
4439 	if (!OK_32PTR(ucp)) {
4440 		ip1dbg(("ip_bind: unaligned address\n"));
4441 		goto bad_addr;
4442 	}
4443 
4444 	switch (tbr->ADDR_length) {
4445 	default:
4446 		ip1dbg(("ip_bind: bad address length %d\n",
4447 		    (int)tbr->ADDR_length));
4448 		goto bad_addr;
4449 
4450 	case IP_ADDR_LEN:
4451 		/* Verification of local address only */
4452 		error = ip_bind_laddr_v4(connp, &mp->b_cont, protocol,
4453 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4454 		break;
4455 
4456 	case sizeof (sin_t):
4457 		sin = (sin_t *)ucp;
4458 		error = ip_bind_laddr_v4(connp, &mp->b_cont, protocol,
4459 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4460 		break;
4461 
4462 	case sizeof (ipa_conn_t):
4463 		ac = (ipa_conn_t *)ucp;
4464 		/* For raw socket, the local port is not set. */
4465 		if (ac->ac_lport == 0)
4466 			ac->ac_lport = connp->conn_lport;
4467 		/* Always verify destination reachability. */
4468 		error = ip_bind_connected_v4(connp, &mp->b_cont, protocol,
4469 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4470 		    B_TRUE, B_TRUE, cr);
4471 		break;
4472 
4473 	case sizeof (ipa_conn_x_t):
4474 		acx = (ipa_conn_x_t *)ucp;
4475 		/*
4476 		 * Whether or not to verify destination reachability depends
4477 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4478 		 */
4479 		error = ip_bind_connected_v4(connp, &mp->b_cont, protocol,
4480 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4481 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4482 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4483 		break;
4484 	}
4485 	ASSERT(error != EINPROGRESS);
4486 	if (error != 0)
4487 		goto bad_addr;
4488 
4489 	/* Send it home. */
4490 	mp->b_datap->db_type = M_PCPROTO;
4491 	tbr->PRIM_type = T_BIND_ACK;
4492 	return (mp);
4493 
4494 bad_addr:
4495 	/*
4496 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4497 	 * a unix errno.
4498 	 */
4499 	if (error > 0)
4500 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4501 	else
4502 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4503 	return (mp);
4504 }
4505 
4506 /*
4507  * Here address is verified to be a valid local address.
4508  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4509  * address is also considered a valid local address.
4510  * In the case of a broadcast/multicast address, however, the
4511  * upper protocol is expected to reset the src address
4512  * to 0 if it sees a IRE_BROADCAST type returned so that
4513  * no packets are emitted with broadcast/multicast address as
4514  * source address (that violates hosts requirements RFC 1122)
4515  * The addresses valid for bind are:
4516  *	(1) - INADDR_ANY (0)
4517  *	(2) - IP address of an UP interface
4518  *	(3) - IP address of a DOWN interface
4519  *	(4) - valid local IP broadcast addresses. In this case
4520  *	the conn will only receive packets destined to
4521  *	the specified broadcast address.
4522  *	(5) - a multicast address. In this case
4523  *	the conn will only receive packets destined to
4524  *	the specified multicast address. Note: the
4525  *	application still has to issue an
4526  *	IP_ADD_MEMBERSHIP socket option.
4527  *
4528  * On error, return -1 for TBADADDR otherwise pass the
4529  * errno with TSYSERR reply.
4530  *
4531  * In all the above cases, the bound address must be valid in the current zone.
4532  * When the address is loopback, multicast or broadcast, there might be many
4533  * matching IREs so bind has to look up based on the zone.
4534  *
4535  * Note: lport is in network byte order.
4536  *
4537  */
4538 int
4539 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4540     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4541 {
4542 	int		error = 0;
4543 	ire_t		*src_ire;
4544 	zoneid_t	zoneid;
4545 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4546 	mblk_t		*mp = NULL;
4547 	boolean_t	ire_requested = B_FALSE;
4548 	boolean_t	ipsec_policy_set = B_FALSE;
4549 
4550 	if (mpp)
4551 		mp = *mpp;
4552 
4553 	if (mp != NULL) {
4554 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4555 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4556 	}
4557 
4558 	/*
4559 	 * If it was previously connected, conn_fully_bound would have
4560 	 * been set.
4561 	 */
4562 	connp->conn_fully_bound = B_FALSE;
4563 
4564 	src_ire = NULL;
4565 
4566 	zoneid = IPCL_ZONEID(connp);
4567 
4568 	if (src_addr) {
4569 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4570 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4571 		/*
4572 		 * If an address other than 0.0.0.0 is requested,
4573 		 * we verify that it is a valid address for bind
4574 		 * Note: Following code is in if-else-if form for
4575 		 * readability compared to a condition check.
4576 		 */
4577 		/* LINTED - statement has no consequence */
4578 		if (IRE_IS_LOCAL(src_ire)) {
4579 			/*
4580 			 * (2) Bind to address of local UP interface
4581 			 */
4582 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4583 			/*
4584 			 * (4) Bind to broadcast address
4585 			 * Note: permitted only from transports that
4586 			 * request IRE
4587 			 */
4588 			if (!ire_requested)
4589 				error = EADDRNOTAVAIL;
4590 		} else {
4591 			/*
4592 			 * (3) Bind to address of local DOWN interface
4593 			 * (ipif_lookup_addr() looks up all interfaces
4594 			 * but we do not get here for UP interfaces
4595 			 * - case (2) above)
4596 			 */
4597 			/* LINTED - statement has no consequent */
4598 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4599 				/* The address exists */
4600 			} else if (CLASSD(src_addr)) {
4601 				error = 0;
4602 				if (src_ire != NULL)
4603 					ire_refrele(src_ire);
4604 				/*
4605 				 * (5) bind to multicast address.
4606 				 * Fake out the IRE returned to upper
4607 				 * layer to be a broadcast IRE.
4608 				 */
4609 				src_ire = ire_ctable_lookup(
4610 				    INADDR_BROADCAST, INADDR_ANY,
4611 				    IRE_BROADCAST, NULL, zoneid, NULL,
4612 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4613 				    ipst);
4614 				if (src_ire == NULL || !ire_requested)
4615 					error = EADDRNOTAVAIL;
4616 			} else {
4617 				/*
4618 				 * Not a valid address for bind
4619 				 */
4620 				error = EADDRNOTAVAIL;
4621 			}
4622 		}
4623 		if (error) {
4624 			/* Red Alert!  Attempting to be a bogon! */
4625 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4626 			    ntohl(src_addr)));
4627 			goto bad_addr;
4628 		}
4629 	}
4630 
4631 	/*
4632 	 * Allow setting new policies. For example, disconnects come
4633 	 * down as ipa_t bind. As we would have set conn_policy_cached
4634 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4635 	 * can change after the disconnect.
4636 	 */
4637 	connp->conn_policy_cached = B_FALSE;
4638 
4639 	/*
4640 	 * If not fanout_insert this was just an address verification
4641 	 */
4642 	if (fanout_insert) {
4643 		/*
4644 		 * The addresses have been verified. Time to insert in
4645 		 * the correct fanout list.
4646 		 */
4647 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4648 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4649 		connp->conn_lport = lport;
4650 		connp->conn_fport = 0;
4651 		/*
4652 		 * Do we need to add a check to reject Multicast packets
4653 		 */
4654 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4655 	}
4656 
4657 	if (error == 0) {
4658 		if (ire_requested) {
4659 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4660 				error = -1;
4661 				/* Falls through to bad_addr */
4662 			}
4663 		} else if (ipsec_policy_set) {
4664 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4665 				error = -1;
4666 				/* Falls through to bad_addr */
4667 			}
4668 		}
4669 	}
4670 bad_addr:
4671 	if (error != 0) {
4672 		if (connp->conn_anon_port) {
4673 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4674 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4675 			    B_FALSE);
4676 		}
4677 		connp->conn_mlp_type = mlptSingle;
4678 	}
4679 	if (src_ire != NULL)
4680 		IRE_REFRELE(src_ire);
4681 	return (error);
4682 }
4683 
4684 int
4685 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4686     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4687 {
4688 	int error;
4689 
4690 	ASSERT(!connp->conn_af_isv6);
4691 	connp->conn_pkt_isv6 = B_FALSE;
4692 	connp->conn_ulp = protocol;
4693 
4694 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4695 	    fanout_insert);
4696 	if (error < 0)
4697 		error = -TBADADDR;
4698 	return (error);
4699 }
4700 
4701 /*
4702  * Verify that both the source and destination addresses
4703  * are valid.  If verify_dst is false, then the destination address may be
4704  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4705  * destination reachability, while tunnels do not.
4706  * Note that we allow connect to broadcast and multicast
4707  * addresses when ire_requested is set. Thus the ULP
4708  * has to check for IRE_BROADCAST and multicast.
4709  *
4710  * Returns zero if ok.
4711  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4712  * (for use with TSYSERR reply).
4713  *
4714  * Note: lport and fport are in network byte order.
4715  */
4716 int
4717 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4718     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4719     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4720 {
4721 
4722 	ire_t		*src_ire;
4723 	ire_t		*dst_ire;
4724 	int		error = 0;
4725 	ire_t		*sire = NULL;
4726 	ire_t		*md_dst_ire = NULL;
4727 	ire_t		*lso_dst_ire = NULL;
4728 	ill_t		*ill = NULL;
4729 	zoneid_t	zoneid;
4730 	ipaddr_t	src_addr = *src_addrp;
4731 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4732 	mblk_t		*mp = NULL;
4733 	boolean_t	ire_requested = B_FALSE;
4734 	boolean_t	ipsec_policy_set = B_FALSE;
4735 	ts_label_t	*tsl = NULL;
4736 	cred_t		*effective_cred = NULL;
4737 
4738 	if (mpp)
4739 		mp = *mpp;
4740 
4741 	if (mp != NULL) {
4742 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4743 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4744 	}
4745 
4746 	src_ire = dst_ire = NULL;
4747 
4748 	/*
4749 	 * If we never got a disconnect before, clear it now.
4750 	 */
4751 	connp->conn_fully_bound = B_FALSE;
4752 
4753 	zoneid = IPCL_ZONEID(connp);
4754 
4755 	/*
4756 	 * Check whether Trusted Solaris policy allows communication with this
4757 	 * host, and pretend that the destination is unreachable if not.
4758 	 *
4759 	 * This is never a problem for TCP, since that transport is known to
4760 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4761 	 * handling.  If the remote is unreachable, it will be detected at that
4762 	 * point, so there's no reason to check it here.
4763 	 *
4764 	 * Note that for sendto (and other datagram-oriented friends), this
4765 	 * check is done as part of the data path label computation instead.
4766 	 * The check here is just to make non-TCP connect() report the right
4767 	 * error.
4768 	 */
4769 	if (is_system_labeled() && !IPCL_IS_TCP(connp)) {
4770 		if ((error = tsol_check_dest(cr, &dst_addr, IPV4_VERSION,
4771 		    connp->conn_mac_mode, &effective_cred)) != 0) {
4772 			if (ip_debug > 2) {
4773 				pr_addr_dbg(
4774 				    "ip_bind_connected_v4:"
4775 				    " no label for dst %s\n",
4776 				    AF_INET, &dst_addr);
4777 			}
4778 			goto bad_addr;
4779 		}
4780 
4781 		/*
4782 		 * tsol_check_dest() may have created a new cred with
4783 		 * a modified security label. Use that cred if it exists
4784 		 * for ire lookups.
4785 		 */
4786 		if (effective_cred == NULL) {
4787 			tsl = crgetlabel(cr);
4788 		} else {
4789 			tsl = crgetlabel(effective_cred);
4790 		}
4791 	}
4792 
4793 	if (CLASSD(dst_addr)) {
4794 		/* Pick up an IRE_BROADCAST */
4795 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4796 		    NULL, zoneid, tsl,
4797 		    (MATCH_IRE_RECURSIVE |
4798 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4799 		    MATCH_IRE_SECATTR), ipst);
4800 	} else {
4801 		/*
4802 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4803 		 * and onlink ipif is not found set ENETUNREACH error.
4804 		 */
4805 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4806 			ipif_t *ipif;
4807 
4808 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4809 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4810 			if (ipif == NULL) {
4811 				error = ENETUNREACH;
4812 				goto bad_addr;
4813 			}
4814 			ipif_refrele(ipif);
4815 		}
4816 
4817 		if (connp->conn_nexthop_set) {
4818 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4819 			    0, 0, NULL, NULL, zoneid, tsl,
4820 			    MATCH_IRE_SECATTR, ipst);
4821 		} else {
4822 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4823 			    &sire, zoneid, tsl,
4824 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4825 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4826 			    MATCH_IRE_SECATTR), ipst);
4827 		}
4828 	}
4829 	/*
4830 	 * dst_ire can't be a broadcast when not ire_requested.
4831 	 * We also prevent ire's with src address INADDR_ANY to
4832 	 * be used, which are created temporarily for
4833 	 * sending out packets from endpoints that have
4834 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4835 	 * reachable.  If verify_dst is false, the destination needn't be
4836 	 * reachable.
4837 	 *
4838 	 * If we match on a reject or black hole, then we've got a
4839 	 * local failure.  May as well fail out the connect() attempt,
4840 	 * since it's never going to succeed.
4841 	 */
4842 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4843 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4844 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4845 		/*
4846 		 * If we're verifying destination reachability, we always want
4847 		 * to complain here.
4848 		 *
4849 		 * If we're not verifying destination reachability but the
4850 		 * destination has a route, we still want to fail on the
4851 		 * temporary address and broadcast address tests.
4852 		 */
4853 		if (verify_dst || (dst_ire != NULL)) {
4854 			if (ip_debug > 2) {
4855 				pr_addr_dbg("ip_bind_connected_v4:"
4856 				    "bad connected dst %s\n",
4857 				    AF_INET, &dst_addr);
4858 			}
4859 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4860 				error = ENETUNREACH;
4861 			else
4862 				error = EHOSTUNREACH;
4863 			goto bad_addr;
4864 		}
4865 	}
4866 
4867 	/*
4868 	 * If the app does a connect(), it means that it will most likely
4869 	 * send more than 1 packet to the destination.  It makes sense
4870 	 * to clear the temporary flag.
4871 	 */
4872 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4873 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4874 		irb_t *irb = dst_ire->ire_bucket;
4875 
4876 		rw_enter(&irb->irb_lock, RW_WRITER);
4877 		/*
4878 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4879 		 * the lock to guarantee irb_tmp_ire_cnt.
4880 		 */
4881 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4882 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4883 			irb->irb_tmp_ire_cnt--;
4884 		}
4885 		rw_exit(&irb->irb_lock);
4886 	}
4887 
4888 	/*
4889 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4890 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4891 	 * eligibility tests for passive connects are handled separately
4892 	 * through tcp_adapt_ire().  We do this before the source address
4893 	 * selection, because dst_ire may change after a call to
4894 	 * ipif_select_source().  This is a best-effort check, as the
4895 	 * packet for this connection may not actually go through
4896 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4897 	 * calling ip_newroute().  This is why we further check on the
4898 	 * IRE during LSO/Multidata packet transmission in
4899 	 * tcp_lsosend()/tcp_multisend().
4900 	 */
4901 	if (!ipsec_policy_set && dst_ire != NULL &&
4902 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4903 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4904 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4905 			lso_dst_ire = dst_ire;
4906 			IRE_REFHOLD(lso_dst_ire);
4907 		} else if (ipst->ips_ip_multidata_outbound &&
4908 		    ILL_MDT_CAPABLE(ill)) {
4909 			md_dst_ire = dst_ire;
4910 			IRE_REFHOLD(md_dst_ire);
4911 		}
4912 	}
4913 
4914 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4915 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4916 		/*
4917 		 * If the IRE belongs to a different zone, look for a matching
4918 		 * route in the forwarding table and use the source address from
4919 		 * that route.
4920 		 */
4921 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4922 		    zoneid, 0, NULL,
4923 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4924 		    MATCH_IRE_RJ_BHOLE, ipst);
4925 		if (src_ire == NULL) {
4926 			error = EHOSTUNREACH;
4927 			goto bad_addr;
4928 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4929 			if (!(src_ire->ire_type & IRE_HOST))
4930 				error = ENETUNREACH;
4931 			else
4932 				error = EHOSTUNREACH;
4933 			goto bad_addr;
4934 		}
4935 		if (src_addr == INADDR_ANY)
4936 			src_addr = src_ire->ire_src_addr;
4937 		ire_refrele(src_ire);
4938 		src_ire = NULL;
4939 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4940 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4941 			src_addr = sire->ire_src_addr;
4942 			ire_refrele(dst_ire);
4943 			dst_ire = sire;
4944 			sire = NULL;
4945 		} else {
4946 			/*
4947 			 * Pick a source address so that a proper inbound
4948 			 * load spreading would happen.
4949 			 */
4950 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
4951 			ipif_t *src_ipif = NULL;
4952 			ire_t *ipif_ire;
4953 
4954 			/*
4955 			 * Supply a local source address such that inbound
4956 			 * load spreading happens.
4957 			 *
4958 			 * Determine the best source address on this ill for
4959 			 * the destination.
4960 			 *
4961 			 * 1) For broadcast, we should return a broadcast ire
4962 			 *    found above so that upper layers know that the
4963 			 *    destination address is a broadcast address.
4964 			 *
4965 			 * 2) If the ipif is DEPRECATED, select a better
4966 			 *    source address.  Similarly, if the ipif is on
4967 			 *    the IPMP meta-interface, pick a source address
4968 			 *    at random to improve inbound load spreading.
4969 			 *
4970 			 * 3) If the outgoing interface is part of a usesrc
4971 			 *    group, then try selecting a source address from
4972 			 *    the usesrc ILL.
4973 			 */
4974 			if ((dst_ire->ire_zoneid != zoneid &&
4975 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4976 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4977 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4978 			    (IS_IPMP(ire_ill) ||
4979 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4980 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
4981 				/*
4982 				 * If the destination is reachable via a
4983 				 * given gateway, the selected source address
4984 				 * should be in the same subnet as the gateway.
4985 				 * Otherwise, the destination is not reachable.
4986 				 *
4987 				 * If there are no interfaces on the same subnet
4988 				 * as the destination, ipif_select_source gives
4989 				 * first non-deprecated interface which might be
4990 				 * on a different subnet than the gateway.
4991 				 * This is not desirable. Hence pass the dst_ire
4992 				 * source address to ipif_select_source.
4993 				 * It is sure that the destination is reachable
4994 				 * with the dst_ire source address subnet.
4995 				 * So passing dst_ire source address to
4996 				 * ipif_select_source will make sure that the
4997 				 * selected source will be on the same subnet
4998 				 * as dst_ire source address.
4999 				 */
5000 				ipaddr_t saddr =
5001 				    dst_ire->ire_ipif->ipif_src_addr;
5002 				src_ipif = ipif_select_source(ire_ill,
5003 				    saddr, zoneid);
5004 				if (src_ipif != NULL) {
5005 					if (IS_VNI(src_ipif->ipif_ill)) {
5006 						/*
5007 						 * For VNI there is no
5008 						 * interface route
5009 						 */
5010 						src_addr =
5011 						    src_ipif->ipif_src_addr;
5012 					} else {
5013 						ipif_ire =
5014 						    ipif_to_ire(src_ipif);
5015 						if (ipif_ire != NULL) {
5016 							IRE_REFRELE(dst_ire);
5017 							dst_ire = ipif_ire;
5018 						}
5019 						src_addr =
5020 						    dst_ire->ire_src_addr;
5021 					}
5022 					ipif_refrele(src_ipif);
5023 				} else {
5024 					src_addr = dst_ire->ire_src_addr;
5025 				}
5026 			} else {
5027 				src_addr = dst_ire->ire_src_addr;
5028 			}
5029 		}
5030 	}
5031 
5032 	/*
5033 	 * We do ire_route_lookup() here (and not
5034 	 * interface lookup as we assert that
5035 	 * src_addr should only come from an
5036 	 * UP interface for hard binding.
5037 	 */
5038 	ASSERT(src_ire == NULL);
5039 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5040 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5041 	/* src_ire must be a local|loopback */
5042 	if (!IRE_IS_LOCAL(src_ire)) {
5043 		if (ip_debug > 2) {
5044 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5045 			    "src %s\n", AF_INET, &src_addr);
5046 		}
5047 		error = EADDRNOTAVAIL;
5048 		goto bad_addr;
5049 	}
5050 
5051 	/*
5052 	 * If the source address is a loopback address, the
5053 	 * destination had best be local or multicast.
5054 	 * The transports that can't handle multicast will reject
5055 	 * those addresses.
5056 	 */
5057 	if (src_ire->ire_type == IRE_LOOPBACK &&
5058 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5059 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5060 		error = -1;
5061 		goto bad_addr;
5062 	}
5063 
5064 	/*
5065 	 * Allow setting new policies. For example, disconnects come
5066 	 * down as ipa_t bind. As we would have set conn_policy_cached
5067 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5068 	 * can change after the disconnect.
5069 	 */
5070 	connp->conn_policy_cached = B_FALSE;
5071 
5072 	/*
5073 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5074 	 * can handle their passed-in conn's.
5075 	 */
5076 
5077 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5078 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5079 	connp->conn_lport = lport;
5080 	connp->conn_fport = fport;
5081 	*src_addrp = src_addr;
5082 
5083 	ASSERT(!(ipsec_policy_set && ire_requested));
5084 	if (ire_requested) {
5085 		iulp_t *ulp_info = NULL;
5086 
5087 		/*
5088 		 * Note that sire will not be NULL if this is an off-link
5089 		 * connection and there is not cache for that dest yet.
5090 		 *
5091 		 * XXX Because of an existing bug, if there are multiple
5092 		 * default routes, the IRE returned now may not be the actual
5093 		 * default route used (default routes are chosen in a
5094 		 * round robin fashion).  So if the metrics for different
5095 		 * default routes are different, we may return the wrong
5096 		 * metrics.  This will not be a problem if the existing
5097 		 * bug is fixed.
5098 		 */
5099 		if (sire != NULL) {
5100 			ulp_info = &(sire->ire_uinfo);
5101 		}
5102 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5103 			error = -1;
5104 			goto bad_addr;
5105 		}
5106 		mp = *mpp;
5107 	} else if (ipsec_policy_set) {
5108 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5109 			error = -1;
5110 			goto bad_addr;
5111 		}
5112 	}
5113 
5114 	/*
5115 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5116 	 * we'll cache that.  If we don't, we'll inherit global policy.
5117 	 *
5118 	 * We can't insert until the conn reflects the policy. Note that
5119 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5120 	 * connections where we don't have a policy. This is to prevent
5121 	 * global policy lookups in the inbound path.
5122 	 *
5123 	 * If we insert before we set conn_policy_cached,
5124 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5125 	 * because global policy cound be non-empty. We normally call
5126 	 * ipsec_check_policy() for conn_policy_cached connections only if
5127 	 * ipc_in_enforce_policy is set. But in this case,
5128 	 * conn_policy_cached can get set anytime since we made the
5129 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5130 	 * called, which will make the above assumption false.  Thus, we
5131 	 * need to insert after we set conn_policy_cached.
5132 	 */
5133 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5134 		goto bad_addr;
5135 
5136 	if (fanout_insert) {
5137 		/*
5138 		 * The addresses have been verified. Time to insert in
5139 		 * the correct fanout list.
5140 		 */
5141 		error = ipcl_conn_insert(connp, protocol, src_addr,
5142 		    dst_addr, connp->conn_ports);
5143 	}
5144 
5145 	if (error == 0) {
5146 		connp->conn_fully_bound = B_TRUE;
5147 		/*
5148 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5149 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5150 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5151 		 * ip_xxinfo_return(), which performs further checks
5152 		 * against them and upon success, returns the LSO/MDT info
5153 		 * mblk which we will attach to the bind acknowledgment.
5154 		 */
5155 		if (lso_dst_ire != NULL) {
5156 			mblk_t *lsoinfo_mp;
5157 
5158 			ASSERT(ill->ill_lso_capab != NULL);
5159 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5160 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5161 				if (mp == NULL) {
5162 					*mpp = lsoinfo_mp;
5163 				} else {
5164 					linkb(mp, lsoinfo_mp);
5165 				}
5166 			}
5167 		} else if (md_dst_ire != NULL) {
5168 			mblk_t *mdinfo_mp;
5169 
5170 			ASSERT(ill->ill_mdt_capab != NULL);
5171 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5172 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5173 				if (mp == NULL) {
5174 					*mpp = mdinfo_mp;
5175 				} else {
5176 					linkb(mp, mdinfo_mp);
5177 				}
5178 			}
5179 		}
5180 	}
5181 bad_addr:
5182 	if (ipsec_policy_set) {
5183 		ASSERT(mp != NULL);
5184 		freeb(mp);
5185 		/*
5186 		 * As of now assume that nothing else accompanies
5187 		 * IPSEC_POLICY_SET.
5188 		 */
5189 		*mpp = NULL;
5190 	}
5191 	if (src_ire != NULL)
5192 		IRE_REFRELE(src_ire);
5193 	if (dst_ire != NULL)
5194 		IRE_REFRELE(dst_ire);
5195 	if (sire != NULL)
5196 		IRE_REFRELE(sire);
5197 	if (md_dst_ire != NULL)
5198 		IRE_REFRELE(md_dst_ire);
5199 	if (lso_dst_ire != NULL)
5200 		IRE_REFRELE(lso_dst_ire);
5201 	if (effective_cred != NULL)
5202 		crfree(effective_cred);
5203 	return (error);
5204 }
5205 
5206 int
5207 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5208     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5209     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5210 {
5211 	int error;
5212 
5213 	ASSERT(!connp->conn_af_isv6);
5214 	connp->conn_pkt_isv6 = B_FALSE;
5215 	connp->conn_ulp = protocol;
5216 
5217 	/* For raw socket, the local port is not set. */
5218 	if (lport == 0)
5219 		lport = connp->conn_lport;
5220 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5221 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5222 	if (error < 0)
5223 		error = -TBADADDR;
5224 	return (error);
5225 }
5226 
5227 /*
5228  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5229  * Prefers dst_ire over src_ire.
5230  */
5231 static boolean_t
5232 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5233 {
5234 	mblk_t	*mp = *mpp;
5235 	ire_t	*ret_ire;
5236 
5237 	ASSERT(mp != NULL);
5238 
5239 	if (ire != NULL) {
5240 		/*
5241 		 * mp initialized above to IRE_DB_REQ_TYPE
5242 		 * appended mblk. Its <upper protocol>'s
5243 		 * job to make sure there is room.
5244 		 */
5245 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5246 			return (B_FALSE);
5247 
5248 		mp->b_datap->db_type = IRE_DB_TYPE;
5249 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5250 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5251 		ret_ire = (ire_t *)mp->b_rptr;
5252 		/*
5253 		 * Pass the latest setting of the ip_path_mtu_discovery and
5254 		 * copy the ulp info if any.
5255 		 */
5256 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5257 		    IPH_DF : 0;
5258 		if (ulp_info != NULL) {
5259 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5260 			    sizeof (iulp_t));
5261 		}
5262 		ret_ire->ire_mp = mp;
5263 	} else {
5264 		/*
5265 		 * No IRE was found. Remove IRE mblk.
5266 		 */
5267 		*mpp = mp->b_cont;
5268 		freeb(mp);
5269 	}
5270 	return (B_TRUE);
5271 }
5272 
5273 /*
5274  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5275  * the final piece where we don't.  Return a pointer to the first mblk in the
5276  * result, and update the pointer to the next mblk to chew on.  If anything
5277  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5278  * NULL pointer.
5279  */
5280 mblk_t *
5281 ip_carve_mp(mblk_t **mpp, ssize_t len)
5282 {
5283 	mblk_t	*mp0;
5284 	mblk_t	*mp1;
5285 	mblk_t	*mp2;
5286 
5287 	if (!len || !mpp || !(mp0 = *mpp))
5288 		return (NULL);
5289 	/* If we aren't going to consume the first mblk, we need a dup. */
5290 	if (mp0->b_wptr - mp0->b_rptr > len) {
5291 		mp1 = dupb(mp0);
5292 		if (mp1) {
5293 			/* Partition the data between the two mblks. */
5294 			mp1->b_wptr = mp1->b_rptr + len;
5295 			mp0->b_rptr = mp1->b_wptr;
5296 			/*
5297 			 * after adjustments if mblk not consumed is now
5298 			 * unaligned, try to align it. If this fails free
5299 			 * all messages and let upper layer recover.
5300 			 */
5301 			if (!OK_32PTR(mp0->b_rptr)) {
5302 				if (!pullupmsg(mp0, -1)) {
5303 					freemsg(mp0);
5304 					freemsg(mp1);
5305 					*mpp = NULL;
5306 					return (NULL);
5307 				}
5308 			}
5309 		}
5310 		return (mp1);
5311 	}
5312 	/* Eat through as many mblks as we need to get len bytes. */
5313 	len -= mp0->b_wptr - mp0->b_rptr;
5314 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5315 		if (mp2->b_wptr - mp2->b_rptr > len) {
5316 			/*
5317 			 * We won't consume the entire last mblk.  Like
5318 			 * above, dup and partition it.
5319 			 */
5320 			mp1->b_cont = dupb(mp2);
5321 			mp1 = mp1->b_cont;
5322 			if (!mp1) {
5323 				/*
5324 				 * Trouble.  Rather than go to a lot of
5325 				 * trouble to clean up, we free the messages.
5326 				 * This won't be any worse than losing it on
5327 				 * the wire.
5328 				 */
5329 				freemsg(mp0);
5330 				freemsg(mp2);
5331 				*mpp = NULL;
5332 				return (NULL);
5333 			}
5334 			mp1->b_wptr = mp1->b_rptr + len;
5335 			mp2->b_rptr = mp1->b_wptr;
5336 			/*
5337 			 * after adjustments if mblk not consumed is now
5338 			 * unaligned, try to align it. If this fails free
5339 			 * all messages and let upper layer recover.
5340 			 */
5341 			if (!OK_32PTR(mp2->b_rptr)) {
5342 				if (!pullupmsg(mp2, -1)) {
5343 					freemsg(mp0);
5344 					freemsg(mp2);
5345 					*mpp = NULL;
5346 					return (NULL);
5347 				}
5348 			}
5349 			*mpp = mp2;
5350 			return (mp0);
5351 		}
5352 		/* Decrement len by the amount we just got. */
5353 		len -= mp2->b_wptr - mp2->b_rptr;
5354 	}
5355 	/*
5356 	 * len should be reduced to zero now.  If not our caller has
5357 	 * screwed up.
5358 	 */
5359 	if (len) {
5360 		/* Shouldn't happen! */
5361 		freemsg(mp0);
5362 		*mpp = NULL;
5363 		return (NULL);
5364 	}
5365 	/*
5366 	 * We consumed up to exactly the end of an mblk.  Detach the part
5367 	 * we are returning from the rest of the chain.
5368 	 */
5369 	mp1->b_cont = NULL;
5370 	*mpp = mp2;
5371 	return (mp0);
5372 }
5373 
5374 /* The ill stream is being unplumbed. Called from ip_close */
5375 int
5376 ip_modclose(ill_t *ill)
5377 {
5378 	boolean_t success;
5379 	ipsq_t	*ipsq;
5380 	ipif_t	*ipif;
5381 	queue_t	*q = ill->ill_rq;
5382 	ip_stack_t	*ipst = ill->ill_ipst;
5383 	int	i;
5384 
5385 	/*
5386 	 * The punlink prior to this may have initiated a capability
5387 	 * negotiation. But ipsq_enter will block until that finishes or
5388 	 * times out.
5389 	 */
5390 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5391 
5392 	/*
5393 	 * Open/close/push/pop is guaranteed to be single threaded
5394 	 * per stream by STREAMS. FS guarantees that all references
5395 	 * from top are gone before close is called. So there can't
5396 	 * be another close thread that has set CONDEMNED on this ill.
5397 	 * and cause ipsq_enter to return failure.
5398 	 */
5399 	ASSERT(success);
5400 	ipsq = ill->ill_phyint->phyint_ipsq;
5401 
5402 	/*
5403 	 * Mark it condemned. No new reference will be made to this ill.
5404 	 * Lookup functions will return an error. Threads that try to
5405 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5406 	 * that the refcnt will drop down to zero.
5407 	 */
5408 	mutex_enter(&ill->ill_lock);
5409 	ill->ill_state_flags |= ILL_CONDEMNED;
5410 	for (ipif = ill->ill_ipif; ipif != NULL;
5411 	    ipif = ipif->ipif_next) {
5412 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5413 	}
5414 	/*
5415 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5416 	 * returns  error if ILL_CONDEMNED is set
5417 	 */
5418 	cv_broadcast(&ill->ill_cv);
5419 	mutex_exit(&ill->ill_lock);
5420 
5421 	/*
5422 	 * Send all the deferred DLPI messages downstream which came in
5423 	 * during the small window right before ipsq_enter(). We do this
5424 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5425 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5426 	 */
5427 	ill_dlpi_send_deferred(ill);
5428 
5429 	/*
5430 	 * Shut down fragmentation reassembly.
5431 	 * ill_frag_timer won't start a timer again.
5432 	 * Now cancel any existing timer
5433 	 */
5434 	(void) untimeout(ill->ill_frag_timer_id);
5435 	(void) ill_frag_timeout(ill, 0);
5436 
5437 	/*
5438 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5439 	 * this ill. Then wait for the refcnts to drop to zero.
5440 	 * ill_is_freeable checks whether the ill is really quiescent.
5441 	 * Then make sure that threads that are waiting to enter the
5442 	 * ipsq have seen the error returned by ipsq_enter and have
5443 	 * gone away. Then we call ill_delete_tail which does the
5444 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5445 	 */
5446 	ill_delete(ill);
5447 	mutex_enter(&ill->ill_lock);
5448 	while (!ill_is_freeable(ill))
5449 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5450 	while (ill->ill_waiters)
5451 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5452 
5453 	mutex_exit(&ill->ill_lock);
5454 
5455 	/*
5456 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5457 	 * it held until the end of the function since the cleanup
5458 	 * below needs to be able to use the ip_stack_t.
5459 	 */
5460 	netstack_hold(ipst->ips_netstack);
5461 
5462 	/* qprocsoff is done via ill_delete_tail */
5463 	ill_delete_tail(ill);
5464 	ASSERT(ill->ill_ipst == NULL);
5465 
5466 	/*
5467 	 * Walk through all upper (conn) streams and qenable
5468 	 * those that have queued data.
5469 	 * close synchronization needs this to
5470 	 * be done to ensure that all upper layers blocked
5471 	 * due to flow control to the closing device
5472 	 * get unblocked.
5473 	 */
5474 	ip1dbg(("ip_wsrv: walking\n"));
5475 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5476 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5477 	}
5478 
5479 	mutex_enter(&ipst->ips_ip_mi_lock);
5480 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5481 	mutex_exit(&ipst->ips_ip_mi_lock);
5482 
5483 	/*
5484 	 * credp could be null if the open didn't succeed and ip_modopen
5485 	 * itself calls ip_close.
5486 	 */
5487 	if (ill->ill_credp != NULL)
5488 		crfree(ill->ill_credp);
5489 
5490 	/*
5491 	 * Now we are done with the module close pieces that
5492 	 * need the netstack_t.
5493 	 */
5494 	netstack_rele(ipst->ips_netstack);
5495 
5496 	mi_close_free((IDP)ill);
5497 	q->q_ptr = WR(q)->q_ptr = NULL;
5498 
5499 	ipsq_exit(ipsq);
5500 
5501 	return (0);
5502 }
5503 
5504 /*
5505  * This is called as part of close() for IP, UDP, ICMP, and RTS
5506  * in order to quiesce the conn.
5507  */
5508 void
5509 ip_quiesce_conn(conn_t *connp)
5510 {
5511 	boolean_t	drain_cleanup_reqd = B_FALSE;
5512 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5513 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5514 	ip_stack_t	*ipst;
5515 
5516 	ASSERT(!IPCL_IS_TCP(connp));
5517 	ipst = connp->conn_netstack->netstack_ip;
5518 
5519 	/*
5520 	 * Mark the conn as closing, and this conn must not be
5521 	 * inserted in future into any list. Eg. conn_drain_insert(),
5522 	 * won't insert this conn into the conn_drain_list.
5523 	 * Similarly ill_pending_mp_add() will not add any mp to
5524 	 * the pending mp list, after this conn has started closing.
5525 	 *
5526 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5527 	 * cannot get set henceforth.
5528 	 */
5529 	mutex_enter(&connp->conn_lock);
5530 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5531 	connp->conn_state_flags |= CONN_CLOSING;
5532 	if (connp->conn_idl != NULL)
5533 		drain_cleanup_reqd = B_TRUE;
5534 	if (connp->conn_oper_pending_ill != NULL)
5535 		conn_ioctl_cleanup_reqd = B_TRUE;
5536 	if (connp->conn_dhcpinit_ill != NULL) {
5537 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5538 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5539 		connp->conn_dhcpinit_ill = NULL;
5540 	}
5541 	if (connp->conn_ilg_inuse != 0)
5542 		ilg_cleanup_reqd = B_TRUE;
5543 	mutex_exit(&connp->conn_lock);
5544 
5545 	if (conn_ioctl_cleanup_reqd)
5546 		conn_ioctl_cleanup(connp);
5547 
5548 	if (is_system_labeled() && connp->conn_anon_port) {
5549 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5550 		    connp->conn_mlp_type, connp->conn_ulp,
5551 		    ntohs(connp->conn_lport), B_FALSE);
5552 		connp->conn_anon_port = 0;
5553 	}
5554 	connp->conn_mlp_type = mlptSingle;
5555 
5556 	/*
5557 	 * Remove this conn from any fanout list it is on.
5558 	 * and then wait for any threads currently operating
5559 	 * on this endpoint to finish
5560 	 */
5561 	ipcl_hash_remove(connp);
5562 
5563 	/*
5564 	 * Remove this conn from the drain list, and do
5565 	 * any other cleanup that may be required.
5566 	 * (Only non-tcp streams may have a non-null conn_idl.
5567 	 * TCP streams are never flow controlled, and
5568 	 * conn_idl will be null)
5569 	 */
5570 	if (drain_cleanup_reqd)
5571 		conn_drain_tail(connp, B_TRUE);
5572 
5573 	if (connp == ipst->ips_ip_g_mrouter)
5574 		(void) ip_mrouter_done(NULL, ipst);
5575 
5576 	if (ilg_cleanup_reqd)
5577 		ilg_delete_all(connp);
5578 
5579 	conn_delete_ire(connp, NULL);
5580 
5581 	/*
5582 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5583 	 * callers from write side can't be there now because close
5584 	 * is in progress. The only other caller is ipcl_walk
5585 	 * which checks for the condemned flag.
5586 	 */
5587 	mutex_enter(&connp->conn_lock);
5588 	connp->conn_state_flags |= CONN_CONDEMNED;
5589 	while (connp->conn_ref != 1)
5590 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5591 	connp->conn_state_flags |= CONN_QUIESCED;
5592 	mutex_exit(&connp->conn_lock);
5593 }
5594 
5595 /* ARGSUSED */
5596 int
5597 ip_close(queue_t *q, int flags)
5598 {
5599 	conn_t		*connp;
5600 
5601 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5602 
5603 	/*
5604 	 * Call the appropriate delete routine depending on whether this is
5605 	 * a module or device.
5606 	 */
5607 	if (WR(q)->q_next != NULL) {
5608 		/* This is a module close */
5609 		return (ip_modclose((ill_t *)q->q_ptr));
5610 	}
5611 
5612 	connp = q->q_ptr;
5613 	ip_quiesce_conn(connp);
5614 
5615 	qprocsoff(q);
5616 
5617 	/*
5618 	 * Now we are truly single threaded on this stream, and can
5619 	 * delete the things hanging off the connp, and finally the connp.
5620 	 * We removed this connp from the fanout list, it cannot be
5621 	 * accessed thru the fanouts, and we already waited for the
5622 	 * conn_ref to drop to 0. We are already in close, so
5623 	 * there cannot be any other thread from the top. qprocsoff
5624 	 * has completed, and service has completed or won't run in
5625 	 * future.
5626 	 */
5627 	ASSERT(connp->conn_ref == 1);
5628 
5629 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5630 
5631 	connp->conn_ref--;
5632 	ipcl_conn_destroy(connp);
5633 
5634 	q->q_ptr = WR(q)->q_ptr = NULL;
5635 	return (0);
5636 }
5637 
5638 /*
5639  * Wapper around putnext() so that ip_rts_request can merely use
5640  * conn_recv.
5641  */
5642 /*ARGSUSED2*/
5643 static void
5644 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5645 {
5646 	conn_t *connp = (conn_t *)arg1;
5647 
5648 	putnext(connp->conn_rq, mp);
5649 }
5650 
5651 /*
5652  * Called when the module is about to be unloaded
5653  */
5654 void
5655 ip_ddi_destroy(void)
5656 {
5657 	tnet_fini();
5658 
5659 	icmp_ddi_g_destroy();
5660 	rts_ddi_g_destroy();
5661 	udp_ddi_g_destroy();
5662 	sctp_ddi_g_destroy();
5663 	tcp_ddi_g_destroy();
5664 	ipsec_policy_g_destroy();
5665 	ipcl_g_destroy();
5666 	ip_net_g_destroy();
5667 	ip_ire_g_fini();
5668 	inet_minor_destroy(ip_minor_arena_sa);
5669 #if defined(_LP64)
5670 	inet_minor_destroy(ip_minor_arena_la);
5671 #endif
5672 
5673 #ifdef DEBUG
5674 	list_destroy(&ip_thread_list);
5675 	rw_destroy(&ip_thread_rwlock);
5676 	tsd_destroy(&ip_thread_data);
5677 #endif
5678 
5679 	netstack_unregister(NS_IP);
5680 }
5681 
5682 /*
5683  * First step in cleanup.
5684  */
5685 /* ARGSUSED */
5686 static void
5687 ip_stack_shutdown(netstackid_t stackid, void *arg)
5688 {
5689 	ip_stack_t *ipst = (ip_stack_t *)arg;
5690 
5691 #ifdef NS_DEBUG
5692 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5693 #endif
5694 
5695 	/*
5696 	 * Perform cleanup for special interfaces (loopback and IPMP).
5697 	 */
5698 	ip_interface_cleanup(ipst);
5699 
5700 	/*
5701 	 * The *_hook_shutdown()s start the process of notifying any
5702 	 * consumers that things are going away.... nothing is destroyed.
5703 	 */
5704 	ipv4_hook_shutdown(ipst);
5705 	ipv6_hook_shutdown(ipst);
5706 
5707 	mutex_enter(&ipst->ips_capab_taskq_lock);
5708 	ipst->ips_capab_taskq_quit = B_TRUE;
5709 	cv_signal(&ipst->ips_capab_taskq_cv);
5710 	mutex_exit(&ipst->ips_capab_taskq_lock);
5711 
5712 	mutex_enter(&ipst->ips_mrt_lock);
5713 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5714 	cv_signal(&ipst->ips_mrt_cv);
5715 	mutex_exit(&ipst->ips_mrt_lock);
5716 }
5717 
5718 /*
5719  * Free the IP stack instance.
5720  */
5721 static void
5722 ip_stack_fini(netstackid_t stackid, void *arg)
5723 {
5724 	ip_stack_t *ipst = (ip_stack_t *)arg;
5725 	int ret;
5726 
5727 #ifdef NS_DEBUG
5728 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5729 #endif
5730 	/*
5731 	 * At this point, all of the notifications that the events and
5732 	 * protocols are going away have been run, meaning that we can
5733 	 * now set about starting to clean things up.
5734 	 */
5735 	ipobs_fini(ipst);
5736 	ipv4_hook_destroy(ipst);
5737 	ipv6_hook_destroy(ipst);
5738 	ip_net_destroy(ipst);
5739 
5740 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5741 	cv_destroy(&ipst->ips_capab_taskq_cv);
5742 
5743 	mutex_enter(&ipst->ips_mrt_lock);
5744 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5745 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5746 	mutex_destroy(&ipst->ips_mrt_lock);
5747 	cv_destroy(&ipst->ips_mrt_cv);
5748 	cv_destroy(&ipst->ips_mrt_done_cv);
5749 
5750 	ipmp_destroy(ipst);
5751 	rw_destroy(&ipst->ips_srcid_lock);
5752 
5753 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5754 	ipst->ips_ip_mibkp = NULL;
5755 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5756 	ipst->ips_icmp_mibkp = NULL;
5757 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5758 	ipst->ips_ip_kstat = NULL;
5759 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5760 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5761 	ipst->ips_ip6_kstat = NULL;
5762 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5763 
5764 	nd_free(&ipst->ips_ip_g_nd);
5765 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5766 	ipst->ips_param_arr = NULL;
5767 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5768 	ipst->ips_ndp_arr = NULL;
5769 
5770 	ip_mrouter_stack_destroy(ipst);
5771 
5772 	mutex_destroy(&ipst->ips_ip_mi_lock);
5773 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5774 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5775 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5776 
5777 	ret = untimeout(ipst->ips_igmp_timeout_id);
5778 	if (ret == -1) {
5779 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5780 	} else {
5781 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5782 		ipst->ips_igmp_timeout_id = 0;
5783 	}
5784 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5785 	if (ret == -1) {
5786 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5787 	} else {
5788 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5789 		ipst->ips_igmp_slowtimeout_id = 0;
5790 	}
5791 	ret = untimeout(ipst->ips_mld_timeout_id);
5792 	if (ret == -1) {
5793 		ASSERT(ipst->ips_mld_timeout_id == 0);
5794 	} else {
5795 		ASSERT(ipst->ips_mld_timeout_id != 0);
5796 		ipst->ips_mld_timeout_id = 0;
5797 	}
5798 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5799 	if (ret == -1) {
5800 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5801 	} else {
5802 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5803 		ipst->ips_mld_slowtimeout_id = 0;
5804 	}
5805 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5806 	if (ret == -1) {
5807 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5808 	} else {
5809 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5810 		ipst->ips_ip_ire_expire_id = 0;
5811 	}
5812 
5813 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5814 	mutex_destroy(&ipst->ips_mld_timer_lock);
5815 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5816 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5817 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5818 	rw_destroy(&ipst->ips_ill_g_lock);
5819 
5820 	ip_ire_fini(ipst);
5821 	ip6_asp_free(ipst);
5822 	conn_drain_fini(ipst);
5823 	ipcl_destroy(ipst);
5824 
5825 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5826 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5827 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5828 	ipst->ips_ndp4 = NULL;
5829 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5830 	ipst->ips_ndp6 = NULL;
5831 
5832 	if (ipst->ips_loopback_ksp != NULL) {
5833 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5834 		ipst->ips_loopback_ksp = NULL;
5835 	}
5836 
5837 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5838 	ipst->ips_phyint_g_list = NULL;
5839 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5840 	ipst->ips_ill_g_heads = NULL;
5841 
5842 	ldi_ident_release(ipst->ips_ldi_ident);
5843 	kmem_free(ipst, sizeof (*ipst));
5844 }
5845 
5846 /*
5847  * This function is called from the TSD destructor, and is used to debug
5848  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5849  * details.
5850  */
5851 static void
5852 ip_thread_exit(void *phash)
5853 {
5854 	th_hash_t *thh = phash;
5855 
5856 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5857 	list_remove(&ip_thread_list, thh);
5858 	rw_exit(&ip_thread_rwlock);
5859 	mod_hash_destroy_hash(thh->thh_hash);
5860 	kmem_free(thh, sizeof (*thh));
5861 }
5862 
5863 /*
5864  * Called when the IP kernel module is loaded into the kernel
5865  */
5866 void
5867 ip_ddi_init(void)
5868 {
5869 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5870 
5871 	/*
5872 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5873 	 * initial devices: ip, ip6, tcp, tcp6.
5874 	 */
5875 	/*
5876 	 * If this is a 64-bit kernel, then create two separate arenas -
5877 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5878 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5879 	 */
5880 	ip_minor_arena_la = NULL;
5881 	ip_minor_arena_sa = NULL;
5882 #if defined(_LP64)
5883 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5884 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5885 		cmn_err(CE_PANIC,
5886 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5887 	}
5888 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5889 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5890 		cmn_err(CE_PANIC,
5891 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5892 	}
5893 #else
5894 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5895 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5896 		cmn_err(CE_PANIC,
5897 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5898 	}
5899 #endif
5900 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5901 
5902 	ipcl_g_init();
5903 	ip_ire_g_init();
5904 	ip_net_g_init();
5905 
5906 #ifdef DEBUG
5907 	tsd_create(&ip_thread_data, ip_thread_exit);
5908 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5909 	list_create(&ip_thread_list, sizeof (th_hash_t),
5910 	    offsetof(th_hash_t, thh_link));
5911 #endif
5912 
5913 	/*
5914 	 * We want to be informed each time a stack is created or
5915 	 * destroyed in the kernel, so we can maintain the
5916 	 * set of udp_stack_t's.
5917 	 */
5918 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5919 	    ip_stack_fini);
5920 
5921 	ipsec_policy_g_init();
5922 	tcp_ddi_g_init();
5923 	sctp_ddi_g_init();
5924 
5925 	tnet_init();
5926 
5927 	udp_ddi_g_init();
5928 	rts_ddi_g_init();
5929 	icmp_ddi_g_init();
5930 }
5931 
5932 /*
5933  * Initialize the IP stack instance.
5934  */
5935 static void *
5936 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5937 {
5938 	ip_stack_t	*ipst;
5939 	ipparam_t	*pa;
5940 	ipndp_t		*na;
5941 	major_t		major;
5942 
5943 #ifdef NS_DEBUG
5944 	printf("ip_stack_init(stack %d)\n", stackid);
5945 #endif
5946 
5947 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5948 	ipst->ips_netstack = ns;
5949 
5950 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5951 	    KM_SLEEP);
5952 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5953 	    KM_SLEEP);
5954 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5955 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5956 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5957 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5958 
5959 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5960 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5961 	ipst->ips_igmp_deferred_next = INFINITY;
5962 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5963 	ipst->ips_mld_deferred_next = INFINITY;
5964 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5965 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5966 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5967 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5968 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5969 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5970 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5971 
5972 	ipcl_init(ipst);
5973 	ip_ire_init(ipst);
5974 	ip6_asp_init(ipst);
5975 	ipif_init(ipst);
5976 	conn_drain_init(ipst);
5977 	ip_mrouter_stack_init(ipst);
5978 
5979 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5980 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5981 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
5982 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
5983 
5984 	ipst->ips_ip_multirt_log_interval = 1000;
5985 
5986 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5987 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5988 	ipst->ips_ill_index = 1;
5989 
5990 	ipst->ips_saved_ip_g_forward = -1;
5991 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5992 
5993 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5994 	ipst->ips_param_arr = pa;
5995 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5996 
5997 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5998 	ipst->ips_ndp_arr = na;
5999 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6000 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6001 	    (caddr_t)&ipst->ips_ip_g_forward;
6002 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6003 	    (caddr_t)&ipst->ips_ipv6_forward;
6004 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6005 	    "ip_cgtp_filter") == 0);
6006 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6007 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6008 
6009 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6010 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6011 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6012 
6013 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6014 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6015 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6016 	ipst->ips_ip6_kstat =
6017 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6018 
6019 	ipst->ips_ip_src_id = 1;
6020 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6021 
6022 	ip_net_init(ipst, ns);
6023 	ipv4_hook_init(ipst);
6024 	ipv6_hook_init(ipst);
6025 	ipmp_init(ipst);
6026 	ipobs_init(ipst);
6027 
6028 	/*
6029 	 * Create the taskq dispatcher thread and initialize related stuff.
6030 	 */
6031 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6032 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6033 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6034 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6035 
6036 	/*
6037 	 * Create the mcast_restart_timers_thread() worker thread.
6038 	 */
6039 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6040 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6041 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6042 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6043 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6044 
6045 	major = mod_name_to_major(INET_NAME);
6046 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6047 	return (ipst);
6048 }
6049 
6050 /*
6051  * Allocate and initialize a DLPI template of the specified length.  (May be
6052  * called as writer.)
6053  */
6054 mblk_t *
6055 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6056 {
6057 	mblk_t	*mp;
6058 
6059 	mp = allocb(len, BPRI_MED);
6060 	if (!mp)
6061 		return (NULL);
6062 
6063 	/*
6064 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6065 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6066 	 * that other DLPI are M_PROTO.
6067 	 */
6068 	if (prim == DL_INFO_REQ) {
6069 		mp->b_datap->db_type = M_PCPROTO;
6070 	} else {
6071 		mp->b_datap->db_type = M_PROTO;
6072 	}
6073 
6074 	mp->b_wptr = mp->b_rptr + len;
6075 	bzero(mp->b_rptr, len);
6076 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6077 	return (mp);
6078 }
6079 
6080 /*
6081  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6082  */
6083 mblk_t *
6084 ip_dlnotify_alloc(uint_t notification, uint_t data)
6085 {
6086 	dl_notify_ind_t	*notifyp;
6087 	mblk_t		*mp;
6088 
6089 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6090 		return (NULL);
6091 
6092 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6093 	notifyp->dl_notification = notification;
6094 	notifyp->dl_data = data;
6095 	return (mp);
6096 }
6097 
6098 /*
6099  * Debug formatting routine.  Returns a character string representation of the
6100  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6101  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6102  *
6103  * Once the ndd table-printing interfaces are removed, this can be changed to
6104  * standard dotted-decimal form.
6105  */
6106 char *
6107 ip_dot_addr(ipaddr_t addr, char *buf)
6108 {
6109 	uint8_t *ap = (uint8_t *)&addr;
6110 
6111 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6112 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6113 	return (buf);
6114 }
6115 
6116 /*
6117  * Write the given MAC address as a printable string in the usual colon-
6118  * separated format.
6119  */
6120 const char *
6121 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6122 {
6123 	char *bp;
6124 
6125 	if (alen == 0 || buflen < 4)
6126 		return ("?");
6127 	bp = buf;
6128 	for (;;) {
6129 		/*
6130 		 * If there are more MAC address bytes available, but we won't
6131 		 * have any room to print them, then add "..." to the string
6132 		 * instead.  See below for the 'magic number' explanation.
6133 		 */
6134 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6135 			(void) strcpy(bp, "...");
6136 			break;
6137 		}
6138 		(void) sprintf(bp, "%02x", *addr++);
6139 		bp += 2;
6140 		if (--alen == 0)
6141 			break;
6142 		*bp++ = ':';
6143 		buflen -= 3;
6144 		/*
6145 		 * At this point, based on the first 'if' statement above,
6146 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6147 		 * buflen >= 4.  The first case leaves room for the final "xx"
6148 		 * number and trailing NUL byte.  The second leaves room for at
6149 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6150 		 * that statement.
6151 		 */
6152 	}
6153 	return (buf);
6154 }
6155 
6156 /*
6157  * Send an ICMP error after patching up the packet appropriately.  Returns
6158  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6159  */
6160 static boolean_t
6161 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6162     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6163     zoneid_t zoneid, ip_stack_t *ipst)
6164 {
6165 	ipha_t *ipha;
6166 	mblk_t *first_mp;
6167 	boolean_t secure;
6168 	unsigned char db_type;
6169 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6170 
6171 	first_mp = mp;
6172 	if (mctl_present) {
6173 		mp = mp->b_cont;
6174 		secure = ipsec_in_is_secure(first_mp);
6175 		ASSERT(mp != NULL);
6176 	} else {
6177 		/*
6178 		 * If this is an ICMP error being reported - which goes
6179 		 * up as M_CTLs, we need to convert them to M_DATA till
6180 		 * we finish checking with global policy because
6181 		 * ipsec_check_global_policy() assumes M_DATA as clear
6182 		 * and M_CTL as secure.
6183 		 */
6184 		db_type = DB_TYPE(mp);
6185 		DB_TYPE(mp) = M_DATA;
6186 		secure = B_FALSE;
6187 	}
6188 	/*
6189 	 * We are generating an icmp error for some inbound packet.
6190 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6191 	 * Before we generate an error, check with global policy
6192 	 * to see whether this is allowed to enter the system. As
6193 	 * there is no "conn", we are checking with global policy.
6194 	 */
6195 	ipha = (ipha_t *)mp->b_rptr;
6196 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6197 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6198 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6199 		if (first_mp == NULL)
6200 			return (B_FALSE);
6201 	}
6202 
6203 	if (!mctl_present)
6204 		DB_TYPE(mp) = db_type;
6205 
6206 	if (flags & IP_FF_SEND_ICMP) {
6207 		if (flags & IP_FF_HDR_COMPLETE) {
6208 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6209 				freemsg(first_mp);
6210 				return (B_TRUE);
6211 			}
6212 		}
6213 		if (flags & IP_FF_CKSUM) {
6214 			/*
6215 			 * Have to correct checksum since
6216 			 * the packet might have been
6217 			 * fragmented and the reassembly code in ip_rput
6218 			 * does not restore the IP checksum.
6219 			 */
6220 			ipha->ipha_hdr_checksum = 0;
6221 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6222 		}
6223 		switch (icmp_type) {
6224 		case ICMP_DEST_UNREACHABLE:
6225 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6226 			    ipst);
6227 			break;
6228 		default:
6229 			freemsg(first_mp);
6230 			break;
6231 		}
6232 	} else {
6233 		freemsg(first_mp);
6234 		return (B_FALSE);
6235 	}
6236 
6237 	return (B_TRUE);
6238 }
6239 
6240 /*
6241  * Used to send an ICMP error message when a packet is received for
6242  * a protocol that is not supported. The mblk passed as argument
6243  * is consumed by this function.
6244  */
6245 void
6246 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6247     ip_stack_t *ipst)
6248 {
6249 	mblk_t *mp;
6250 	ipha_t *ipha;
6251 	ill_t *ill;
6252 	ipsec_in_t *ii;
6253 
6254 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6255 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6256 
6257 	mp = ipsec_mp->b_cont;
6258 	ipsec_mp->b_cont = NULL;
6259 	ipha = (ipha_t *)mp->b_rptr;
6260 	/* Get ill from index in ipsec_in_t. */
6261 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6262 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6263 	    ipst);
6264 	if (ill != NULL) {
6265 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6266 			if (ip_fanout_send_icmp(q, mp, flags,
6267 			    ICMP_DEST_UNREACHABLE,
6268 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6269 				BUMP_MIB(ill->ill_ip_mib,
6270 				    ipIfStatsInUnknownProtos);
6271 			}
6272 		} else {
6273 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6274 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6275 			    0, B_FALSE, zoneid, ipst)) {
6276 				BUMP_MIB(ill->ill_ip_mib,
6277 				    ipIfStatsInUnknownProtos);
6278 			}
6279 		}
6280 		ill_refrele(ill);
6281 	} else { /* re-link for the freemsg() below. */
6282 		ipsec_mp->b_cont = mp;
6283 	}
6284 
6285 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6286 	freemsg(ipsec_mp);
6287 }
6288 
6289 /*
6290  * See if the inbound datagram has had IPsec processing applied to it.
6291  */
6292 boolean_t
6293 ipsec_in_is_secure(mblk_t *ipsec_mp)
6294 {
6295 	ipsec_in_t *ii;
6296 
6297 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6298 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6299 
6300 	if (ii->ipsec_in_loopback) {
6301 		return (ii->ipsec_in_secure);
6302 	} else {
6303 		return (ii->ipsec_in_ah_sa != NULL ||
6304 		    ii->ipsec_in_esp_sa != NULL ||
6305 		    ii->ipsec_in_decaps);
6306 	}
6307 }
6308 
6309 /*
6310  * Handle protocols with which IP is less intimate.  There
6311  * can be more than one stream bound to a particular
6312  * protocol.  When this is the case, normally each one gets a copy
6313  * of any incoming packets.
6314  *
6315  * IPsec NOTE :
6316  *
6317  * Don't allow a secure packet going up a non-secure connection.
6318  * We don't allow this because
6319  *
6320  * 1) Reply might go out in clear which will be dropped at
6321  *    the sending side.
6322  * 2) If the reply goes out in clear it will give the
6323  *    adversary enough information for getting the key in
6324  *    most of the cases.
6325  *
6326  * Moreover getting a secure packet when we expect clear
6327  * implies that SA's were added without checking for
6328  * policy on both ends. This should not happen once ISAKMP
6329  * is used to negotiate SAs as SAs will be added only after
6330  * verifying the policy.
6331  *
6332  * IPQoS Notes:
6333  * Once we have determined the client, invoke IPPF processing.
6334  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6335  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6336  * ip_policy will be false.
6337  *
6338  * Zones notes:
6339  * Currently only applications in the global zone can create raw sockets for
6340  * protocols other than ICMP. So unlike the broadcast / multicast case of
6341  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6342  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6343  */
6344 static void
6345 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6346     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6347     zoneid_t zoneid)
6348 {
6349 	queue_t	*rq;
6350 	mblk_t	*mp1, *first_mp1;
6351 	uint_t	protocol = ipha->ipha_protocol;
6352 	ipaddr_t dst;
6353 	mblk_t *first_mp = mp;
6354 	boolean_t secure;
6355 	uint32_t ill_index;
6356 	conn_t	*connp, *first_connp, *next_connp;
6357 	connf_t	*connfp;
6358 	boolean_t shared_addr;
6359 	mib2_ipIfStatsEntry_t *mibptr;
6360 	ip_stack_t *ipst = recv_ill->ill_ipst;
6361 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6362 
6363 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6364 	if (mctl_present) {
6365 		mp = first_mp->b_cont;
6366 		secure = ipsec_in_is_secure(first_mp);
6367 		ASSERT(mp != NULL);
6368 	} else {
6369 		secure = B_FALSE;
6370 	}
6371 	dst = ipha->ipha_dst;
6372 	shared_addr = (zoneid == ALL_ZONES);
6373 	if (shared_addr) {
6374 		/*
6375 		 * We don't allow multilevel ports for raw IP, so no need to
6376 		 * check for that here.
6377 		 */
6378 		zoneid = tsol_packet_to_zoneid(mp);
6379 	}
6380 
6381 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6382 	mutex_enter(&connfp->connf_lock);
6383 	connp = connfp->connf_head;
6384 	for (connp = connfp->connf_head; connp != NULL;
6385 	    connp = connp->conn_next) {
6386 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6387 		    zoneid) &&
6388 		    (!is_system_labeled() ||
6389 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6390 		    connp))) {
6391 			break;
6392 		}
6393 	}
6394 
6395 	if (connp == NULL) {
6396 		/*
6397 		 * No one bound to these addresses.  Is
6398 		 * there a client that wants all
6399 		 * unclaimed datagrams?
6400 		 */
6401 		mutex_exit(&connfp->connf_lock);
6402 		/*
6403 		 * Check for IPPROTO_ENCAP...
6404 		 */
6405 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6406 			/*
6407 			 * If an IPsec mblk is here on a multicast
6408 			 * tunnel (using ip_mroute stuff), check policy here,
6409 			 * THEN ship off to ip_mroute_decap().
6410 			 *
6411 			 * BTW,  If I match a configured IP-in-IP
6412 			 * tunnel, this path will not be reached, and
6413 			 * ip_mroute_decap will never be called.
6414 			 */
6415 			first_mp = ipsec_check_global_policy(first_mp, connp,
6416 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6417 			if (first_mp != NULL) {
6418 				if (mctl_present)
6419 					freeb(first_mp);
6420 				ip_mroute_decap(q, mp, ill);
6421 			} /* Else we already freed everything! */
6422 		} else {
6423 			/*
6424 			 * Otherwise send an ICMP protocol unreachable.
6425 			 */
6426 			if (ip_fanout_send_icmp(q, first_mp, flags,
6427 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6428 			    mctl_present, zoneid, ipst)) {
6429 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6430 			}
6431 		}
6432 		return;
6433 	}
6434 
6435 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6436 
6437 	CONN_INC_REF(connp);
6438 	first_connp = connp;
6439 	connp = connp->conn_next;
6440 
6441 	for (;;) {
6442 		while (connp != NULL) {
6443 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6444 			    flags, zoneid) &&
6445 			    (!is_system_labeled() ||
6446 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6447 			    shared_addr, connp)))
6448 				break;
6449 			connp = connp->conn_next;
6450 		}
6451 
6452 		/*
6453 		 * Copy the packet.
6454 		 */
6455 		if (connp == NULL ||
6456 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6457 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6458 			/*
6459 			 * No more interested clients or memory
6460 			 * allocation failed
6461 			 */
6462 			connp = first_connp;
6463 			break;
6464 		}
6465 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6466 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6467 		CONN_INC_REF(connp);
6468 		mutex_exit(&connfp->connf_lock);
6469 		rq = connp->conn_rq;
6470 
6471 		/*
6472 		 * Check flow control
6473 		 */
6474 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6475 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6476 			if (flags & IP_FF_RAWIP) {
6477 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6478 			} else {
6479 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6480 			}
6481 
6482 			freemsg(first_mp1);
6483 		} else {
6484 			/*
6485 			 * Enforce policy like any other conn_t.  Note that
6486 			 * IP-in-IP packets don't come through here, but
6487 			 * through ip_iptun_input() or
6488 			 * icmp_inbound_iptun_fanout().  IPsec policy for such
6489 			 * packets is enforced in the iptun module.
6490 			 */
6491 			if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6492 			    secure) {
6493 				first_mp1 = ipsec_check_inbound_policy
6494 				    (first_mp1, connp, ipha, NULL,
6495 				    mctl_present);
6496 			}
6497 			if (first_mp1 != NULL) {
6498 				int in_flags = 0;
6499 				/*
6500 				 * ip_fanout_proto also gets called from
6501 				 * icmp_inbound_error_fanout, in which case
6502 				 * the msg type is M_CTL.  Don't add info
6503 				 * in this case for the time being. In future
6504 				 * when there is a need for knowing the
6505 				 * inbound iface index for ICMP error msgs,
6506 				 * then this can be changed.
6507 				 */
6508 				if (connp->conn_recvif)
6509 					in_flags = IPF_RECVIF;
6510 				/*
6511 				 * The ULP may support IP_RECVPKTINFO for both
6512 				 * IP v4 and v6 so pass the appropriate argument
6513 				 * based on conn IP version.
6514 				 */
6515 				if (connp->conn_ip_recvpktinfo) {
6516 					if (connp->conn_af_isv6) {
6517 						/*
6518 						 * V6 only needs index
6519 						 */
6520 						in_flags |= IPF_RECVIF;
6521 					} else {
6522 						/*
6523 						 * V4 needs index +
6524 						 * matching address.
6525 						 */
6526 						in_flags |= IPF_RECVADDR;
6527 					}
6528 				}
6529 				if ((in_flags != 0) &&
6530 				    (mp->b_datap->db_type != M_CTL)) {
6531 					/*
6532 					 * the actual data will be
6533 					 * contained in b_cont upon
6534 					 * successful return of the
6535 					 * following call else
6536 					 * original mblk is returned
6537 					 */
6538 					ASSERT(recv_ill != NULL);
6539 					mp1 = ip_add_info(mp1, recv_ill,
6540 					    in_flags, IPCL_ZONEID(connp), ipst);
6541 				}
6542 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6543 				if (mctl_present)
6544 					freeb(first_mp1);
6545 				(connp->conn_recv)(connp, mp1, NULL);
6546 			}
6547 		}
6548 		mutex_enter(&connfp->connf_lock);
6549 		/* Follow the next pointer before releasing the conn. */
6550 		next_connp = connp->conn_next;
6551 		CONN_DEC_REF(connp);
6552 		connp = next_connp;
6553 	}
6554 
6555 	/* Last one.  Send it upstream. */
6556 	mutex_exit(&connfp->connf_lock);
6557 
6558 	/*
6559 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6560 	 * will be set to false.
6561 	 */
6562 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6563 		ill_index = ill->ill_phyint->phyint_ifindex;
6564 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6565 		if (mp == NULL) {
6566 			CONN_DEC_REF(connp);
6567 			if (mctl_present) {
6568 				freeb(first_mp);
6569 			}
6570 			return;
6571 		}
6572 	}
6573 
6574 	rq = connp->conn_rq;
6575 	/*
6576 	 * Check flow control
6577 	 */
6578 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6579 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6580 		if (flags & IP_FF_RAWIP) {
6581 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6582 		} else {
6583 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6584 		}
6585 
6586 		freemsg(first_mp);
6587 	} else {
6588 		ASSERT(!IPCL_IS_IPTUN(connp));
6589 
6590 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6591 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6592 			    ipha, NULL, mctl_present);
6593 		}
6594 
6595 		if (first_mp != NULL) {
6596 			int in_flags = 0;
6597 
6598 			/*
6599 			 * ip_fanout_proto also gets called
6600 			 * from icmp_inbound_error_fanout, in
6601 			 * which case the msg type is M_CTL.
6602 			 * Don't add info in this case for time
6603 			 * being. In future when there is a
6604 			 * need for knowing the inbound iface
6605 			 * index for ICMP error msgs, then this
6606 			 * can be changed
6607 			 */
6608 			if (connp->conn_recvif)
6609 				in_flags = IPF_RECVIF;
6610 			if (connp->conn_ip_recvpktinfo) {
6611 				if (connp->conn_af_isv6) {
6612 					/*
6613 					 * V6 only needs index
6614 					 */
6615 					in_flags |= IPF_RECVIF;
6616 				} else {
6617 					/*
6618 					 * V4 needs index +
6619 					 * matching address.
6620 					 */
6621 					in_flags |= IPF_RECVADDR;
6622 				}
6623 			}
6624 			if ((in_flags != 0) &&
6625 			    (mp->b_datap->db_type != M_CTL)) {
6626 
6627 				/*
6628 				 * the actual data will be contained in
6629 				 * b_cont upon successful return
6630 				 * of the following call else original
6631 				 * mblk is returned
6632 				 */
6633 				ASSERT(recv_ill != NULL);
6634 				mp = ip_add_info(mp, recv_ill,
6635 				    in_flags, IPCL_ZONEID(connp), ipst);
6636 			}
6637 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6638 			(connp->conn_recv)(connp, mp, NULL);
6639 			if (mctl_present)
6640 				freeb(first_mp);
6641 		}
6642 	}
6643 	CONN_DEC_REF(connp);
6644 }
6645 
6646 /*
6647  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6648  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6649  * the correct squeue, in this case the same squeue as a valid listener with
6650  * no current connection state for the packet we are processing. The function
6651  * is called for synchronizing both IPv4 and IPv6.
6652  */
6653 void
6654 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6655     tcp_stack_t *tcps, conn_t *connp)
6656 {
6657 	mblk_t *rst_mp;
6658 	tcp_xmit_reset_event_t *eventp;
6659 
6660 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6661 
6662 	if (rst_mp == NULL) {
6663 		freemsg(mp);
6664 		return;
6665 	}
6666 
6667 	rst_mp->b_datap->db_type = M_PROTO;
6668 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6669 
6670 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6671 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6672 	eventp->tcp_xre_iphdrlen = hdrlen;
6673 	eventp->tcp_xre_zoneid = zoneid;
6674 	eventp->tcp_xre_tcps = tcps;
6675 
6676 	rst_mp->b_cont = mp;
6677 	mp = rst_mp;
6678 
6679 	/*
6680 	 * Increment the connref, this ref will be released by the squeue
6681 	 * framework.
6682 	 */
6683 	CONN_INC_REF(connp);
6684 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6685 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6686 }
6687 
6688 /*
6689  * Fanout for TCP packets
6690  * The caller puts <fport, lport> in the ports parameter.
6691  *
6692  * IPQoS Notes
6693  * Before sending it to the client, invoke IPPF processing.
6694  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6695  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6696  * ip_policy is false.
6697  */
6698 static void
6699 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6700     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6701 {
6702 	mblk_t  *first_mp;
6703 	boolean_t secure;
6704 	uint32_t ill_index;
6705 	int	ip_hdr_len;
6706 	tcph_t	*tcph;
6707 	boolean_t syn_present = B_FALSE;
6708 	conn_t	*connp;
6709 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6710 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6711 
6712 	ASSERT(recv_ill != NULL);
6713 
6714 	first_mp = mp;
6715 	if (mctl_present) {
6716 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6717 		mp = first_mp->b_cont;
6718 		secure = ipsec_in_is_secure(first_mp);
6719 		ASSERT(mp != NULL);
6720 	} else {
6721 		secure = B_FALSE;
6722 	}
6723 
6724 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6725 
6726 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6727 	    zoneid, ipst)) == NULL) {
6728 		/*
6729 		 * No connected connection or listener. Send a
6730 		 * TH_RST via tcp_xmit_listeners_reset.
6731 		 */
6732 
6733 		/* Initiate IPPf processing, if needed. */
6734 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6735 			uint32_t ill_index;
6736 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6737 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6738 			if (first_mp == NULL)
6739 				return;
6740 		}
6741 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6742 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6743 		    zoneid));
6744 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6745 		    ipst->ips_netstack->netstack_tcp, NULL);
6746 		return;
6747 	}
6748 
6749 	/*
6750 	 * Allocate the SYN for the TCP connection here itself
6751 	 */
6752 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6753 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6754 		if (IPCL_IS_TCP(connp)) {
6755 			squeue_t *sqp;
6756 
6757 			/*
6758 			 * If the queue belongs to a conn, and fused tcp
6759 			 * loopback is enabled, assign the eager's squeue
6760 			 * to be that of the active connect's. Note that
6761 			 * we don't check for IP_FF_LOOPBACK here since this
6762 			 * routine gets called only for loopback (unlike the
6763 			 * IPv6 counterpart).
6764 			 */
6765 			if (do_tcp_fusion &&
6766 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6767 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6768 			    !secure &&
6769 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6770 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6771 				sqp = Q_TO_CONN(q)->conn_sqp;
6772 			} else {
6773 				sqp = IP_SQUEUE_GET(lbolt);
6774 			}
6775 
6776 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6777 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6778 			syn_present = B_TRUE;
6779 		}
6780 	}
6781 
6782 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6783 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6784 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6785 		if ((flags & TH_RST) || (flags & TH_URG)) {
6786 			CONN_DEC_REF(connp);
6787 			freemsg(first_mp);
6788 			return;
6789 		}
6790 		if (flags & TH_ACK) {
6791 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6792 			    ipst->ips_netstack->netstack_tcp, connp);
6793 			CONN_DEC_REF(connp);
6794 			return;
6795 		}
6796 
6797 		CONN_DEC_REF(connp);
6798 		freemsg(first_mp);
6799 		return;
6800 	}
6801 
6802 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6803 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6804 		    NULL, mctl_present);
6805 		if (first_mp == NULL) {
6806 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6807 			CONN_DEC_REF(connp);
6808 			return;
6809 		}
6810 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6811 			ASSERT(syn_present);
6812 			if (mctl_present) {
6813 				ASSERT(first_mp != mp);
6814 				first_mp->b_datap->db_struioflag |=
6815 				    STRUIO_POLICY;
6816 			} else {
6817 				ASSERT(first_mp == mp);
6818 				mp->b_datap->db_struioflag &=
6819 				    ~STRUIO_EAGER;
6820 				mp->b_datap->db_struioflag |=
6821 				    STRUIO_POLICY;
6822 			}
6823 		} else {
6824 			/*
6825 			 * Discard first_mp early since we're dealing with a
6826 			 * fully-connected conn_t and tcp doesn't do policy in
6827 			 * this case.
6828 			 */
6829 			if (mctl_present) {
6830 				freeb(first_mp);
6831 				mctl_present = B_FALSE;
6832 			}
6833 			first_mp = mp;
6834 		}
6835 	}
6836 
6837 	/*
6838 	 * Initiate policy processing here if needed. If we get here from
6839 	 * icmp_inbound_error_fanout, ip_policy is false.
6840 	 */
6841 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6842 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6843 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6844 		if (mp == NULL) {
6845 			CONN_DEC_REF(connp);
6846 			if (mctl_present)
6847 				freeb(first_mp);
6848 			return;
6849 		} else if (mctl_present) {
6850 			ASSERT(first_mp != mp);
6851 			first_mp->b_cont = mp;
6852 		} else {
6853 			first_mp = mp;
6854 		}
6855 	}
6856 
6857 	/* Handle socket options. */
6858 	if (!syn_present &&
6859 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6860 		/* Add header */
6861 		ASSERT(recv_ill != NULL);
6862 		/*
6863 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6864 		 * IPF_RECVIF.
6865 		 */
6866 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6867 		    ipst);
6868 		if (mp == NULL) {
6869 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6870 			CONN_DEC_REF(connp);
6871 			if (mctl_present)
6872 				freeb(first_mp);
6873 			return;
6874 		} else if (mctl_present) {
6875 			/*
6876 			 * ip_add_info might return a new mp.
6877 			 */
6878 			ASSERT(first_mp != mp);
6879 			first_mp->b_cont = mp;
6880 		} else {
6881 			first_mp = mp;
6882 		}
6883 	}
6884 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6885 	if (IPCL_IS_TCP(connp)) {
6886 		/* do not drain, certain use cases can blow the stack */
6887 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6888 		    connp, SQ_NODRAIN, SQTAG_IP_FANOUT_TCP);
6889 	} else {
6890 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6891 		(connp->conn_recv)(connp, first_mp, NULL);
6892 		CONN_DEC_REF(connp);
6893 	}
6894 }
6895 
6896 /*
6897  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6898  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6899  * is not consumed.
6900  *
6901  * One of four things can happen, all of which affect the passed-in mblk:
6902  *
6903  * 1.) ICMP messages that go through here just get returned TRUE.
6904  *
6905  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6906  *
6907  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6908  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6909  *
6910  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6911  */
6912 static boolean_t
6913 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6914     ipsec_stack_t *ipss)
6915 {
6916 	int shift, plen, iph_len;
6917 	ipha_t *ipha;
6918 	udpha_t *udpha;
6919 	uint32_t *spi;
6920 	uint32_t esp_ports;
6921 	uint8_t *orptr;
6922 	boolean_t free_ire;
6923 
6924 	if (DB_TYPE(mp) == M_CTL) {
6925 		/*
6926 		 * ICMP message with UDP inside.  Don't bother stripping, just
6927 		 * send it up.
6928 		 *
6929 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6930 		 * to ignore errors set by ICMP anyway ('cause they might be
6931 		 * forged), but that's the app's decision, not ours.
6932 		 */
6933 
6934 		/* Bunch of reality checks for DEBUG kernels... */
6935 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6936 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6937 
6938 		return (B_TRUE);
6939 	}
6940 
6941 	ipha = (ipha_t *)mp->b_rptr;
6942 	iph_len = IPH_HDR_LENGTH(ipha);
6943 	plen = ntohs(ipha->ipha_length);
6944 
6945 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6946 		/*
6947 		 * Most likely a keepalive for the benefit of an intervening
6948 		 * NAT.  These aren't for us, per se, so drop it.
6949 		 *
6950 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6951 		 * byte packets (keepalives are 1-byte), but we'll drop them
6952 		 * also.
6953 		 */
6954 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6955 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6956 		return (B_FALSE);
6957 	}
6958 
6959 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6960 		/* might as well pull it all up - it might be ESP. */
6961 		if (!pullupmsg(mp, -1)) {
6962 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6963 			    DROPPER(ipss, ipds_esp_nomem),
6964 			    &ipss->ipsec_dropper);
6965 			return (B_FALSE);
6966 		}
6967 
6968 		ipha = (ipha_t *)mp->b_rptr;
6969 	}
6970 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6971 	if (*spi == 0) {
6972 		/* UDP packet - remove 0-spi. */
6973 		shift = sizeof (uint32_t);
6974 	} else {
6975 		/* ESP-in-UDP packet - reduce to ESP. */
6976 		ipha->ipha_protocol = IPPROTO_ESP;
6977 		shift = sizeof (udpha_t);
6978 	}
6979 
6980 	/* Fix IP header */
6981 	ipha->ipha_length = htons(plen - shift);
6982 	ipha->ipha_hdr_checksum = 0;
6983 
6984 	orptr = mp->b_rptr;
6985 	mp->b_rptr += shift;
6986 
6987 	udpha = (udpha_t *)(orptr + iph_len);
6988 	if (*spi == 0) {
6989 		ASSERT((uint8_t *)ipha == orptr);
6990 		udpha->uha_length = htons(plen - shift - iph_len);
6991 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6992 		esp_ports = 0;
6993 	} else {
6994 		esp_ports = *((uint32_t *)udpha);
6995 		ASSERT(esp_ports != 0);
6996 	}
6997 	ovbcopy(orptr, orptr + shift, iph_len);
6998 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6999 		ipha = (ipha_t *)(orptr + shift);
7000 
7001 		free_ire = (ire == NULL);
7002 		if (free_ire) {
7003 			/* Re-acquire ire. */
7004 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7005 			    ipss->ipsec_netstack->netstack_ip);
7006 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7007 				if (ire != NULL)
7008 					ire_refrele(ire);
7009 				/*
7010 				 * Do a regular freemsg(), as this is an IP
7011 				 * error (no local route) not an IPsec one.
7012 				 */
7013 				freemsg(mp);
7014 			}
7015 		}
7016 
7017 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7018 		if (free_ire)
7019 			ire_refrele(ire);
7020 	}
7021 
7022 	return (esp_ports == 0);
7023 }
7024 
7025 /*
7026  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7027  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7028  * Caller is responsible for dropping references to the conn, and freeing
7029  * first_mp.
7030  *
7031  * IPQoS Notes
7032  * Before sending it to the client, invoke IPPF processing. Policy processing
7033  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7034  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7035  * ip_wput_local, ip_policy is false.
7036  */
7037 static void
7038 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7039     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7040     boolean_t ip_policy)
7041 {
7042 	boolean_t	mctl_present = (first_mp != NULL);
7043 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7044 	uint32_t	ill_index;
7045 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7046 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7047 
7048 	ASSERT(ill != NULL);
7049 
7050 	if (mctl_present)
7051 		first_mp->b_cont = mp;
7052 	else
7053 		first_mp = mp;
7054 
7055 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7056 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7057 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7058 		freemsg(first_mp);
7059 		return;
7060 	}
7061 
7062 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7063 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7064 		    NULL, mctl_present);
7065 		/* Freed by ipsec_check_inbound_policy(). */
7066 		if (first_mp == NULL) {
7067 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7068 			return;
7069 		}
7070 	}
7071 	if (mctl_present)
7072 		freeb(first_mp);
7073 
7074 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7075 	if (connp->conn_udp->udp_nat_t_endpoint) {
7076 		if (mctl_present) {
7077 			/* mctl_present *shouldn't* happen. */
7078 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7079 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7080 			    &ipss->ipsec_dropper);
7081 			return;
7082 		}
7083 
7084 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7085 			return;
7086 	}
7087 
7088 	/* Handle options. */
7089 	if (connp->conn_recvif)
7090 		in_flags = IPF_RECVIF;
7091 	/*
7092 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7093 	 * passed to ip_add_info is based on IP version of connp.
7094 	 */
7095 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7096 		if (connp->conn_af_isv6) {
7097 			/*
7098 			 * V6 only needs index
7099 			 */
7100 			in_flags |= IPF_RECVIF;
7101 		} else {
7102 			/*
7103 			 * V4 needs index + matching address.
7104 			 */
7105 			in_flags |= IPF_RECVADDR;
7106 		}
7107 	}
7108 
7109 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7110 		in_flags |= IPF_RECVSLLA;
7111 
7112 	/*
7113 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7114 	 * freed if the packet is dropped. The caller will do so.
7115 	 */
7116 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7117 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7118 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7119 		if (mp == NULL) {
7120 			return;
7121 		}
7122 	}
7123 	if ((in_flags != 0) &&
7124 	    (mp->b_datap->db_type != M_CTL)) {
7125 		/*
7126 		 * The actual data will be contained in b_cont
7127 		 * upon successful return of the following call
7128 		 * else original mblk is returned
7129 		 */
7130 		ASSERT(recv_ill != NULL);
7131 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7132 		    ipst);
7133 	}
7134 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7135 	/* Send it upstream */
7136 	(connp->conn_recv)(connp, mp, NULL);
7137 }
7138 
7139 /*
7140  * Fanout for UDP packets.
7141  * The caller puts <fport, lport> in the ports parameter.
7142  *
7143  * If SO_REUSEADDR is set all multicast and broadcast packets
7144  * will be delivered to all streams bound to the same port.
7145  *
7146  * Zones notes:
7147  * Multicast and broadcast packets will be distributed to streams in all zones.
7148  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7149  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7150  * packets. To maintain this behavior with multiple zones, the conns are grouped
7151  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7152  * each zone. If unset, all the following conns in the same zone are skipped.
7153  */
7154 static void
7155 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7156     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7157     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7158 {
7159 	uint32_t	dstport, srcport;
7160 	ipaddr_t	dst;
7161 	mblk_t		*first_mp;
7162 	boolean_t	secure;
7163 	in6_addr_t	v6src;
7164 	conn_t		*connp;
7165 	connf_t		*connfp;
7166 	conn_t		*first_connp;
7167 	conn_t		*next_connp;
7168 	mblk_t		*mp1, *first_mp1;
7169 	ipaddr_t	src;
7170 	zoneid_t	last_zoneid;
7171 	boolean_t	reuseaddr;
7172 	boolean_t	shared_addr;
7173 	boolean_t	unlabeled;
7174 	ip_stack_t	*ipst;
7175 
7176 	ASSERT(recv_ill != NULL);
7177 	ipst = recv_ill->ill_ipst;
7178 
7179 	first_mp = mp;
7180 	if (mctl_present) {
7181 		mp = first_mp->b_cont;
7182 		first_mp->b_cont = NULL;
7183 		secure = ipsec_in_is_secure(first_mp);
7184 		ASSERT(mp != NULL);
7185 	} else {
7186 		first_mp = NULL;
7187 		secure = B_FALSE;
7188 	}
7189 
7190 	/* Extract ports in net byte order */
7191 	dstport = htons(ntohl(ports) & 0xFFFF);
7192 	srcport = htons(ntohl(ports) >> 16);
7193 	dst = ipha->ipha_dst;
7194 	src = ipha->ipha_src;
7195 
7196 	unlabeled = B_FALSE;
7197 	if (is_system_labeled())
7198 		/* Cred cannot be null on IPv4 */
7199 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7200 		    TSLF_UNLABELED) != 0;
7201 	shared_addr = (zoneid == ALL_ZONES);
7202 	if (shared_addr) {
7203 		/*
7204 		 * No need to handle exclusive-stack zones since ALL_ZONES
7205 		 * only applies to the shared stack.
7206 		 */
7207 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7208 		/*
7209 		 * If no shared MLP is found, tsol_mlp_findzone returns
7210 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7211 		 * search for the zone based on the packet label.
7212 		 *
7213 		 * If there is such a zone, we prefer to find a
7214 		 * connection in it.  Otherwise, we look for a
7215 		 * MAC-exempt connection in any zone whose label
7216 		 * dominates the default label on the packet.
7217 		 */
7218 		if (zoneid == ALL_ZONES)
7219 			zoneid = tsol_packet_to_zoneid(mp);
7220 		else
7221 			unlabeled = B_FALSE;
7222 	}
7223 
7224 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7225 	mutex_enter(&connfp->connf_lock);
7226 	connp = connfp->connf_head;
7227 	if (!broadcast && !CLASSD(dst)) {
7228 		/*
7229 		 * Not broadcast or multicast. Send to the one (first)
7230 		 * client we find. No need to check conn_wantpacket()
7231 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7232 		 * IPv4 unicast packets.
7233 		 */
7234 		while ((connp != NULL) &&
7235 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7236 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7237 		    !(unlabeled && (connp->conn_mac_mode != CONN_MAC_DEFAULT) &&
7238 		    shared_addr)))) {
7239 			/*
7240 			 * We keep searching since the conn did not match,
7241 			 * or its zone did not match and it is not either
7242 			 * an allzones conn or a mac exempt conn (if the
7243 			 * sender is unlabeled.)
7244 			 */
7245 			connp = connp->conn_next;
7246 		}
7247 
7248 		if (connp == NULL ||
7249 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7250 			goto notfound;
7251 
7252 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7253 
7254 		if (is_system_labeled() &&
7255 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7256 		    connp))
7257 			goto notfound;
7258 
7259 		CONN_INC_REF(connp);
7260 		mutex_exit(&connfp->connf_lock);
7261 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7262 		    flags, recv_ill, ip_policy);
7263 		IP_STAT(ipst, ip_udp_fannorm);
7264 		CONN_DEC_REF(connp);
7265 		return;
7266 	}
7267 
7268 	/*
7269 	 * Broadcast and multicast case
7270 	 *
7271 	 * Need to check conn_wantpacket().
7272 	 * If SO_REUSEADDR has been set on the first we send the
7273 	 * packet to all clients that have joined the group and
7274 	 * match the port.
7275 	 */
7276 
7277 	while (connp != NULL) {
7278 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7279 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7280 		    (!is_system_labeled() ||
7281 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7282 		    connp)))
7283 			break;
7284 		connp = connp->conn_next;
7285 	}
7286 
7287 	if (connp == NULL ||
7288 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7289 		goto notfound;
7290 
7291 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7292 
7293 	first_connp = connp;
7294 	/*
7295 	 * When SO_REUSEADDR is not set, send the packet only to the first
7296 	 * matching connection in its zone by keeping track of the zoneid.
7297 	 */
7298 	reuseaddr = first_connp->conn_reuseaddr;
7299 	last_zoneid = first_connp->conn_zoneid;
7300 
7301 	CONN_INC_REF(connp);
7302 	connp = connp->conn_next;
7303 	for (;;) {
7304 		while (connp != NULL) {
7305 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7306 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7307 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7308 			    (!is_system_labeled() ||
7309 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7310 			    shared_addr, connp)))
7311 				break;
7312 			connp = connp->conn_next;
7313 		}
7314 		/*
7315 		 * Just copy the data part alone. The mctl part is
7316 		 * needed just for verifying policy and it is never
7317 		 * sent up.
7318 		 */
7319 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7320 		    ((mp1 = copymsg(mp)) == NULL))) {
7321 			/*
7322 			 * No more interested clients or memory
7323 			 * allocation failed
7324 			 */
7325 			connp = first_connp;
7326 			break;
7327 		}
7328 		if (connp->conn_zoneid != last_zoneid) {
7329 			/*
7330 			 * Update the zoneid so that the packet isn't sent to
7331 			 * any more conns in the same zone unless SO_REUSEADDR
7332 			 * is set.
7333 			 */
7334 			reuseaddr = connp->conn_reuseaddr;
7335 			last_zoneid = connp->conn_zoneid;
7336 		}
7337 		if (first_mp != NULL) {
7338 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7339 			    ipsec_info_type == IPSEC_IN);
7340 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7341 			    ipst->ips_netstack);
7342 			if (first_mp1 == NULL) {
7343 				freemsg(mp1);
7344 				connp = first_connp;
7345 				break;
7346 			}
7347 		} else {
7348 			first_mp1 = NULL;
7349 		}
7350 		CONN_INC_REF(connp);
7351 		mutex_exit(&connfp->connf_lock);
7352 		/*
7353 		 * IPQoS notes: We don't send the packet for policy
7354 		 * processing here, will do it for the last one (below).
7355 		 * i.e. we do it per-packet now, but if we do policy
7356 		 * processing per-conn, then we would need to do it
7357 		 * here too.
7358 		 */
7359 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7360 		    ipha, flags, recv_ill, B_FALSE);
7361 		mutex_enter(&connfp->connf_lock);
7362 		/* Follow the next pointer before releasing the conn. */
7363 		next_connp = connp->conn_next;
7364 		IP_STAT(ipst, ip_udp_fanmb);
7365 		CONN_DEC_REF(connp);
7366 		connp = next_connp;
7367 	}
7368 
7369 	/* Last one.  Send it upstream. */
7370 	mutex_exit(&connfp->connf_lock);
7371 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7372 	    recv_ill, ip_policy);
7373 	IP_STAT(ipst, ip_udp_fanmb);
7374 	CONN_DEC_REF(connp);
7375 	return;
7376 
7377 notfound:
7378 
7379 	mutex_exit(&connfp->connf_lock);
7380 	IP_STAT(ipst, ip_udp_fanothers);
7381 	/*
7382 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7383 	 * have already been matched above, since they live in the IPv4
7384 	 * fanout tables. This implies we only need to
7385 	 * check for IPv6 in6addr_any endpoints here.
7386 	 * Thus we compare using ipv6_all_zeros instead of the destination
7387 	 * address, except for the multicast group membership lookup which
7388 	 * uses the IPv4 destination.
7389 	 */
7390 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7391 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7392 	mutex_enter(&connfp->connf_lock);
7393 	connp = connfp->connf_head;
7394 	if (!broadcast && !CLASSD(dst)) {
7395 		while (connp != NULL) {
7396 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7397 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7398 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7399 			    !connp->conn_ipv6_v6only)
7400 				break;
7401 			connp = connp->conn_next;
7402 		}
7403 
7404 		if (connp != NULL && is_system_labeled() &&
7405 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7406 		    connp))
7407 			connp = NULL;
7408 
7409 		if (connp == NULL ||
7410 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7411 			/*
7412 			 * No one bound to this port.  Is
7413 			 * there a client that wants all
7414 			 * unclaimed datagrams?
7415 			 */
7416 			mutex_exit(&connfp->connf_lock);
7417 
7418 			if (mctl_present)
7419 				first_mp->b_cont = mp;
7420 			else
7421 				first_mp = mp;
7422 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7423 			    connf_head != NULL) {
7424 				ip_fanout_proto(q, first_mp, ill, ipha,
7425 				    flags | IP_FF_RAWIP, mctl_present,
7426 				    ip_policy, recv_ill, zoneid);
7427 			} else {
7428 				if (ip_fanout_send_icmp(q, first_mp, flags,
7429 				    ICMP_DEST_UNREACHABLE,
7430 				    ICMP_PORT_UNREACHABLE,
7431 				    mctl_present, zoneid, ipst)) {
7432 					BUMP_MIB(ill->ill_ip_mib,
7433 					    udpIfStatsNoPorts);
7434 				}
7435 			}
7436 			return;
7437 		}
7438 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7439 
7440 		CONN_INC_REF(connp);
7441 		mutex_exit(&connfp->connf_lock);
7442 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7443 		    flags, recv_ill, ip_policy);
7444 		CONN_DEC_REF(connp);
7445 		return;
7446 	}
7447 	/*
7448 	 * IPv4 multicast packet being delivered to an AF_INET6
7449 	 * in6addr_any endpoint.
7450 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7451 	 * and not conn_wantpacket_v6() since any multicast membership is
7452 	 * for an IPv4-mapped multicast address.
7453 	 * The packet is sent to all clients in all zones that have joined the
7454 	 * group and match the port.
7455 	 */
7456 	while (connp != NULL) {
7457 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7458 		    srcport, v6src) &&
7459 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7460 		    (!is_system_labeled() ||
7461 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7462 		    connp)))
7463 			break;
7464 		connp = connp->conn_next;
7465 	}
7466 
7467 	if (connp == NULL ||
7468 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7469 		/*
7470 		 * No one bound to this port.  Is
7471 		 * there a client that wants all
7472 		 * unclaimed datagrams?
7473 		 */
7474 		mutex_exit(&connfp->connf_lock);
7475 
7476 		if (mctl_present)
7477 			first_mp->b_cont = mp;
7478 		else
7479 			first_mp = mp;
7480 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7481 		    NULL) {
7482 			ip_fanout_proto(q, first_mp, ill, ipha,
7483 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7484 			    recv_ill, zoneid);
7485 		} else {
7486 			/*
7487 			 * We used to attempt to send an icmp error here, but
7488 			 * since this is known to be a multicast packet
7489 			 * and we don't send icmp errors in response to
7490 			 * multicast, just drop the packet and give up sooner.
7491 			 */
7492 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7493 			freemsg(first_mp);
7494 		}
7495 		return;
7496 	}
7497 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7498 
7499 	first_connp = connp;
7500 
7501 	CONN_INC_REF(connp);
7502 	connp = connp->conn_next;
7503 	for (;;) {
7504 		while (connp != NULL) {
7505 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7506 			    ipv6_all_zeros, srcport, v6src) &&
7507 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7508 			    (!is_system_labeled() ||
7509 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7510 			    shared_addr, connp)))
7511 				break;
7512 			connp = connp->conn_next;
7513 		}
7514 		/*
7515 		 * Just copy the data part alone. The mctl part is
7516 		 * needed just for verifying policy and it is never
7517 		 * sent up.
7518 		 */
7519 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7520 		    ((mp1 = copymsg(mp)) == NULL))) {
7521 			/*
7522 			 * No more intested clients or memory
7523 			 * allocation failed
7524 			 */
7525 			connp = first_connp;
7526 			break;
7527 		}
7528 		if (first_mp != NULL) {
7529 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7530 			    ipsec_info_type == IPSEC_IN);
7531 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7532 			    ipst->ips_netstack);
7533 			if (first_mp1 == NULL) {
7534 				freemsg(mp1);
7535 				connp = first_connp;
7536 				break;
7537 			}
7538 		} else {
7539 			first_mp1 = NULL;
7540 		}
7541 		CONN_INC_REF(connp);
7542 		mutex_exit(&connfp->connf_lock);
7543 		/*
7544 		 * IPQoS notes: We don't send the packet for policy
7545 		 * processing here, will do it for the last one (below).
7546 		 * i.e. we do it per-packet now, but if we do policy
7547 		 * processing per-conn, then we would need to do it
7548 		 * here too.
7549 		 */
7550 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7551 		    ipha, flags, recv_ill, B_FALSE);
7552 		mutex_enter(&connfp->connf_lock);
7553 		/* Follow the next pointer before releasing the conn. */
7554 		next_connp = connp->conn_next;
7555 		CONN_DEC_REF(connp);
7556 		connp = next_connp;
7557 	}
7558 
7559 	/* Last one.  Send it upstream. */
7560 	mutex_exit(&connfp->connf_lock);
7561 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7562 	    recv_ill, ip_policy);
7563 	CONN_DEC_REF(connp);
7564 }
7565 
7566 /*
7567  * Complete the ip_wput header so that it
7568  * is possible to generate ICMP
7569  * errors.
7570  */
7571 int
7572 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7573 {
7574 	ire_t *ire;
7575 
7576 	if (ipha->ipha_src == INADDR_ANY) {
7577 		ire = ire_lookup_local(zoneid, ipst);
7578 		if (ire == NULL) {
7579 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7580 			return (1);
7581 		}
7582 		ipha->ipha_src = ire->ire_addr;
7583 		ire_refrele(ire);
7584 	}
7585 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7586 	ipha->ipha_hdr_checksum = 0;
7587 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7588 	return (0);
7589 }
7590 
7591 /*
7592  * Nobody should be sending
7593  * packets up this stream
7594  */
7595 static void
7596 ip_lrput(queue_t *q, mblk_t *mp)
7597 {
7598 	mblk_t *mp1;
7599 
7600 	switch (mp->b_datap->db_type) {
7601 	case M_FLUSH:
7602 		/* Turn around */
7603 		if (*mp->b_rptr & FLUSHW) {
7604 			*mp->b_rptr &= ~FLUSHR;
7605 			qreply(q, mp);
7606 			return;
7607 		}
7608 		break;
7609 	}
7610 	/* Could receive messages that passed through ar_rput */
7611 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7612 		mp1->b_prev = mp1->b_next = NULL;
7613 	freemsg(mp);
7614 }
7615 
7616 /* Nobody should be sending packets down this stream */
7617 /* ARGSUSED */
7618 void
7619 ip_lwput(queue_t *q, mblk_t *mp)
7620 {
7621 	freemsg(mp);
7622 }
7623 
7624 /*
7625  * Move the first hop in any source route to ipha_dst and remove that part of
7626  * the source route.  Called by other protocols.  Errors in option formatting
7627  * are ignored - will be handled by ip_wput_options Return the final
7628  * destination (either ipha_dst or the last entry in a source route.)
7629  */
7630 ipaddr_t
7631 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7632 {
7633 	ipoptp_t	opts;
7634 	uchar_t		*opt;
7635 	uint8_t		optval;
7636 	uint8_t		optlen;
7637 	ipaddr_t	dst;
7638 	int		i;
7639 	ire_t		*ire;
7640 	ip_stack_t	*ipst = ns->netstack_ip;
7641 
7642 	ip2dbg(("ip_massage_options\n"));
7643 	dst = ipha->ipha_dst;
7644 	for (optval = ipoptp_first(&opts, ipha);
7645 	    optval != IPOPT_EOL;
7646 	    optval = ipoptp_next(&opts)) {
7647 		opt = opts.ipoptp_cur;
7648 		switch (optval) {
7649 			uint8_t off;
7650 		case IPOPT_SSRR:
7651 		case IPOPT_LSRR:
7652 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7653 				ip1dbg(("ip_massage_options: bad src route\n"));
7654 				break;
7655 			}
7656 			optlen = opts.ipoptp_len;
7657 			off = opt[IPOPT_OFFSET];
7658 			off--;
7659 		redo_srr:
7660 			if (optlen < IP_ADDR_LEN ||
7661 			    off > optlen - IP_ADDR_LEN) {
7662 				/* End of source route */
7663 				ip1dbg(("ip_massage_options: end of SR\n"));
7664 				break;
7665 			}
7666 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7667 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7668 			    ntohl(dst)));
7669 			/*
7670 			 * Check if our address is present more than
7671 			 * once as consecutive hops in source route.
7672 			 * XXX verify per-interface ip_forwarding
7673 			 * for source route?
7674 			 */
7675 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7676 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7677 			if (ire != NULL) {
7678 				ire_refrele(ire);
7679 				off += IP_ADDR_LEN;
7680 				goto redo_srr;
7681 			}
7682 			if (dst == htonl(INADDR_LOOPBACK)) {
7683 				ip1dbg(("ip_massage_options: loopback addr in "
7684 				    "source route!\n"));
7685 				break;
7686 			}
7687 			/*
7688 			 * Update ipha_dst to be the first hop and remove the
7689 			 * first hop from the source route (by overwriting
7690 			 * part of the option with NOP options).
7691 			 */
7692 			ipha->ipha_dst = dst;
7693 			/* Put the last entry in dst */
7694 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7695 			    3;
7696 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7697 
7698 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7699 			    ntohl(dst)));
7700 			/* Move down and overwrite */
7701 			opt[IP_ADDR_LEN] = opt[0];
7702 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7703 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7704 			for (i = 0; i < IP_ADDR_LEN; i++)
7705 				opt[i] = IPOPT_NOP;
7706 			break;
7707 		}
7708 	}
7709 	return (dst);
7710 }
7711 
7712 /*
7713  * Return the network mask
7714  * associated with the specified address.
7715  */
7716 ipaddr_t
7717 ip_net_mask(ipaddr_t addr)
7718 {
7719 	uchar_t	*up = (uchar_t *)&addr;
7720 	ipaddr_t mask = 0;
7721 	uchar_t	*maskp = (uchar_t *)&mask;
7722 
7723 #if defined(__i386) || defined(__amd64)
7724 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7725 #endif
7726 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7727 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7728 #endif
7729 	if (CLASSD(addr)) {
7730 		maskp[0] = 0xF0;
7731 		return (mask);
7732 	}
7733 
7734 	/* We assume Class E default netmask to be 32 */
7735 	if (CLASSE(addr))
7736 		return (0xffffffffU);
7737 
7738 	if (addr == 0)
7739 		return (0);
7740 	maskp[0] = 0xFF;
7741 	if ((up[0] & 0x80) == 0)
7742 		return (mask);
7743 
7744 	maskp[1] = 0xFF;
7745 	if ((up[0] & 0xC0) == 0x80)
7746 		return (mask);
7747 
7748 	maskp[2] = 0xFF;
7749 	if ((up[0] & 0xE0) == 0xC0)
7750 		return (mask);
7751 
7752 	/* Otherwise return no mask */
7753 	return ((ipaddr_t)0);
7754 }
7755 
7756 /*
7757  * Helper ill lookup function used by IPsec.
7758  */
7759 ill_t *
7760 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7761 {
7762 	ill_t *ret_ill;
7763 
7764 	ASSERT(ifindex != 0);
7765 
7766 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7767 	    ipst);
7768 	if (ret_ill == NULL) {
7769 		if (isv6) {
7770 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7771 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7772 			    ifindex));
7773 		} else {
7774 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7775 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7776 			    ifindex));
7777 		}
7778 		freemsg(first_mp);
7779 		return (NULL);
7780 	}
7781 	return (ret_ill);
7782 }
7783 
7784 /*
7785  * IPv4 -
7786  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7787  * out a packet to a destination address for which we do not have specific
7788  * (or sufficient) routing information.
7789  *
7790  * NOTE : These are the scopes of some of the variables that point at IRE,
7791  *	  which needs to be followed while making any future modifications
7792  *	  to avoid memory leaks.
7793  *
7794  *	- ire and sire are the entries looked up initially by
7795  *	  ire_ftable_lookup.
7796  *	- ipif_ire is used to hold the interface ire associated with
7797  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7798  *	  it before branching out to error paths.
7799  *	- save_ire is initialized before ire_create, so that ire returned
7800  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7801  *	  before breaking out of the switch.
7802  *
7803  *	Thus on failures, we have to REFRELE only ire and sire, if they
7804  *	are not NULL.
7805  */
7806 void
7807 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7808     zoneid_t zoneid, ip_stack_t *ipst)
7809 {
7810 	areq_t	*areq;
7811 	ipaddr_t gw = 0;
7812 	ire_t	*ire = NULL;
7813 	mblk_t	*res_mp;
7814 	ipaddr_t *addrp;
7815 	ipaddr_t nexthop_addr;
7816 	ipif_t  *src_ipif = NULL;
7817 	ill_t	*dst_ill = NULL;
7818 	ipha_t  *ipha;
7819 	ire_t	*sire = NULL;
7820 	mblk_t	*first_mp;
7821 	ire_t	*save_ire;
7822 	ushort_t ire_marks = 0;
7823 	boolean_t mctl_present;
7824 	ipsec_out_t *io;
7825 	mblk_t	*saved_mp;
7826 	mblk_t	*copy_mp = NULL;
7827 	mblk_t	*xmit_mp = NULL;
7828 	ipaddr_t save_dst;
7829 	uint32_t multirt_flags =
7830 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7831 	boolean_t multirt_is_resolvable;
7832 	boolean_t multirt_resolve_next;
7833 	boolean_t unspec_src;
7834 	boolean_t ip_nexthop = B_FALSE;
7835 	tsol_ire_gw_secattr_t *attrp = NULL;
7836 	tsol_gcgrp_t *gcgrp = NULL;
7837 	tsol_gcgrp_addr_t ga;
7838 	int multirt_res_failures = 0;
7839 	int multirt_res_attempts = 0;
7840 	int multirt_already_resolved = 0;
7841 	boolean_t multirt_no_icmp_error = B_FALSE;
7842 
7843 	if (ip_debug > 2) {
7844 		/* ip1dbg */
7845 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7846 	}
7847 
7848 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7849 	if (mctl_present) {
7850 		io = (ipsec_out_t *)first_mp->b_rptr;
7851 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7852 		ASSERT(zoneid == io->ipsec_out_zoneid);
7853 		ASSERT(zoneid != ALL_ZONES);
7854 	}
7855 
7856 	ipha = (ipha_t *)mp->b_rptr;
7857 
7858 	/* All multicast lookups come through ip_newroute_ipif() */
7859 	if (CLASSD(dst)) {
7860 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7861 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7862 		freemsg(first_mp);
7863 		return;
7864 	}
7865 
7866 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7867 		ip_nexthop = B_TRUE;
7868 		nexthop_addr = io->ipsec_out_nexthop_addr;
7869 	}
7870 	/*
7871 	 * If this IRE is created for forwarding or it is not for
7872 	 * traffic for congestion controlled protocols, mark it as temporary.
7873 	 */
7874 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7875 		ire_marks |= IRE_MARK_TEMPORARY;
7876 
7877 	/*
7878 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7879 	 * chain until it gets the most specific information available.
7880 	 * For example, we know that there is no IRE_CACHE for this dest,
7881 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7882 	 * ire_ftable_lookup will look up the gateway, etc.
7883 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7884 	 * to the destination, of equal netmask length in the forward table,
7885 	 * will be recursively explored. If no information is available
7886 	 * for the final gateway of that route, we force the returned ire
7887 	 * to be equal to sire using MATCH_IRE_PARENT.
7888 	 * At least, in this case we have a starting point (in the buckets)
7889 	 * to look for other routes to the destination in the forward table.
7890 	 * This is actually used only for multirouting, where a list
7891 	 * of routes has to be processed in sequence.
7892 	 *
7893 	 * In the process of coming up with the most specific information,
7894 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7895 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7896 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7897 	 * Two caveats when handling incomplete ire's in ip_newroute:
7898 	 * - we should be careful when accessing its ire_nce (specifically
7899 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7900 	 * - not all legacy code path callers are prepared to handle
7901 	 *   incomplete ire's, so we should not create/add incomplete
7902 	 *   ire_cache entries here. (See discussion about temporary solution
7903 	 *   further below).
7904 	 *
7905 	 * In order to minimize packet dropping, and to preserve existing
7906 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7907 	 * gateway, and instead use the IF_RESOLVER ire to send out
7908 	 * another request to ARP (this is achieved by passing the
7909 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7910 	 * arp response comes back in ip_wput_nondata, we will create
7911 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7912 	 *
7913 	 * Note that this is a temporary solution; the correct solution is
7914 	 * to create an incomplete  per-dst ire_cache entry, and send the
7915 	 * packet out when the gw's nce is resolved. In order to achieve this,
7916 	 * all packet processing must have been completed prior to calling
7917 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7918 	 * to be modified to accomodate this solution.
7919 	 */
7920 	if (ip_nexthop) {
7921 		/*
7922 		 * The first time we come here, we look for an IRE_INTERFACE
7923 		 * entry for the specified nexthop, set the dst to be the
7924 		 * nexthop address and create an IRE_CACHE entry for the
7925 		 * nexthop. The next time around, we are able to find an
7926 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7927 		 * nexthop address and create an IRE_CACHE entry for the
7928 		 * destination address via the specified nexthop.
7929 		 */
7930 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7931 		    msg_getlabel(mp), ipst);
7932 		if (ire != NULL) {
7933 			gw = nexthop_addr;
7934 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7935 		} else {
7936 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7937 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7938 			    msg_getlabel(mp),
7939 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7940 			    ipst);
7941 			if (ire != NULL) {
7942 				dst = nexthop_addr;
7943 			}
7944 		}
7945 	} else {
7946 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7947 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
7948 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7949 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7950 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7951 		    ipst);
7952 	}
7953 
7954 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7955 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7956 
7957 	/*
7958 	 * This loop is run only once in most cases.
7959 	 * We loop to resolve further routes only when the destination
7960 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7961 	 */
7962 	do {
7963 		/* Clear the previous iteration's values */
7964 		if (src_ipif != NULL) {
7965 			ipif_refrele(src_ipif);
7966 			src_ipif = NULL;
7967 		}
7968 		if (dst_ill != NULL) {
7969 			ill_refrele(dst_ill);
7970 			dst_ill = NULL;
7971 		}
7972 
7973 		multirt_resolve_next = B_FALSE;
7974 		/*
7975 		 * We check if packets have to be multirouted.
7976 		 * In this case, given the current <ire, sire> couple,
7977 		 * we look for the next suitable <ire, sire>.
7978 		 * This check is done in ire_multirt_lookup(),
7979 		 * which applies various criteria to find the next route
7980 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7981 		 * unchanged if it detects it has not been tried yet.
7982 		 */
7983 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7984 			ip3dbg(("ip_newroute: starting next_resolution "
7985 			    "with first_mp %p, tag %d\n",
7986 			    (void *)first_mp,
7987 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7988 
7989 			ASSERT(sire != NULL);
7990 			multirt_is_resolvable =
7991 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7992 			    &multirt_already_resolved, msg_getlabel(mp), ipst);
7993 
7994 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7995 			    "multirt_already_resolved %d, "
7996 			    "multirt_res_attempts %d, multirt_res_failures %d, "
7997 			    "ire %p, sire %p\n", multirt_is_resolvable,
7998 			    multirt_already_resolved, multirt_res_attempts,
7999 			    multirt_res_failures, (void *)ire, (void *)sire));
8000 
8001 			if (!multirt_is_resolvable) {
8002 				/*
8003 				 * No more multirt route to resolve; give up
8004 				 * (all routes resolved or no more
8005 				 * resolvable routes).
8006 				 */
8007 				if (ire != NULL) {
8008 					ire_refrele(ire);
8009 					ire = NULL;
8010 				}
8011 				/*
8012 				 * Generate ICMP error only if all attempts to
8013 				 * resolve multirt route failed and there is no
8014 				 * already resolved one.  Don't generate ICMP
8015 				 * error when:
8016 				 *
8017 				 *  1) there was no attempt to resolve
8018 				 *  2) at least one attempt passed
8019 				 *  3) a multirt route is already resolved
8020 				 *
8021 				 *  Case 1) may occur due to multiple
8022 				 *    resolution attempts during single
8023 				 *    ip_multirt_resolution_interval.
8024 				 *
8025 				 *  Case 2-3) means that CGTP destination is
8026 				 *    reachable via one link so we don't want to
8027 				 *    generate ICMP host unreachable error.
8028 				 */
8029 				if (multirt_res_attempts == 0 ||
8030 				    multirt_res_failures <
8031 				    multirt_res_attempts ||
8032 				    multirt_already_resolved > 0)
8033 					multirt_no_icmp_error = B_TRUE;
8034 			} else {
8035 				ASSERT(sire != NULL);
8036 				ASSERT(ire != NULL);
8037 
8038 				multirt_res_attempts++;
8039 			}
8040 		}
8041 
8042 		if (ire == NULL) {
8043 			if (ip_debug > 3) {
8044 				/* ip2dbg */
8045 				pr_addr_dbg("ip_newroute: "
8046 				    "can't resolve %s\n", AF_INET, &dst);
8047 			}
8048 			ip3dbg(("ip_newroute: "
8049 			    "ire %p, sire %p, multirt_no_icmp_error %d\n",
8050 			    (void *)ire, (void *)sire,
8051 			    (int)multirt_no_icmp_error));
8052 
8053 			if (sire != NULL) {
8054 				ire_refrele(sire);
8055 				sire = NULL;
8056 			}
8057 
8058 			if (multirt_no_icmp_error) {
8059 				/* There is no need to report an ICMP error. */
8060 				MULTIRT_DEBUG_UNTAG(first_mp);
8061 				freemsg(first_mp);
8062 				return;
8063 			}
8064 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8065 			    RTA_DST, ipst);
8066 			goto icmp_err_ret;
8067 		}
8068 
8069 		/*
8070 		 * Verify that the returned IRE does not have either
8071 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8072 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8073 		 */
8074 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8075 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8076 			goto icmp_err_ret;
8077 		}
8078 		/*
8079 		 * Increment the ire_ob_pkt_count field for ire if it is an
8080 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8081 		 * increment the same for the parent IRE, sire, if it is some
8082 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8083 		 */
8084 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8085 			UPDATE_OB_PKT_COUNT(ire);
8086 			ire->ire_last_used_time = lbolt;
8087 		}
8088 
8089 		if (sire != NULL) {
8090 			gw = sire->ire_gateway_addr;
8091 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8092 			    IRE_INTERFACE)) == 0);
8093 			UPDATE_OB_PKT_COUNT(sire);
8094 			sire->ire_last_used_time = lbolt;
8095 		}
8096 		/*
8097 		 * We have a route to reach the destination.  Find the
8098 		 * appropriate ill, then get a source address using
8099 		 * ipif_select_source().
8100 		 *
8101 		 * If we are here trying to create an IRE_CACHE for an offlink
8102 		 * destination and have an IRE_CACHE entry for VNI, then use
8103 		 * ire_stq instead since VNI's queue is a black hole.
8104 		 */
8105 		if ((ire->ire_type == IRE_CACHE) &&
8106 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8107 			dst_ill = ire->ire_stq->q_ptr;
8108 			ill_refhold(dst_ill);
8109 		} else {
8110 			ill_t *ill = ire->ire_ipif->ipif_ill;
8111 
8112 			if (IS_IPMP(ill)) {
8113 				dst_ill =
8114 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8115 			} else {
8116 				dst_ill = ill;
8117 				ill_refhold(dst_ill);
8118 			}
8119 		}
8120 
8121 		if (dst_ill == NULL) {
8122 			if (ip_debug > 2) {
8123 				pr_addr_dbg("ip_newroute: no dst "
8124 				    "ill for dst %s\n", AF_INET, &dst);
8125 			}
8126 			goto icmp_err_ret;
8127 		}
8128 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8129 
8130 		/*
8131 		 * Pick the best source address from dst_ill.
8132 		 *
8133 		 * 1) Try to pick the source address from the destination
8134 		 *    route. Clustering assumes that when we have multiple
8135 		 *    prefixes hosted on an interface, the prefix of the
8136 		 *    source address matches the prefix of the destination
8137 		 *    route. We do this only if the address is not
8138 		 *    DEPRECATED.
8139 		 *
8140 		 * 2) If the conn is in a different zone than the ire, we
8141 		 *    need to pick a source address from the right zone.
8142 		 */
8143 		ASSERT(src_ipif == NULL);
8144 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8145 			/*
8146 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8147 			 * Check that the ipif matching the requested source
8148 			 * address still exists.
8149 			 */
8150 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8151 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8152 		}
8153 
8154 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8155 
8156 		if (src_ipif == NULL &&
8157 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8158 			ire_marks |= IRE_MARK_USESRC_CHECK;
8159 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8160 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8161 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8162 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8163 			    ire->ire_zoneid != ALL_ZONES) ||
8164 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8165 				/*
8166 				 * If the destination is reachable via a
8167 				 * given gateway, the selected source address
8168 				 * should be in the same subnet as the gateway.
8169 				 * Otherwise, the destination is not reachable.
8170 				 *
8171 				 * If there are no interfaces on the same subnet
8172 				 * as the destination, ipif_select_source gives
8173 				 * first non-deprecated interface which might be
8174 				 * on a different subnet than the gateway.
8175 				 * This is not desirable. Hence pass the dst_ire
8176 				 * source address to ipif_select_source.
8177 				 * It is sure that the destination is reachable
8178 				 * with the dst_ire source address subnet.
8179 				 * So passing dst_ire source address to
8180 				 * ipif_select_source will make sure that the
8181 				 * selected source will be on the same subnet
8182 				 * as dst_ire source address.
8183 				 */
8184 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8185 
8186 				src_ipif = ipif_select_source(dst_ill, saddr,
8187 				    zoneid);
8188 				if (src_ipif == NULL) {
8189 					/*
8190 					 * In the case of multirouting, it may
8191 					 * happen that ipif_select_source fails
8192 					 * as DAD may disallow use of the
8193 					 * particular source interface.  Anyway,
8194 					 * we need to continue and attempt to
8195 					 * resolve other multirt routes.
8196 					 */
8197 					if ((sire != NULL) &&
8198 					    (sire->ire_flags & RTF_MULTIRT)) {
8199 						ire_refrele(ire);
8200 						ire = NULL;
8201 						multirt_resolve_next = B_TRUE;
8202 						multirt_res_failures++;
8203 						continue;
8204 					}
8205 
8206 					if (ip_debug > 2) {
8207 						pr_addr_dbg("ip_newroute: "
8208 						    "no src for dst %s ",
8209 						    AF_INET, &dst);
8210 						printf("on interface %s\n",
8211 						    dst_ill->ill_name);
8212 					}
8213 					goto icmp_err_ret;
8214 				}
8215 			} else {
8216 				src_ipif = ire->ire_ipif;
8217 				ASSERT(src_ipif != NULL);
8218 				/* hold src_ipif for uniformity */
8219 				ipif_refhold(src_ipif);
8220 			}
8221 		}
8222 
8223 		/*
8224 		 * Assign a source address while we have the conn.
8225 		 * We can't have ip_wput_ire pick a source address when the
8226 		 * packet returns from arp since we need to look at
8227 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8228 		 * going through arp.
8229 		 *
8230 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8231 		 *	  it uses ip6i to store this information.
8232 		 */
8233 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8234 			ipha->ipha_src = src_ipif->ipif_src_addr;
8235 
8236 		if (ip_debug > 3) {
8237 			/* ip2dbg */
8238 			pr_addr_dbg("ip_newroute: first hop %s\n",
8239 			    AF_INET, &gw);
8240 		}
8241 		ip2dbg(("\tire type %s (%d)\n",
8242 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8243 
8244 		/*
8245 		 * The TTL of multirouted packets is bounded by the
8246 		 * ip_multirt_ttl ndd variable.
8247 		 */
8248 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8249 			/* Force TTL of multirouted packets */
8250 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8251 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8252 				ip2dbg(("ip_newroute: forcing multirt TTL "
8253 				    "to %d (was %d), dst 0x%08x\n",
8254 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8255 				    ntohl(sire->ire_addr)));
8256 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8257 			}
8258 		}
8259 		/*
8260 		 * At this point in ip_newroute(), ire is either the
8261 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8262 		 * destination or an IRE_INTERFACE type that should be used
8263 		 * to resolve an on-subnet destination or an on-subnet
8264 		 * next-hop gateway.
8265 		 *
8266 		 * In the IRE_CACHE case, we have the following :
8267 		 *
8268 		 * 1) src_ipif - used for getting a source address.
8269 		 *
8270 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8271 		 *    means packets using this IRE_CACHE will go out on
8272 		 *    dst_ill.
8273 		 *
8274 		 * 3) The IRE sire will point to the prefix that is the
8275 		 *    longest  matching route for the destination. These
8276 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8277 		 *
8278 		 *    The newly created IRE_CACHE entry for the off-subnet
8279 		 *    destination is tied to both the prefix route and the
8280 		 *    interface route used to resolve the next-hop gateway
8281 		 *    via the ire_phandle and ire_ihandle fields,
8282 		 *    respectively.
8283 		 *
8284 		 * In the IRE_INTERFACE case, we have the following :
8285 		 *
8286 		 * 1) src_ipif - used for getting a source address.
8287 		 *
8288 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8289 		 *    means packets using the IRE_CACHE that we will build
8290 		 *    here will go out on dst_ill.
8291 		 *
8292 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8293 		 *    to be created will only be tied to the IRE_INTERFACE
8294 		 *    that was derived from the ire_ihandle field.
8295 		 *
8296 		 *    If sire is non-NULL, it means the destination is
8297 		 *    off-link and we will first create the IRE_CACHE for the
8298 		 *    gateway. Next time through ip_newroute, we will create
8299 		 *    the IRE_CACHE for the final destination as described
8300 		 *    above.
8301 		 *
8302 		 * In both cases, after the current resolution has been
8303 		 * completed (or possibly initialised, in the IRE_INTERFACE
8304 		 * case), the loop may be re-entered to attempt the resolution
8305 		 * of another RTF_MULTIRT route.
8306 		 *
8307 		 * When an IRE_CACHE entry for the off-subnet destination is
8308 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8309 		 * for further processing in emission loops.
8310 		 */
8311 		save_ire = ire;
8312 		switch (ire->ire_type) {
8313 		case IRE_CACHE: {
8314 			ire_t	*ipif_ire;
8315 
8316 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8317 			if (gw == 0)
8318 				gw = ire->ire_gateway_addr;
8319 			/*
8320 			 * We need 3 ire's to create a new cache ire for an
8321 			 * off-link destination from the cache ire of the
8322 			 * gateway.
8323 			 *
8324 			 *	1. The prefix ire 'sire' (Note that this does
8325 			 *	   not apply to the conn_nexthop_set case)
8326 			 *	2. The cache ire of the gateway 'ire'
8327 			 *	3. The interface ire 'ipif_ire'
8328 			 *
8329 			 * We have (1) and (2). We lookup (3) below.
8330 			 *
8331 			 * If there is no interface route to the gateway,
8332 			 * it is a race condition, where we found the cache
8333 			 * but the interface route has been deleted.
8334 			 */
8335 			if (ip_nexthop) {
8336 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8337 			} else {
8338 				ipif_ire =
8339 				    ire_ihandle_lookup_offlink(ire, sire);
8340 			}
8341 			if (ipif_ire == NULL) {
8342 				ip1dbg(("ip_newroute: "
8343 				    "ire_ihandle_lookup_offlink failed\n"));
8344 				goto icmp_err_ret;
8345 			}
8346 
8347 			/*
8348 			 * Check cached gateway IRE for any security
8349 			 * attributes; if found, associate the gateway
8350 			 * credentials group to the destination IRE.
8351 			 */
8352 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8353 				mutex_enter(&attrp->igsa_lock);
8354 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8355 					GCGRP_REFHOLD(gcgrp);
8356 				mutex_exit(&attrp->igsa_lock);
8357 			}
8358 
8359 			/*
8360 			 * XXX For the source of the resolver mp,
8361 			 * we are using the same DL_UNITDATA_REQ
8362 			 * (from save_ire->ire_nce->nce_res_mp)
8363 			 * though the save_ire is not pointing at the same ill.
8364 			 * This is incorrect. We need to send it up to the
8365 			 * resolver to get the right res_mp. For ethernets
8366 			 * this may be okay (ill_type == DL_ETHER).
8367 			 */
8368 
8369 			ire = ire_create(
8370 			    (uchar_t *)&dst,		/* dest address */
8371 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8372 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8373 			    (uchar_t *)&gw,		/* gateway address */
8374 			    &save_ire->ire_max_frag,
8375 			    save_ire->ire_nce,		/* src nce */
8376 			    dst_ill->ill_rq,		/* recv-from queue */
8377 			    dst_ill->ill_wq,		/* send-to queue */
8378 			    IRE_CACHE,			/* IRE type */
8379 			    src_ipif,
8380 			    (sire != NULL) ?
8381 			    sire->ire_mask : 0, 	/* Parent mask */
8382 			    (sire != NULL) ?
8383 			    sire->ire_phandle : 0,	/* Parent handle */
8384 			    ipif_ire->ire_ihandle,	/* Interface handle */
8385 			    (sire != NULL) ? (sire->ire_flags &
8386 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8387 			    (sire != NULL) ?
8388 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8389 			    NULL,
8390 			    gcgrp,
8391 			    ipst);
8392 
8393 			if (ire == NULL) {
8394 				if (gcgrp != NULL) {
8395 					GCGRP_REFRELE(gcgrp);
8396 					gcgrp = NULL;
8397 				}
8398 				ire_refrele(ipif_ire);
8399 				ire_refrele(save_ire);
8400 				break;
8401 			}
8402 
8403 			/* reference now held by IRE */
8404 			gcgrp = NULL;
8405 
8406 			ire->ire_marks |= ire_marks;
8407 
8408 			/*
8409 			 * Prevent sire and ipif_ire from getting deleted.
8410 			 * The newly created ire is tied to both of them via
8411 			 * the phandle and ihandle respectively.
8412 			 */
8413 			if (sire != NULL) {
8414 				IRB_REFHOLD(sire->ire_bucket);
8415 				/* Has it been removed already ? */
8416 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8417 					IRB_REFRELE(sire->ire_bucket);
8418 					ire_refrele(ipif_ire);
8419 					ire_refrele(save_ire);
8420 					break;
8421 				}
8422 			}
8423 
8424 			IRB_REFHOLD(ipif_ire->ire_bucket);
8425 			/* Has it been removed already ? */
8426 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8427 				IRB_REFRELE(ipif_ire->ire_bucket);
8428 				if (sire != NULL)
8429 					IRB_REFRELE(sire->ire_bucket);
8430 				ire_refrele(ipif_ire);
8431 				ire_refrele(save_ire);
8432 				break;
8433 			}
8434 
8435 			xmit_mp = first_mp;
8436 			/*
8437 			 * In the case of multirouting, a copy
8438 			 * of the packet is done before its sending.
8439 			 * The copy is used to attempt another
8440 			 * route resolution, in a next loop.
8441 			 */
8442 			if (ire->ire_flags & RTF_MULTIRT) {
8443 				copy_mp = copymsg(first_mp);
8444 				if (copy_mp != NULL) {
8445 					xmit_mp = copy_mp;
8446 					MULTIRT_DEBUG_TAG(first_mp);
8447 				}
8448 			}
8449 
8450 			ire_add_then_send(q, ire, xmit_mp);
8451 			ire_refrele(save_ire);
8452 
8453 			/* Assert that sire is not deleted yet. */
8454 			if (sire != NULL) {
8455 				ASSERT(sire->ire_ptpn != NULL);
8456 				IRB_REFRELE(sire->ire_bucket);
8457 			}
8458 
8459 			/* Assert that ipif_ire is not deleted yet. */
8460 			ASSERT(ipif_ire->ire_ptpn != NULL);
8461 			IRB_REFRELE(ipif_ire->ire_bucket);
8462 			ire_refrele(ipif_ire);
8463 
8464 			/*
8465 			 * If copy_mp is not NULL, multirouting was
8466 			 * requested. We loop to initiate a next
8467 			 * route resolution attempt, starting from sire.
8468 			 */
8469 			if (copy_mp != NULL) {
8470 				/*
8471 				 * Search for the next unresolved
8472 				 * multirt route.
8473 				 */
8474 				copy_mp = NULL;
8475 				ipif_ire = NULL;
8476 				ire = NULL;
8477 				multirt_resolve_next = B_TRUE;
8478 				continue;
8479 			}
8480 			if (sire != NULL)
8481 				ire_refrele(sire);
8482 			ipif_refrele(src_ipif);
8483 			ill_refrele(dst_ill);
8484 			return;
8485 		}
8486 		case IRE_IF_NORESOLVER: {
8487 			if (dst_ill->ill_resolver_mp == NULL) {
8488 				ip1dbg(("ip_newroute: dst_ill %p "
8489 				    "for IRE_IF_NORESOLVER ire %p has "
8490 				    "no ill_resolver_mp\n",
8491 				    (void *)dst_ill, (void *)ire));
8492 				break;
8493 			}
8494 
8495 			/*
8496 			 * TSol note: We are creating the ire cache for the
8497 			 * destination 'dst'. If 'dst' is offlink, going
8498 			 * through the first hop 'gw', the security attributes
8499 			 * of 'dst' must be set to point to the gateway
8500 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8501 			 * is possible that 'dst' is a potential gateway that is
8502 			 * referenced by some route that has some security
8503 			 * attributes. Thus in the former case, we need to do a
8504 			 * gcgrp_lookup of 'gw' while in the latter case we
8505 			 * need to do gcgrp_lookup of 'dst' itself.
8506 			 */
8507 			ga.ga_af = AF_INET;
8508 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8509 			    &ga.ga_addr);
8510 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8511 
8512 			ire = ire_create(
8513 			    (uchar_t *)&dst,		/* dest address */
8514 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8515 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8516 			    (uchar_t *)&gw,		/* gateway address */
8517 			    &save_ire->ire_max_frag,
8518 			    NULL,			/* no src nce */
8519 			    dst_ill->ill_rq,		/* recv-from queue */
8520 			    dst_ill->ill_wq,		/* send-to queue */
8521 			    IRE_CACHE,
8522 			    src_ipif,
8523 			    save_ire->ire_mask,		/* Parent mask */
8524 			    (sire != NULL) ?		/* Parent handle */
8525 			    sire->ire_phandle : 0,
8526 			    save_ire->ire_ihandle,	/* Interface handle */
8527 			    (sire != NULL) ? sire->ire_flags &
8528 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8529 			    &(save_ire->ire_uinfo),
8530 			    NULL,
8531 			    gcgrp,
8532 			    ipst);
8533 
8534 			if (ire == NULL) {
8535 				if (gcgrp != NULL) {
8536 					GCGRP_REFRELE(gcgrp);
8537 					gcgrp = NULL;
8538 				}
8539 				ire_refrele(save_ire);
8540 				break;
8541 			}
8542 
8543 			/* reference now held by IRE */
8544 			gcgrp = NULL;
8545 
8546 			ire->ire_marks |= ire_marks;
8547 
8548 			/* Prevent save_ire from getting deleted */
8549 			IRB_REFHOLD(save_ire->ire_bucket);
8550 			/* Has it been removed already ? */
8551 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8552 				IRB_REFRELE(save_ire->ire_bucket);
8553 				ire_refrele(save_ire);
8554 				break;
8555 			}
8556 
8557 			/*
8558 			 * In the case of multirouting, a copy
8559 			 * of the packet is made before it is sent.
8560 			 * The copy is used in the next
8561 			 * loop to attempt another resolution.
8562 			 */
8563 			xmit_mp = first_mp;
8564 			if ((sire != NULL) &&
8565 			    (sire->ire_flags & RTF_MULTIRT)) {
8566 				copy_mp = copymsg(first_mp);
8567 				if (copy_mp != NULL) {
8568 					xmit_mp = copy_mp;
8569 					MULTIRT_DEBUG_TAG(first_mp);
8570 				}
8571 			}
8572 			ire_add_then_send(q, ire, xmit_mp);
8573 
8574 			/* Assert that it is not deleted yet. */
8575 			ASSERT(save_ire->ire_ptpn != NULL);
8576 			IRB_REFRELE(save_ire->ire_bucket);
8577 			ire_refrele(save_ire);
8578 
8579 			if (copy_mp != NULL) {
8580 				/*
8581 				 * If we found a (no)resolver, we ignore any
8582 				 * trailing top priority IRE_CACHE in further
8583 				 * loops. This ensures that we do not omit any
8584 				 * (no)resolver.
8585 				 * This IRE_CACHE, if any, will be processed
8586 				 * by another thread entering ip_newroute().
8587 				 * IRE_CACHE entries, if any, will be processed
8588 				 * by another thread entering ip_newroute(),
8589 				 * (upon resolver response, for instance).
8590 				 * This aims to force parallel multirt
8591 				 * resolutions as soon as a packet must be sent.
8592 				 * In the best case, after the tx of only one
8593 				 * packet, all reachable routes are resolved.
8594 				 * Otherwise, the resolution of all RTF_MULTIRT
8595 				 * routes would require several emissions.
8596 				 */
8597 				multirt_flags &= ~MULTIRT_CACHEGW;
8598 
8599 				/*
8600 				 * Search for the next unresolved multirt
8601 				 * route.
8602 				 */
8603 				copy_mp = NULL;
8604 				save_ire = NULL;
8605 				ire = NULL;
8606 				multirt_resolve_next = B_TRUE;
8607 				continue;
8608 			}
8609 
8610 			/*
8611 			 * Don't need sire anymore
8612 			 */
8613 			if (sire != NULL)
8614 				ire_refrele(sire);
8615 
8616 			ipif_refrele(src_ipif);
8617 			ill_refrele(dst_ill);
8618 			return;
8619 		}
8620 		case IRE_IF_RESOLVER:
8621 			/*
8622 			 * We can't build an IRE_CACHE yet, but at least we
8623 			 * found a resolver that can help.
8624 			 */
8625 			res_mp = dst_ill->ill_resolver_mp;
8626 			if (!OK_RESOLVER_MP(res_mp))
8627 				break;
8628 
8629 			/*
8630 			 * To be at this point in the code with a non-zero gw
8631 			 * means that dst is reachable through a gateway that
8632 			 * we have never resolved.  By changing dst to the gw
8633 			 * addr we resolve the gateway first.
8634 			 * When ire_add_then_send() tries to put the IP dg
8635 			 * to dst, it will reenter ip_newroute() at which
8636 			 * time we will find the IRE_CACHE for the gw and
8637 			 * create another IRE_CACHE in case IRE_CACHE above.
8638 			 */
8639 			if (gw != INADDR_ANY) {
8640 				/*
8641 				 * The source ipif that was determined above was
8642 				 * relative to the destination address, not the
8643 				 * gateway's. If src_ipif was not taken out of
8644 				 * the IRE_IF_RESOLVER entry, we'll need to call
8645 				 * ipif_select_source() again.
8646 				 */
8647 				if (src_ipif != ire->ire_ipif) {
8648 					ipif_refrele(src_ipif);
8649 					src_ipif = ipif_select_source(dst_ill,
8650 					    gw, zoneid);
8651 					/*
8652 					 * In the case of multirouting, it may
8653 					 * happen that ipif_select_source fails
8654 					 * as DAD may disallow use of the
8655 					 * particular source interface.  Anyway,
8656 					 * we need to continue and attempt to
8657 					 * resolve other multirt routes.
8658 					 */
8659 					if (src_ipif == NULL) {
8660 						if (sire != NULL &&
8661 						    (sire->ire_flags &
8662 						    RTF_MULTIRT)) {
8663 							ire_refrele(ire);
8664 							ire = NULL;
8665 							multirt_resolve_next =
8666 							    B_TRUE;
8667 							multirt_res_failures++;
8668 							continue;
8669 						}
8670 						if (ip_debug > 2) {
8671 							pr_addr_dbg(
8672 							    "ip_newroute: no "
8673 							    "src for gw %s ",
8674 							    AF_INET, &gw);
8675 							printf("on "
8676 							    "interface %s\n",
8677 							    dst_ill->ill_name);
8678 						}
8679 						goto icmp_err_ret;
8680 					}
8681 				}
8682 				save_dst = dst;
8683 				dst = gw;
8684 				gw = INADDR_ANY;
8685 			}
8686 
8687 			/*
8688 			 * We obtain a partial IRE_CACHE which we will pass
8689 			 * along with the resolver query.  When the response
8690 			 * comes back it will be there ready for us to add.
8691 			 * The ire_max_frag is atomically set under the
8692 			 * irebucket lock in ire_add_v[46].
8693 			 */
8694 
8695 			ire = ire_create_mp(
8696 			    (uchar_t *)&dst,		/* dest address */
8697 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8698 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8699 			    (uchar_t *)&gw,		/* gateway address */
8700 			    NULL,			/* ire_max_frag */
8701 			    NULL,			/* no src nce */
8702 			    dst_ill->ill_rq,		/* recv-from queue */
8703 			    dst_ill->ill_wq,		/* send-to queue */
8704 			    IRE_CACHE,
8705 			    src_ipif,			/* Interface ipif */
8706 			    save_ire->ire_mask,		/* Parent mask */
8707 			    0,
8708 			    save_ire->ire_ihandle,	/* Interface handle */
8709 			    0,				/* flags if any */
8710 			    &(save_ire->ire_uinfo),
8711 			    NULL,
8712 			    NULL,
8713 			    ipst);
8714 
8715 			if (ire == NULL) {
8716 				ire_refrele(save_ire);
8717 				break;
8718 			}
8719 
8720 			if ((sire != NULL) &&
8721 			    (sire->ire_flags & RTF_MULTIRT)) {
8722 				copy_mp = copymsg(first_mp);
8723 				if (copy_mp != NULL)
8724 					MULTIRT_DEBUG_TAG(copy_mp);
8725 			}
8726 
8727 			ire->ire_marks |= ire_marks;
8728 
8729 			/*
8730 			 * Construct message chain for the resolver
8731 			 * of the form:
8732 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8733 			 * Packet could contain a IPSEC_OUT mp.
8734 			 *
8735 			 * NOTE : ire will be added later when the response
8736 			 * comes back from ARP. If the response does not
8737 			 * come back, ARP frees the packet. For this reason,
8738 			 * we can't REFHOLD the bucket of save_ire to prevent
8739 			 * deletions. We may not be able to REFRELE the bucket
8740 			 * if the response never comes back. Thus, before
8741 			 * adding the ire, ire_add_v4 will make sure that the
8742 			 * interface route does not get deleted. This is the
8743 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8744 			 * where we can always prevent deletions because of
8745 			 * the synchronous nature of adding IRES i.e
8746 			 * ire_add_then_send is called after creating the IRE.
8747 			 */
8748 			ASSERT(ire->ire_mp != NULL);
8749 			ire->ire_mp->b_cont = first_mp;
8750 			/* Have saved_mp handy, for cleanup if canput fails */
8751 			saved_mp = mp;
8752 			mp = copyb(res_mp);
8753 			if (mp == NULL) {
8754 				/* Prepare for cleanup */
8755 				mp = saved_mp; /* pkt */
8756 				ire_delete(ire); /* ire_mp */
8757 				ire = NULL;
8758 				ire_refrele(save_ire);
8759 				if (copy_mp != NULL) {
8760 					MULTIRT_DEBUG_UNTAG(copy_mp);
8761 					freemsg(copy_mp);
8762 					copy_mp = NULL;
8763 				}
8764 				break;
8765 			}
8766 			linkb(mp, ire->ire_mp);
8767 
8768 			/*
8769 			 * Fill in the source and dest addrs for the resolver.
8770 			 * NOTE: this depends on memory layouts imposed by
8771 			 * ill_init().
8772 			 */
8773 			areq = (areq_t *)mp->b_rptr;
8774 			addrp = (ipaddr_t *)((char *)areq +
8775 			    areq->areq_sender_addr_offset);
8776 			*addrp = save_ire->ire_src_addr;
8777 
8778 			ire_refrele(save_ire);
8779 			addrp = (ipaddr_t *)((char *)areq +
8780 			    areq->areq_target_addr_offset);
8781 			*addrp = dst;
8782 			/* Up to the resolver. */
8783 			if (canputnext(dst_ill->ill_rq) &&
8784 			    !(dst_ill->ill_arp_closing)) {
8785 				putnext(dst_ill->ill_rq, mp);
8786 				ire = NULL;
8787 				if (copy_mp != NULL) {
8788 					/*
8789 					 * If we found a resolver, we ignore
8790 					 * any trailing top priority IRE_CACHE
8791 					 * in the further loops. This ensures
8792 					 * that we do not omit any resolver.
8793 					 * IRE_CACHE entries, if any, will be
8794 					 * processed next time we enter
8795 					 * ip_newroute().
8796 					 */
8797 					multirt_flags &= ~MULTIRT_CACHEGW;
8798 					/*
8799 					 * Search for the next unresolved
8800 					 * multirt route.
8801 					 */
8802 					first_mp = copy_mp;
8803 					copy_mp = NULL;
8804 					/* Prepare the next resolution loop. */
8805 					mp = first_mp;
8806 					EXTRACT_PKT_MP(mp, first_mp,
8807 					    mctl_present);
8808 					if (mctl_present)
8809 						io = (ipsec_out_t *)
8810 						    first_mp->b_rptr;
8811 					ipha = (ipha_t *)mp->b_rptr;
8812 
8813 					ASSERT(sire != NULL);
8814 
8815 					dst = save_dst;
8816 					multirt_resolve_next = B_TRUE;
8817 					continue;
8818 				}
8819 
8820 				if (sire != NULL)
8821 					ire_refrele(sire);
8822 
8823 				/*
8824 				 * The response will come back in ip_wput
8825 				 * with db_type IRE_DB_TYPE.
8826 				 */
8827 				ipif_refrele(src_ipif);
8828 				ill_refrele(dst_ill);
8829 				return;
8830 			} else {
8831 				/* Prepare for cleanup */
8832 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8833 				    mp);
8834 				mp->b_cont = NULL;
8835 				freeb(mp); /* areq */
8836 				/*
8837 				 * this is an ire that is not added to the
8838 				 * cache. ire_freemblk will handle the release
8839 				 * of any resources associated with the ire.
8840 				 */
8841 				ire_delete(ire); /* ire_mp */
8842 				mp = saved_mp; /* pkt */
8843 				ire = NULL;
8844 				if (copy_mp != NULL) {
8845 					MULTIRT_DEBUG_UNTAG(copy_mp);
8846 					freemsg(copy_mp);
8847 					copy_mp = NULL;
8848 				}
8849 				break;
8850 			}
8851 		default:
8852 			break;
8853 		}
8854 	} while (multirt_resolve_next);
8855 
8856 	ip1dbg(("ip_newroute: dropped\n"));
8857 	/* Did this packet originate externally? */
8858 	if (mp->b_prev) {
8859 		mp->b_next = NULL;
8860 		mp->b_prev = NULL;
8861 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8862 	} else {
8863 		if (dst_ill != NULL) {
8864 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8865 		} else {
8866 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8867 		}
8868 	}
8869 	ASSERT(copy_mp == NULL);
8870 	MULTIRT_DEBUG_UNTAG(first_mp);
8871 	freemsg(first_mp);
8872 	if (ire != NULL)
8873 		ire_refrele(ire);
8874 	if (sire != NULL)
8875 		ire_refrele(sire);
8876 	if (src_ipif != NULL)
8877 		ipif_refrele(src_ipif);
8878 	if (dst_ill != NULL)
8879 		ill_refrele(dst_ill);
8880 	return;
8881 
8882 icmp_err_ret:
8883 	ip1dbg(("ip_newroute: no route\n"));
8884 	if (src_ipif != NULL)
8885 		ipif_refrele(src_ipif);
8886 	if (dst_ill != NULL)
8887 		ill_refrele(dst_ill);
8888 	if (sire != NULL)
8889 		ire_refrele(sire);
8890 	/* Did this packet originate externally? */
8891 	if (mp->b_prev) {
8892 		mp->b_next = NULL;
8893 		mp->b_prev = NULL;
8894 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8895 		q = WR(q);
8896 	} else {
8897 		/*
8898 		 * There is no outgoing ill, so just increment the
8899 		 * system MIB.
8900 		 */
8901 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8902 		/*
8903 		 * Since ip_wput() isn't close to finished, we fill
8904 		 * in enough of the header for credible error reporting.
8905 		 */
8906 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8907 			/* Failed */
8908 			MULTIRT_DEBUG_UNTAG(first_mp);
8909 			freemsg(first_mp);
8910 			if (ire != NULL)
8911 				ire_refrele(ire);
8912 			return;
8913 		}
8914 	}
8915 
8916 	/*
8917 	 * At this point we will have ire only if RTF_BLACKHOLE
8918 	 * or RTF_REJECT flags are set on the IRE. It will not
8919 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8920 	 */
8921 	if (ire != NULL) {
8922 		if (ire->ire_flags & RTF_BLACKHOLE) {
8923 			ire_refrele(ire);
8924 			MULTIRT_DEBUG_UNTAG(first_mp);
8925 			freemsg(first_mp);
8926 			return;
8927 		}
8928 		ire_refrele(ire);
8929 	}
8930 	if (ip_source_routed(ipha, ipst)) {
8931 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8932 		    zoneid, ipst);
8933 		return;
8934 	}
8935 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8936 }
8937 
8938 ip_opt_info_t zero_info;
8939 
8940 /*
8941  * IPv4 -
8942  * ip_newroute_ipif is called by ip_wput_multicast and
8943  * ip_rput_forward_multicast whenever we need to send
8944  * out a packet to a destination address for which we do not have specific
8945  * routing information. It is used when the packet will be sent out
8946  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8947  * socket option is set or icmp error message wants to go out on a particular
8948  * interface for a unicast packet.
8949  *
8950  * In most cases, the destination address is resolved thanks to the ipif
8951  * intrinsic resolver. However, there are some cases where the call to
8952  * ip_newroute_ipif must take into account the potential presence of
8953  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8954  * that uses the interface. This is specified through flags,
8955  * which can be a combination of:
8956  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8957  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8958  *   and flags. Additionally, the packet source address has to be set to
8959  *   the specified address. The caller is thus expected to set this flag
8960  *   if the packet has no specific source address yet.
8961  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8962  *   flag, the resulting ire will inherit the flag. All unresolved routes
8963  *   to the destination must be explored in the same call to
8964  *   ip_newroute_ipif().
8965  */
8966 static void
8967 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8968     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8969 {
8970 	areq_t	*areq;
8971 	ire_t	*ire = NULL;
8972 	mblk_t	*res_mp;
8973 	ipaddr_t *addrp;
8974 	mblk_t *first_mp;
8975 	ire_t	*save_ire = NULL;
8976 	ipif_t	*src_ipif = NULL;
8977 	ushort_t ire_marks = 0;
8978 	ill_t	*dst_ill = NULL;
8979 	ipha_t *ipha;
8980 	mblk_t	*saved_mp;
8981 	ire_t   *fire = NULL;
8982 	mblk_t  *copy_mp = NULL;
8983 	boolean_t multirt_resolve_next;
8984 	boolean_t unspec_src;
8985 	ipaddr_t ipha_dst;
8986 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8987 
8988 	/*
8989 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8990 	 * here for uniformity
8991 	 */
8992 	ipif_refhold(ipif);
8993 
8994 	/*
8995 	 * This loop is run only once in most cases.
8996 	 * We loop to resolve further routes only when the destination
8997 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8998 	 */
8999 	do {
9000 		if (dst_ill != NULL) {
9001 			ill_refrele(dst_ill);
9002 			dst_ill = NULL;
9003 		}
9004 		if (src_ipif != NULL) {
9005 			ipif_refrele(src_ipif);
9006 			src_ipif = NULL;
9007 		}
9008 		multirt_resolve_next = B_FALSE;
9009 
9010 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9011 		    ipif->ipif_ill->ill_name));
9012 
9013 		first_mp = mp;
9014 		if (DB_TYPE(mp) == M_CTL)
9015 			mp = mp->b_cont;
9016 		ipha = (ipha_t *)mp->b_rptr;
9017 
9018 		/*
9019 		 * Save the packet destination address, we may need it after
9020 		 * the packet has been consumed.
9021 		 */
9022 		ipha_dst = ipha->ipha_dst;
9023 
9024 		/*
9025 		 * If the interface is a pt-pt interface we look for an
9026 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9027 		 * local_address and the pt-pt destination address. Otherwise
9028 		 * we just match the local address.
9029 		 * NOTE: dst could be different than ipha->ipha_dst in case
9030 		 * of sending igmp multicast packets over a point-to-point
9031 		 * connection.
9032 		 * Thus we must be careful enough to check ipha_dst to be a
9033 		 * multicast address, otherwise it will take xmit_if path for
9034 		 * multicast packets resulting into kernel stack overflow by
9035 		 * repeated calls to ip_newroute_ipif from ire_send().
9036 		 */
9037 		if (CLASSD(ipha_dst) &&
9038 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9039 			goto err_ret;
9040 		}
9041 
9042 		/*
9043 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9044 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9045 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9046 		 * propagate its flags to the new ire.
9047 		 */
9048 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9049 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9050 			ip2dbg(("ip_newroute_ipif: "
9051 			    "ipif_lookup_multi_ire("
9052 			    "ipif %p, dst %08x) = fire %p\n",
9053 			    (void *)ipif, ntohl(dst), (void *)fire));
9054 		}
9055 
9056 		/*
9057 		 * Note: While we pick a dst_ill we are really only
9058 		 * interested in the ill for load spreading. The source
9059 		 * ipif is determined by source address selection below.
9060 		 */
9061 		if (IS_IPMP(ipif->ipif_ill)) {
9062 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9063 
9064 			if (CLASSD(ipha_dst))
9065 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9066 			else
9067 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9068 		} else {
9069 			dst_ill = ipif->ipif_ill;
9070 			ill_refhold(dst_ill);
9071 		}
9072 
9073 		if (dst_ill == NULL) {
9074 			if (ip_debug > 2) {
9075 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9076 				    "for dst %s\n", AF_INET, &dst);
9077 			}
9078 			goto err_ret;
9079 		}
9080 
9081 		/*
9082 		 * Pick a source address preferring non-deprecated ones.
9083 		 * Unlike ip_newroute, we don't do any source address
9084 		 * selection here since for multicast it really does not help
9085 		 * in inbound load spreading as in the unicast case.
9086 		 */
9087 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9088 		    (fire->ire_flags & RTF_SETSRC)) {
9089 			/*
9090 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9091 			 * on that interface. This ire has RTF_SETSRC flag, so
9092 			 * the source address of the packet must be changed.
9093 			 * Check that the ipif matching the requested source
9094 			 * address still exists.
9095 			 */
9096 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9097 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9098 		}
9099 
9100 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9101 
9102 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9103 		    (IS_IPMP(ipif->ipif_ill) ||
9104 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9105 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9106 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9107 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9108 		    (src_ipif == NULL) &&
9109 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9110 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9111 			if (src_ipif == NULL) {
9112 				if (ip_debug > 2) {
9113 					/* ip1dbg */
9114 					pr_addr_dbg("ip_newroute_ipif: "
9115 					    "no src for dst %s",
9116 					    AF_INET, &dst);
9117 				}
9118 				ip1dbg((" on interface %s\n",
9119 				    dst_ill->ill_name));
9120 				goto err_ret;
9121 			}
9122 			ipif_refrele(ipif);
9123 			ipif = src_ipif;
9124 			ipif_refhold(ipif);
9125 		}
9126 		if (src_ipif == NULL) {
9127 			src_ipif = ipif;
9128 			ipif_refhold(src_ipif);
9129 		}
9130 
9131 		/*
9132 		 * Assign a source address while we have the conn.
9133 		 * We can't have ip_wput_ire pick a source address when the
9134 		 * packet returns from arp since conn_unspec_src might be set
9135 		 * and we lose the conn when going through arp.
9136 		 */
9137 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9138 			ipha->ipha_src = src_ipif->ipif_src_addr;
9139 
9140 		/*
9141 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9142 		 * that the outgoing interface does not have an interface ire.
9143 		 */
9144 		if (CLASSD(ipha_dst) && (connp == NULL ||
9145 		    connp->conn_outgoing_ill == NULL) &&
9146 		    infop->ip_opt_ill_index == 0) {
9147 			/* ipif_to_ire returns an held ire */
9148 			ire = ipif_to_ire(ipif);
9149 			if (ire == NULL)
9150 				goto err_ret;
9151 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9152 				goto err_ret;
9153 			save_ire = ire;
9154 
9155 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9156 			    "flags %04x\n",
9157 			    (void *)ire, (void *)ipif, flags));
9158 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9159 			    (fire->ire_flags & RTF_MULTIRT)) {
9160 				/*
9161 				 * As requested by flags, an IRE_OFFSUBNET was
9162 				 * looked up on that interface. This ire has
9163 				 * RTF_MULTIRT flag, so the resolution loop will
9164 				 * be re-entered to resolve additional routes on
9165 				 * other interfaces. For that purpose, a copy of
9166 				 * the packet is performed at this point.
9167 				 */
9168 				fire->ire_last_used_time = lbolt;
9169 				copy_mp = copymsg(first_mp);
9170 				if (copy_mp) {
9171 					MULTIRT_DEBUG_TAG(copy_mp);
9172 				}
9173 			}
9174 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9175 			    (fire->ire_flags & RTF_SETSRC)) {
9176 				/*
9177 				 * As requested by flags, an IRE_OFFSUBET was
9178 				 * looked up on that interface. This ire has
9179 				 * RTF_SETSRC flag, so the source address of the
9180 				 * packet must be changed.
9181 				 */
9182 				ipha->ipha_src = fire->ire_src_addr;
9183 			}
9184 		} else {
9185 			/*
9186 			 * The only ways we can come here are:
9187 			 * 1) IP_BOUND_IF socket option is set
9188 			 * 2) SO_DONTROUTE socket option is set
9189 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9190 			 * In all cases, the new ire will not be added
9191 			 * into cache table.
9192 			 */
9193 			ASSERT(connp == NULL || connp->conn_dontroute ||
9194 			    connp->conn_outgoing_ill != NULL ||
9195 			    infop->ip_opt_ill_index != 0);
9196 			ire_marks |= IRE_MARK_NOADD;
9197 		}
9198 
9199 		switch (ipif->ipif_net_type) {
9200 		case IRE_IF_NORESOLVER: {
9201 			/* We have what we need to build an IRE_CACHE. */
9202 
9203 			if (dst_ill->ill_resolver_mp == NULL) {
9204 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9205 				    "for IRE_IF_NORESOLVER ire %p has "
9206 				    "no ill_resolver_mp\n",
9207 				    (void *)dst_ill, (void *)ire));
9208 				break;
9209 			}
9210 
9211 			/*
9212 			 * The new ire inherits the IRE_OFFSUBNET flags
9213 			 * and source address, if this was requested.
9214 			 */
9215 			ire = ire_create(
9216 			    (uchar_t *)&dst,		/* dest address */
9217 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9218 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9219 			    NULL,			/* gateway address */
9220 			    &ipif->ipif_mtu,
9221 			    NULL,			/* no src nce */
9222 			    dst_ill->ill_rq,		/* recv-from queue */
9223 			    dst_ill->ill_wq,		/* send-to queue */
9224 			    IRE_CACHE,
9225 			    src_ipif,
9226 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9227 			    (fire != NULL) ?		/* Parent handle */
9228 			    fire->ire_phandle : 0,
9229 			    (save_ire != NULL) ?	/* Interface handle */
9230 			    save_ire->ire_ihandle : 0,
9231 			    (fire != NULL) ?
9232 			    (fire->ire_flags &
9233 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9234 			    (save_ire == NULL ? &ire_uinfo_null :
9235 			    &save_ire->ire_uinfo),
9236 			    NULL,
9237 			    NULL,
9238 			    ipst);
9239 
9240 			if (ire == NULL) {
9241 				if (save_ire != NULL)
9242 					ire_refrele(save_ire);
9243 				break;
9244 			}
9245 
9246 			ire->ire_marks |= ire_marks;
9247 
9248 			/*
9249 			 * If IRE_MARK_NOADD is set then we need to convert
9250 			 * the max_fragp to a useable value now. This is
9251 			 * normally done in ire_add_v[46]. We also need to
9252 			 * associate the ire with an nce (normally would be
9253 			 * done in ip_wput_nondata()).
9254 			 *
9255 			 * Note that IRE_MARK_NOADD packets created here
9256 			 * do not have a non-null ire_mp pointer. The null
9257 			 * value of ire_bucket indicates that they were
9258 			 * never added.
9259 			 */
9260 			if (ire->ire_marks & IRE_MARK_NOADD) {
9261 				uint_t  max_frag;
9262 
9263 				max_frag = *ire->ire_max_fragp;
9264 				ire->ire_max_fragp = NULL;
9265 				ire->ire_max_frag = max_frag;
9266 
9267 				if ((ire->ire_nce = ndp_lookup_v4(
9268 				    ire_to_ill(ire),
9269 				    (ire->ire_gateway_addr != INADDR_ANY ?
9270 				    &ire->ire_gateway_addr : &ire->ire_addr),
9271 				    B_FALSE)) == NULL) {
9272 					if (save_ire != NULL)
9273 						ire_refrele(save_ire);
9274 					break;
9275 				}
9276 				ASSERT(ire->ire_nce->nce_state ==
9277 				    ND_REACHABLE);
9278 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9279 			}
9280 
9281 			/* Prevent save_ire from getting deleted */
9282 			if (save_ire != NULL) {
9283 				IRB_REFHOLD(save_ire->ire_bucket);
9284 				/* Has it been removed already ? */
9285 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9286 					IRB_REFRELE(save_ire->ire_bucket);
9287 					ire_refrele(save_ire);
9288 					break;
9289 				}
9290 			}
9291 
9292 			ire_add_then_send(q, ire, first_mp);
9293 
9294 			/* Assert that save_ire is not deleted yet. */
9295 			if (save_ire != NULL) {
9296 				ASSERT(save_ire->ire_ptpn != NULL);
9297 				IRB_REFRELE(save_ire->ire_bucket);
9298 				ire_refrele(save_ire);
9299 				save_ire = NULL;
9300 			}
9301 			if (fire != NULL) {
9302 				ire_refrele(fire);
9303 				fire = NULL;
9304 			}
9305 
9306 			/*
9307 			 * the resolution loop is re-entered if this
9308 			 * was requested through flags and if we
9309 			 * actually are in a multirouting case.
9310 			 */
9311 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9312 				boolean_t need_resolve =
9313 				    ire_multirt_need_resolve(ipha_dst,
9314 				    msg_getlabel(copy_mp), ipst);
9315 				if (!need_resolve) {
9316 					MULTIRT_DEBUG_UNTAG(copy_mp);
9317 					freemsg(copy_mp);
9318 					copy_mp = NULL;
9319 				} else {
9320 					/*
9321 					 * ipif_lookup_group() calls
9322 					 * ire_lookup_multi() that uses
9323 					 * ire_ftable_lookup() to find
9324 					 * an IRE_INTERFACE for the group.
9325 					 * In the multirt case,
9326 					 * ire_lookup_multi() then invokes
9327 					 * ire_multirt_lookup() to find
9328 					 * the next resolvable ire.
9329 					 * As a result, we obtain an new
9330 					 * interface, derived from the
9331 					 * next ire.
9332 					 */
9333 					ipif_refrele(ipif);
9334 					ipif = ipif_lookup_group(ipha_dst,
9335 					    zoneid, ipst);
9336 					ip2dbg(("ip_newroute_ipif: "
9337 					    "multirt dst %08x, ipif %p\n",
9338 					    htonl(dst), (void *)ipif));
9339 					if (ipif != NULL) {
9340 						mp = copy_mp;
9341 						copy_mp = NULL;
9342 						multirt_resolve_next = B_TRUE;
9343 						continue;
9344 					} else {
9345 						freemsg(copy_mp);
9346 					}
9347 				}
9348 			}
9349 			if (ipif != NULL)
9350 				ipif_refrele(ipif);
9351 			ill_refrele(dst_ill);
9352 			ipif_refrele(src_ipif);
9353 			return;
9354 		}
9355 		case IRE_IF_RESOLVER:
9356 			/*
9357 			 * We can't build an IRE_CACHE yet, but at least
9358 			 * we found a resolver that can help.
9359 			 */
9360 			res_mp = dst_ill->ill_resolver_mp;
9361 			if (!OK_RESOLVER_MP(res_mp))
9362 				break;
9363 
9364 			/*
9365 			 * We obtain a partial IRE_CACHE which we will pass
9366 			 * along with the resolver query.  When the response
9367 			 * comes back it will be there ready for us to add.
9368 			 * The new ire inherits the IRE_OFFSUBNET flags
9369 			 * and source address, if this was requested.
9370 			 * The ire_max_frag is atomically set under the
9371 			 * irebucket lock in ire_add_v[46]. Only in the
9372 			 * case of IRE_MARK_NOADD, we set it here itself.
9373 			 */
9374 			ire = ire_create_mp(
9375 			    (uchar_t *)&dst,		/* dest address */
9376 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9377 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9378 			    NULL,			/* gateway address */
9379 			    (ire_marks & IRE_MARK_NOADD) ?
9380 			    ipif->ipif_mtu : 0,		/* max_frag */
9381 			    NULL,			/* no src nce */
9382 			    dst_ill->ill_rq,		/* recv-from queue */
9383 			    dst_ill->ill_wq,		/* send-to queue */
9384 			    IRE_CACHE,
9385 			    src_ipif,
9386 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9387 			    (fire != NULL) ?		/* Parent handle */
9388 			    fire->ire_phandle : 0,
9389 			    (save_ire != NULL) ?	/* Interface handle */
9390 			    save_ire->ire_ihandle : 0,
9391 			    (fire != NULL) ?		/* flags if any */
9392 			    (fire->ire_flags &
9393 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9394 			    (save_ire == NULL ? &ire_uinfo_null :
9395 			    &save_ire->ire_uinfo),
9396 			    NULL,
9397 			    NULL,
9398 			    ipst);
9399 
9400 			if (save_ire != NULL) {
9401 				ire_refrele(save_ire);
9402 				save_ire = NULL;
9403 			}
9404 			if (ire == NULL)
9405 				break;
9406 
9407 			ire->ire_marks |= ire_marks;
9408 			/*
9409 			 * Construct message chain for the resolver of the
9410 			 * form:
9411 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9412 			 *
9413 			 * NOTE : ire will be added later when the response
9414 			 * comes back from ARP. If the response does not
9415 			 * come back, ARP frees the packet. For this reason,
9416 			 * we can't REFHOLD the bucket of save_ire to prevent
9417 			 * deletions. We may not be able to REFRELE the
9418 			 * bucket if the response never comes back.
9419 			 * Thus, before adding the ire, ire_add_v4 will make
9420 			 * sure that the interface route does not get deleted.
9421 			 * This is the only case unlike ip_newroute_v6,
9422 			 * ip_newroute_ipif_v6 where we can always prevent
9423 			 * deletions because ire_add_then_send is called after
9424 			 * creating the IRE.
9425 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9426 			 * does not add this IRE into the IRE CACHE.
9427 			 */
9428 			ASSERT(ire->ire_mp != NULL);
9429 			ire->ire_mp->b_cont = first_mp;
9430 			/* Have saved_mp handy, for cleanup if canput fails */
9431 			saved_mp = mp;
9432 			mp = copyb(res_mp);
9433 			if (mp == NULL) {
9434 				/* Prepare for cleanup */
9435 				mp = saved_mp; /* pkt */
9436 				ire_delete(ire); /* ire_mp */
9437 				ire = NULL;
9438 				if (copy_mp != NULL) {
9439 					MULTIRT_DEBUG_UNTAG(copy_mp);
9440 					freemsg(copy_mp);
9441 					copy_mp = NULL;
9442 				}
9443 				break;
9444 			}
9445 			linkb(mp, ire->ire_mp);
9446 
9447 			/*
9448 			 * Fill in the source and dest addrs for the resolver.
9449 			 * NOTE: this depends on memory layouts imposed by
9450 			 * ill_init().  There are corner cases above where we
9451 			 * might've created the IRE with an INADDR_ANY source
9452 			 * address (e.g., if the zeroth ipif on an underlying
9453 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9454 			 * on the ill has a usable test address).  If so, tell
9455 			 * ARP to use ipha_src as its sender address.
9456 			 */
9457 			areq = (areq_t *)mp->b_rptr;
9458 			addrp = (ipaddr_t *)((char *)areq +
9459 			    areq->areq_sender_addr_offset);
9460 			if (ire->ire_src_addr != INADDR_ANY)
9461 				*addrp = ire->ire_src_addr;
9462 			else
9463 				*addrp = ipha->ipha_src;
9464 			addrp = (ipaddr_t *)((char *)areq +
9465 			    areq->areq_target_addr_offset);
9466 			*addrp = dst;
9467 			/* Up to the resolver. */
9468 			if (canputnext(dst_ill->ill_rq) &&
9469 			    !(dst_ill->ill_arp_closing)) {
9470 				putnext(dst_ill->ill_rq, mp);
9471 				/*
9472 				 * The response will come back in ip_wput
9473 				 * with db_type IRE_DB_TYPE.
9474 				 */
9475 			} else {
9476 				mp->b_cont = NULL;
9477 				freeb(mp); /* areq */
9478 				ire_delete(ire); /* ire_mp */
9479 				saved_mp->b_next = NULL;
9480 				saved_mp->b_prev = NULL;
9481 				freemsg(first_mp); /* pkt */
9482 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9483 			}
9484 
9485 			if (fire != NULL) {
9486 				ire_refrele(fire);
9487 				fire = NULL;
9488 			}
9489 
9490 			/*
9491 			 * The resolution loop is re-entered if this was
9492 			 * requested through flags and we actually are
9493 			 * in a multirouting case.
9494 			 */
9495 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9496 				boolean_t need_resolve =
9497 				    ire_multirt_need_resolve(ipha_dst,
9498 				    msg_getlabel(copy_mp), ipst);
9499 				if (!need_resolve) {
9500 					MULTIRT_DEBUG_UNTAG(copy_mp);
9501 					freemsg(copy_mp);
9502 					copy_mp = NULL;
9503 				} else {
9504 					/*
9505 					 * ipif_lookup_group() calls
9506 					 * ire_lookup_multi() that uses
9507 					 * ire_ftable_lookup() to find
9508 					 * an IRE_INTERFACE for the group.
9509 					 * In the multirt case,
9510 					 * ire_lookup_multi() then invokes
9511 					 * ire_multirt_lookup() to find
9512 					 * the next resolvable ire.
9513 					 * As a result, we obtain an new
9514 					 * interface, derived from the
9515 					 * next ire.
9516 					 */
9517 					ipif_refrele(ipif);
9518 					ipif = ipif_lookup_group(ipha_dst,
9519 					    zoneid, ipst);
9520 					if (ipif != NULL) {
9521 						mp = copy_mp;
9522 						copy_mp = NULL;
9523 						multirt_resolve_next = B_TRUE;
9524 						continue;
9525 					} else {
9526 						freemsg(copy_mp);
9527 					}
9528 				}
9529 			}
9530 			if (ipif != NULL)
9531 				ipif_refrele(ipif);
9532 			ill_refrele(dst_ill);
9533 			ipif_refrele(src_ipif);
9534 			return;
9535 		default:
9536 			break;
9537 		}
9538 	} while (multirt_resolve_next);
9539 
9540 err_ret:
9541 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9542 	if (fire != NULL)
9543 		ire_refrele(fire);
9544 	ipif_refrele(ipif);
9545 	/* Did this packet originate externally? */
9546 	if (dst_ill != NULL)
9547 		ill_refrele(dst_ill);
9548 	if (src_ipif != NULL)
9549 		ipif_refrele(src_ipif);
9550 	if (mp->b_prev || mp->b_next) {
9551 		mp->b_next = NULL;
9552 		mp->b_prev = NULL;
9553 	} else {
9554 		/*
9555 		 * Since ip_wput() isn't close to finished, we fill
9556 		 * in enough of the header for credible error reporting.
9557 		 */
9558 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9559 			/* Failed */
9560 			freemsg(first_mp);
9561 			if (ire != NULL)
9562 				ire_refrele(ire);
9563 			return;
9564 		}
9565 	}
9566 	/*
9567 	 * At this point we will have ire only if RTF_BLACKHOLE
9568 	 * or RTF_REJECT flags are set on the IRE. It will not
9569 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9570 	 */
9571 	if (ire != NULL) {
9572 		if (ire->ire_flags & RTF_BLACKHOLE) {
9573 			ire_refrele(ire);
9574 			freemsg(first_mp);
9575 			return;
9576 		}
9577 		ire_refrele(ire);
9578 	}
9579 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9580 }
9581 
9582 /* Name/Value Table Lookup Routine */
9583 char *
9584 ip_nv_lookup(nv_t *nv, int value)
9585 {
9586 	if (!nv)
9587 		return (NULL);
9588 	for (; nv->nv_name; nv++) {
9589 		if (nv->nv_value == value)
9590 			return (nv->nv_name);
9591 	}
9592 	return ("unknown");
9593 }
9594 
9595 /*
9596  * This is a module open, i.e. this is a control stream for access
9597  * to a DLPI device.  We allocate an ill_t as the instance data in
9598  * this case.
9599  */
9600 int
9601 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9602 {
9603 	ill_t	*ill;
9604 	int	err;
9605 	zoneid_t zoneid;
9606 	netstack_t *ns;
9607 	ip_stack_t *ipst;
9608 
9609 	/*
9610 	 * Prevent unprivileged processes from pushing IP so that
9611 	 * they can't send raw IP.
9612 	 */
9613 	if (secpolicy_net_rawaccess(credp) != 0)
9614 		return (EPERM);
9615 
9616 	ns = netstack_find_by_cred(credp);
9617 	ASSERT(ns != NULL);
9618 	ipst = ns->netstack_ip;
9619 	ASSERT(ipst != NULL);
9620 
9621 	/*
9622 	 * For exclusive stacks we set the zoneid to zero
9623 	 * to make IP operate as if in the global zone.
9624 	 */
9625 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9626 		zoneid = GLOBAL_ZONEID;
9627 	else
9628 		zoneid = crgetzoneid(credp);
9629 
9630 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9631 	q->q_ptr = WR(q)->q_ptr = ill;
9632 	ill->ill_ipst = ipst;
9633 	ill->ill_zoneid = zoneid;
9634 
9635 	/*
9636 	 * ill_init initializes the ill fields and then sends down
9637 	 * down a DL_INFO_REQ after calling qprocson.
9638 	 */
9639 	err = ill_init(q, ill);
9640 	if (err != 0) {
9641 		mi_free(ill);
9642 		netstack_rele(ipst->ips_netstack);
9643 		q->q_ptr = NULL;
9644 		WR(q)->q_ptr = NULL;
9645 		return (err);
9646 	}
9647 
9648 	/* ill_init initializes the ipsq marking this thread as writer */
9649 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9650 	/* Wait for the DL_INFO_ACK */
9651 	mutex_enter(&ill->ill_lock);
9652 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9653 		/*
9654 		 * Return value of 0 indicates a pending signal.
9655 		 */
9656 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9657 		if (err == 0) {
9658 			mutex_exit(&ill->ill_lock);
9659 			(void) ip_close(q, 0);
9660 			return (EINTR);
9661 		}
9662 	}
9663 	mutex_exit(&ill->ill_lock);
9664 
9665 	/*
9666 	 * ip_rput_other could have set an error  in ill_error on
9667 	 * receipt of M_ERROR.
9668 	 */
9669 
9670 	err = ill->ill_error;
9671 	if (err != 0) {
9672 		(void) ip_close(q, 0);
9673 		return (err);
9674 	}
9675 
9676 	ill->ill_credp = credp;
9677 	crhold(credp);
9678 
9679 	mutex_enter(&ipst->ips_ip_mi_lock);
9680 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9681 	    credp);
9682 	mutex_exit(&ipst->ips_ip_mi_lock);
9683 	if (err) {
9684 		(void) ip_close(q, 0);
9685 		return (err);
9686 	}
9687 	return (0);
9688 }
9689 
9690 /* For /dev/ip aka AF_INET open */
9691 int
9692 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9693 {
9694 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9695 }
9696 
9697 /* For /dev/ip6 aka AF_INET6 open */
9698 int
9699 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9700 {
9701 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9702 }
9703 
9704 /* IP open routine. */
9705 int
9706 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9707     boolean_t isv6)
9708 {
9709 	conn_t 		*connp;
9710 	major_t		maj;
9711 	zoneid_t	zoneid;
9712 	netstack_t	*ns;
9713 	ip_stack_t	*ipst;
9714 
9715 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9716 
9717 	/* Allow reopen. */
9718 	if (q->q_ptr != NULL)
9719 		return (0);
9720 
9721 	if (sflag & MODOPEN) {
9722 		/* This is a module open */
9723 		return (ip_modopen(q, devp, flag, sflag, credp));
9724 	}
9725 
9726 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9727 		/*
9728 		 * Non streams based socket looking for a stream
9729 		 * to access IP
9730 		 */
9731 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9732 		    credp, isv6));
9733 	}
9734 
9735 	ns = netstack_find_by_cred(credp);
9736 	ASSERT(ns != NULL);
9737 	ipst = ns->netstack_ip;
9738 	ASSERT(ipst != NULL);
9739 
9740 	/*
9741 	 * For exclusive stacks we set the zoneid to zero
9742 	 * to make IP operate as if in the global zone.
9743 	 */
9744 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9745 		zoneid = GLOBAL_ZONEID;
9746 	else
9747 		zoneid = crgetzoneid(credp);
9748 
9749 	/*
9750 	 * We are opening as a device. This is an IP client stream, and we
9751 	 * allocate an conn_t as the instance data.
9752 	 */
9753 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9754 
9755 	/*
9756 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9757 	 * done by netstack_find_by_cred()
9758 	 */
9759 	netstack_rele(ipst->ips_netstack);
9760 
9761 	connp->conn_zoneid = zoneid;
9762 	connp->conn_sqp = NULL;
9763 	connp->conn_initial_sqp = NULL;
9764 	connp->conn_final_sqp = NULL;
9765 
9766 	connp->conn_upq = q;
9767 	q->q_ptr = WR(q)->q_ptr = connp;
9768 
9769 	if (flag & SO_SOCKSTR)
9770 		connp->conn_flags |= IPCL_SOCKET;
9771 
9772 	/* Minor tells us which /dev entry was opened */
9773 	if (isv6) {
9774 		connp->conn_af_isv6 = B_TRUE;
9775 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9776 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9777 	} else {
9778 		connp->conn_af_isv6 = B_FALSE;
9779 		connp->conn_pkt_isv6 = B_FALSE;
9780 	}
9781 
9782 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9783 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9784 		connp->conn_minor_arena = ip_minor_arena_la;
9785 	} else {
9786 		/*
9787 		 * Either minor numbers in the large arena were exhausted
9788 		 * or a non socket application is doing the open.
9789 		 * Try to allocate from the small arena.
9790 		 */
9791 		if ((connp->conn_dev =
9792 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9793 			/* CONN_DEC_REF takes care of netstack_rele() */
9794 			q->q_ptr = WR(q)->q_ptr = NULL;
9795 			CONN_DEC_REF(connp);
9796 			return (EBUSY);
9797 		}
9798 		connp->conn_minor_arena = ip_minor_arena_sa;
9799 	}
9800 
9801 	maj = getemajor(*devp);
9802 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9803 
9804 	/*
9805 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9806 	 */
9807 	connp->conn_cred = credp;
9808 
9809 	/*
9810 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9811 	 */
9812 	connp->conn_recv = ip_conn_input;
9813 
9814 	crhold(connp->conn_cred);
9815 
9816 	/*
9817 	 * If the caller has the process-wide flag set, then default to MAC
9818 	 * exempt mode.  This allows read-down to unlabeled hosts.
9819 	 */
9820 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9821 		connp->conn_mac_mode = CONN_MAC_AWARE;
9822 
9823 	connp->conn_rq = q;
9824 	connp->conn_wq = WR(q);
9825 
9826 	/* Non-zero default values */
9827 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9828 
9829 	/*
9830 	 * Make the conn globally visible to walkers
9831 	 */
9832 	ASSERT(connp->conn_ref == 1);
9833 	mutex_enter(&connp->conn_lock);
9834 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9835 	mutex_exit(&connp->conn_lock);
9836 
9837 	qprocson(q);
9838 
9839 	return (0);
9840 }
9841 
9842 /*
9843  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9844  * Note that there is no race since either ip_output function works - it
9845  * is just an optimization to enter the best ip_output routine directly.
9846  */
9847 void
9848 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9849     ip_stack_t *ipst)
9850 {
9851 	if (isv6)  {
9852 		if (bump_mib) {
9853 			BUMP_MIB(&ipst->ips_ip6_mib,
9854 			    ipIfStatsOutSwitchIPVersion);
9855 		}
9856 		connp->conn_send = ip_output_v6;
9857 		connp->conn_pkt_isv6 = B_TRUE;
9858 	} else {
9859 		if (bump_mib) {
9860 			BUMP_MIB(&ipst->ips_ip_mib,
9861 			    ipIfStatsOutSwitchIPVersion);
9862 		}
9863 		connp->conn_send = ip_output;
9864 		connp->conn_pkt_isv6 = B_FALSE;
9865 	}
9866 
9867 }
9868 
9869 /*
9870  * See if IPsec needs loading because of the options in mp.
9871  */
9872 static boolean_t
9873 ipsec_opt_present(mblk_t *mp)
9874 {
9875 	uint8_t *optcp, *next_optcp, *opt_endcp;
9876 	struct opthdr *opt;
9877 	struct T_opthdr *topt;
9878 	int opthdr_len;
9879 	t_uscalar_t optname, optlevel;
9880 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9881 	ipsec_req_t *ipsr;
9882 
9883 	/*
9884 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9885 	 * return TRUE.
9886 	 */
9887 
9888 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9889 	opt_endcp = optcp + tor->OPT_length;
9890 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9891 		opthdr_len = sizeof (struct T_opthdr);
9892 	} else {		/* O_OPTMGMT_REQ */
9893 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9894 		opthdr_len = sizeof (struct opthdr);
9895 	}
9896 	for (; optcp < opt_endcp; optcp = next_optcp) {
9897 		if (optcp + opthdr_len > opt_endcp)
9898 			return (B_FALSE);	/* Not enough option header. */
9899 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9900 			topt = (struct T_opthdr *)optcp;
9901 			optlevel = topt->level;
9902 			optname = topt->name;
9903 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9904 		} else {
9905 			opt = (struct opthdr *)optcp;
9906 			optlevel = opt->level;
9907 			optname = opt->name;
9908 			next_optcp = optcp + opthdr_len +
9909 			    _TPI_ALIGN_OPT(opt->len);
9910 		}
9911 		if ((next_optcp < optcp) || /* wraparound pointer space */
9912 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9913 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9914 			return (B_FALSE); /* bad option buffer */
9915 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9916 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9917 			/*
9918 			 * Check to see if it's an all-bypass or all-zeroes
9919 			 * IPsec request.  Don't bother loading IPsec if
9920 			 * the socket doesn't want to use it.  (A good example
9921 			 * is a bypass request.)
9922 			 *
9923 			 * Basically, if any of the non-NEVER bits are set,
9924 			 * load IPsec.
9925 			 */
9926 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9927 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9928 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9929 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9930 			    != 0)
9931 				return (B_TRUE);
9932 		}
9933 	}
9934 	return (B_FALSE);
9935 }
9936 
9937 /*
9938  * If conn is is waiting for ipsec to finish loading, kick it.
9939  */
9940 /* ARGSUSED */
9941 static void
9942 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9943 {
9944 	t_scalar_t	optreq_prim;
9945 	mblk_t		*mp;
9946 	cred_t		*cr;
9947 	int		err = 0;
9948 
9949 	/*
9950 	 * This function is called, after ipsec loading is complete.
9951 	 * Since IP checks exclusively and atomically (i.e it prevents
9952 	 * ipsec load from completing until ip_optcom_req completes)
9953 	 * whether ipsec load is complete, there cannot be a race with IP
9954 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9955 	 */
9956 	mutex_enter(&connp->conn_lock);
9957 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9958 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9959 		mp = connp->conn_ipsec_opt_mp;
9960 		connp->conn_ipsec_opt_mp = NULL;
9961 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9962 		mutex_exit(&connp->conn_lock);
9963 
9964 		/*
9965 		 * All Solaris components should pass a db_credp
9966 		 * for this TPI message, hence we ASSERT.
9967 		 * But in case there is some other M_PROTO that looks
9968 		 * like a TPI message sent by some other kernel
9969 		 * component, we check and return an error.
9970 		 */
9971 		cr = msg_getcred(mp, NULL);
9972 		ASSERT(cr != NULL);
9973 		if (cr == NULL) {
9974 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
9975 			if (mp != NULL)
9976 				qreply(connp->conn_wq, mp);
9977 			return;
9978 		}
9979 
9980 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9981 
9982 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9983 		if (optreq_prim == T_OPTMGMT_REQ) {
9984 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9985 			    &ip_opt_obj, B_FALSE);
9986 		} else {
9987 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9988 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9989 			    &ip_opt_obj, B_FALSE);
9990 		}
9991 		if (err != EINPROGRESS)
9992 			CONN_OPER_PENDING_DONE(connp);
9993 		return;
9994 	}
9995 	mutex_exit(&connp->conn_lock);
9996 }
9997 
9998 /*
9999  * Called from the ipsec_loader thread, outside any perimeter, to tell
10000  * ip qenable any of the queues waiting for the ipsec loader to
10001  * complete.
10002  */
10003 void
10004 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10005 {
10006 	netstack_t *ns = ipss->ipsec_netstack;
10007 
10008 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10009 }
10010 
10011 /*
10012  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10013  * determines the grp on which it has to become exclusive, queues the mp
10014  * and IPSQ draining restarts the optmgmt
10015  */
10016 static boolean_t
10017 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10018 {
10019 	conn_t *connp = Q_TO_CONN(q);
10020 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10021 
10022 	/*
10023 	 * Take IPsec requests and treat them special.
10024 	 */
10025 	if (ipsec_opt_present(mp)) {
10026 		/* First check if IPsec is loaded. */
10027 		mutex_enter(&ipss->ipsec_loader_lock);
10028 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10029 			mutex_exit(&ipss->ipsec_loader_lock);
10030 			return (B_FALSE);
10031 		}
10032 		mutex_enter(&connp->conn_lock);
10033 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10034 
10035 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10036 		connp->conn_ipsec_opt_mp = mp;
10037 		mutex_exit(&connp->conn_lock);
10038 		mutex_exit(&ipss->ipsec_loader_lock);
10039 
10040 		ipsec_loader_loadnow(ipss);
10041 		return (B_TRUE);
10042 	}
10043 	return (B_FALSE);
10044 }
10045 
10046 /*
10047  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10048  * all of them are copied to the conn_t. If the req is "zero", the policy is
10049  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10050  * fields.
10051  * We keep only the latest setting of the policy and thus policy setting
10052  * is not incremental/cumulative.
10053  *
10054  * Requests to set policies with multiple alternative actions will
10055  * go through a different API.
10056  */
10057 int
10058 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10059 {
10060 	uint_t ah_req = 0;
10061 	uint_t esp_req = 0;
10062 	uint_t se_req = 0;
10063 	ipsec_act_t *actp = NULL;
10064 	uint_t nact;
10065 	ipsec_policy_head_t *ph;
10066 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
10067 	int error = 0;
10068 	netstack_t	*ns = connp->conn_netstack;
10069 	ip_stack_t	*ipst = ns->netstack_ip;
10070 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10071 
10072 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10073 
10074 	/*
10075 	 * The IP_SEC_OPT option does not allow variable length parameters,
10076 	 * hence a request cannot be NULL.
10077 	 */
10078 	if (req == NULL)
10079 		return (EINVAL);
10080 
10081 	ah_req = req->ipsr_ah_req;
10082 	esp_req = req->ipsr_esp_req;
10083 	se_req = req->ipsr_self_encap_req;
10084 
10085 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10086 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10087 		return (EINVAL);
10088 
10089 	/*
10090 	 * Are we dealing with a request to reset the policy (i.e.
10091 	 * zero requests).
10092 	 */
10093 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10094 	    (esp_req & REQ_MASK) == 0 &&
10095 	    (se_req & REQ_MASK) == 0);
10096 
10097 	if (!is_pol_reset) {
10098 		/*
10099 		 * If we couldn't load IPsec, fail with "protocol
10100 		 * not supported".
10101 		 * IPsec may not have been loaded for a request with zero
10102 		 * policies, so we don't fail in this case.
10103 		 */
10104 		mutex_enter(&ipss->ipsec_loader_lock);
10105 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10106 			mutex_exit(&ipss->ipsec_loader_lock);
10107 			return (EPROTONOSUPPORT);
10108 		}
10109 		mutex_exit(&ipss->ipsec_loader_lock);
10110 
10111 		/*
10112 		 * Test for valid requests. Invalid algorithms
10113 		 * need to be tested by IPsec code because new
10114 		 * algorithms can be added dynamically.
10115 		 */
10116 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10117 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10118 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10119 			return (EINVAL);
10120 		}
10121 
10122 		/*
10123 		 * Only privileged users can issue these
10124 		 * requests.
10125 		 */
10126 		if (((ah_req & IPSEC_PREF_NEVER) ||
10127 		    (esp_req & IPSEC_PREF_NEVER) ||
10128 		    (se_req & IPSEC_PREF_NEVER)) &&
10129 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10130 			return (EPERM);
10131 		}
10132 
10133 		/*
10134 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10135 		 * are mutually exclusive.
10136 		 */
10137 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10138 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10139 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10140 			/* Both of them are set */
10141 			return (EINVAL);
10142 		}
10143 	}
10144 
10145 	mutex_enter(&connp->conn_lock);
10146 
10147 	/*
10148 	 * If we have already cached policies in ip_bind_connected*(), don't
10149 	 * let them change now. We cache policies for connections
10150 	 * whose src,dst [addr, port] is known.
10151 	 */
10152 	if (connp->conn_policy_cached) {
10153 		mutex_exit(&connp->conn_lock);
10154 		return (EINVAL);
10155 	}
10156 
10157 	/*
10158 	 * We have a zero policies, reset the connection policy if already
10159 	 * set. This will cause the connection to inherit the
10160 	 * global policy, if any.
10161 	 */
10162 	if (is_pol_reset) {
10163 		if (connp->conn_policy != NULL) {
10164 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10165 			connp->conn_policy = NULL;
10166 		}
10167 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10168 		connp->conn_in_enforce_policy = B_FALSE;
10169 		connp->conn_out_enforce_policy = B_FALSE;
10170 		mutex_exit(&connp->conn_lock);
10171 		return (0);
10172 	}
10173 
10174 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10175 	    ipst->ips_netstack);
10176 	if (ph == NULL)
10177 		goto enomem;
10178 
10179 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10180 	if (actp == NULL)
10181 		goto enomem;
10182 
10183 	/*
10184 	 * Always insert IPv4 policy entries, since they can also apply to
10185 	 * ipv6 sockets being used in ipv4-compat mode.
10186 	 */
10187 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10188 	    IPSEC_TYPE_INBOUND, ns))
10189 		goto enomem;
10190 	is_pol_inserted = B_TRUE;
10191 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10192 	    IPSEC_TYPE_OUTBOUND, ns))
10193 		goto enomem;
10194 
10195 	/*
10196 	 * We're looking at a v6 socket, also insert the v6-specific
10197 	 * entries.
10198 	 */
10199 	if (connp->conn_af_isv6) {
10200 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10201 		    IPSEC_TYPE_INBOUND, ns))
10202 			goto enomem;
10203 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10204 		    IPSEC_TYPE_OUTBOUND, ns))
10205 			goto enomem;
10206 	}
10207 
10208 	ipsec_actvec_free(actp, nact);
10209 
10210 	/*
10211 	 * If the requests need security, set enforce_policy.
10212 	 * If the requests are IPSEC_PREF_NEVER, one should
10213 	 * still set conn_out_enforce_policy so that an ipsec_out
10214 	 * gets attached in ip_wput. This is needed so that
10215 	 * for connections that we don't cache policy in ip_bind,
10216 	 * if global policy matches in ip_wput_attach_policy, we
10217 	 * don't wrongly inherit global policy. Similarly, we need
10218 	 * to set conn_in_enforce_policy also so that we don't verify
10219 	 * policy wrongly.
10220 	 */
10221 	if ((ah_req & REQ_MASK) != 0 ||
10222 	    (esp_req & REQ_MASK) != 0 ||
10223 	    (se_req & REQ_MASK) != 0) {
10224 		connp->conn_in_enforce_policy = B_TRUE;
10225 		connp->conn_out_enforce_policy = B_TRUE;
10226 		connp->conn_flags |= IPCL_CHECK_POLICY;
10227 	}
10228 
10229 	mutex_exit(&connp->conn_lock);
10230 	return (error);
10231 #undef REQ_MASK
10232 
10233 	/*
10234 	 * Common memory-allocation-failure exit path.
10235 	 */
10236 enomem:
10237 	mutex_exit(&connp->conn_lock);
10238 	if (actp != NULL)
10239 		ipsec_actvec_free(actp, nact);
10240 	if (is_pol_inserted)
10241 		ipsec_polhead_flush(ph, ns);
10242 	return (ENOMEM);
10243 }
10244 
10245 /*
10246  * Only for options that pass in an IP addr. Currently only V4 options
10247  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10248  * So this function assumes level is IPPROTO_IP
10249  */
10250 int
10251 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10252     mblk_t *first_mp)
10253 {
10254 	ipif_t *ipif = NULL;
10255 	int error;
10256 	ill_t *ill;
10257 	int zoneid;
10258 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10259 
10260 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10261 
10262 	if (addr != INADDR_ANY || checkonly) {
10263 		ASSERT(connp != NULL);
10264 		zoneid = IPCL_ZONEID(connp);
10265 		if (option == IP_NEXTHOP) {
10266 			ipif = ipif_lookup_onlink_addr(addr,
10267 			    connp->conn_zoneid, ipst);
10268 		} else {
10269 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10270 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10271 			    &error, ipst);
10272 		}
10273 		if (ipif == NULL) {
10274 			if (error == EINPROGRESS)
10275 				return (error);
10276 			if ((option == IP_MULTICAST_IF) ||
10277 			    (option == IP_NEXTHOP))
10278 				return (EHOSTUNREACH);
10279 			else
10280 				return (EINVAL);
10281 		} else if (checkonly) {
10282 			if (option == IP_MULTICAST_IF) {
10283 				ill = ipif->ipif_ill;
10284 				/* not supported by the virtual network iface */
10285 				if (IS_VNI(ill)) {
10286 					ipif_refrele(ipif);
10287 					return (EINVAL);
10288 				}
10289 			}
10290 			ipif_refrele(ipif);
10291 			return (0);
10292 		}
10293 		ill = ipif->ipif_ill;
10294 		mutex_enter(&connp->conn_lock);
10295 		mutex_enter(&ill->ill_lock);
10296 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10297 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10298 			mutex_exit(&ill->ill_lock);
10299 			mutex_exit(&connp->conn_lock);
10300 			ipif_refrele(ipif);
10301 			return (option == IP_MULTICAST_IF ?
10302 			    EHOSTUNREACH : EINVAL);
10303 		}
10304 	} else {
10305 		mutex_enter(&connp->conn_lock);
10306 	}
10307 
10308 	/* None of the options below are supported on the VNI */
10309 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10310 		mutex_exit(&ill->ill_lock);
10311 		mutex_exit(&connp->conn_lock);
10312 		ipif_refrele(ipif);
10313 		return (EINVAL);
10314 	}
10315 
10316 	switch (option) {
10317 	case IP_MULTICAST_IF:
10318 		connp->conn_multicast_ipif = ipif;
10319 		break;
10320 	case IP_NEXTHOP:
10321 		connp->conn_nexthop_v4 = addr;
10322 		connp->conn_nexthop_set = B_TRUE;
10323 		break;
10324 	}
10325 
10326 	if (ipif != NULL) {
10327 		mutex_exit(&ill->ill_lock);
10328 		mutex_exit(&connp->conn_lock);
10329 		ipif_refrele(ipif);
10330 		return (0);
10331 	}
10332 	mutex_exit(&connp->conn_lock);
10333 	/* We succeded in cleared the option */
10334 	return (0);
10335 }
10336 
10337 /*
10338  * For options that pass in an ifindex specifying the ill. V6 options always
10339  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10340  */
10341 int
10342 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10343     int level, int option, mblk_t *first_mp)
10344 {
10345 	ill_t *ill = NULL;
10346 	int error = 0;
10347 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10348 
10349 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10350 	if (ifindex != 0) {
10351 		ASSERT(connp != NULL);
10352 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10353 		    first_mp, ip_restart_optmgmt, &error, ipst);
10354 		if (ill != NULL) {
10355 			if (checkonly) {
10356 				/* not supported by the virtual network iface */
10357 				if (IS_VNI(ill)) {
10358 					ill_refrele(ill);
10359 					return (EINVAL);
10360 				}
10361 				ill_refrele(ill);
10362 				return (0);
10363 			}
10364 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10365 			    0, NULL)) {
10366 				ill_refrele(ill);
10367 				ill = NULL;
10368 				mutex_enter(&connp->conn_lock);
10369 				goto setit;
10370 			}
10371 			mutex_enter(&connp->conn_lock);
10372 			mutex_enter(&ill->ill_lock);
10373 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10374 				mutex_exit(&ill->ill_lock);
10375 				mutex_exit(&connp->conn_lock);
10376 				ill_refrele(ill);
10377 				ill = NULL;
10378 				mutex_enter(&connp->conn_lock);
10379 			}
10380 			goto setit;
10381 		} else if (error == EINPROGRESS) {
10382 			return (error);
10383 		} else {
10384 			error = 0;
10385 		}
10386 	}
10387 	mutex_enter(&connp->conn_lock);
10388 setit:
10389 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10390 
10391 	/*
10392 	 * The options below assume that the ILL (if any) transmits and/or
10393 	 * receives traffic. Neither of which is true for the virtual network
10394 	 * interface, so fail setting these on a VNI.
10395 	 */
10396 	if (IS_VNI(ill)) {
10397 		ASSERT(ill != NULL);
10398 		mutex_exit(&ill->ill_lock);
10399 		mutex_exit(&connp->conn_lock);
10400 		ill_refrele(ill);
10401 		return (EINVAL);
10402 	}
10403 
10404 	if (level == IPPROTO_IP) {
10405 		switch (option) {
10406 		case IP_BOUND_IF:
10407 			connp->conn_incoming_ill = ill;
10408 			connp->conn_outgoing_ill = ill;
10409 			break;
10410 
10411 		case IP_MULTICAST_IF:
10412 			/*
10413 			 * This option is an internal special. The socket
10414 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10415 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10416 			 * specifies an ifindex and we try first on V6 ill's.
10417 			 * If we don't find one, we they try using on v4 ill's
10418 			 * intenally and we come here.
10419 			 */
10420 			if (!checkonly && ill != NULL) {
10421 				ipif_t	*ipif;
10422 				ipif = ill->ill_ipif;
10423 
10424 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10425 					mutex_exit(&ill->ill_lock);
10426 					mutex_exit(&connp->conn_lock);
10427 					ill_refrele(ill);
10428 					ill = NULL;
10429 					mutex_enter(&connp->conn_lock);
10430 				} else {
10431 					connp->conn_multicast_ipif = ipif;
10432 				}
10433 			}
10434 			break;
10435 
10436 		case IP_DHCPINIT_IF:
10437 			if (connp->conn_dhcpinit_ill != NULL) {
10438 				/*
10439 				 * We've locked the conn so conn_cleanup_ill()
10440 				 * cannot clear conn_dhcpinit_ill -- so it's
10441 				 * safe to access the ill.
10442 				 */
10443 				ill_t *oill = connp->conn_dhcpinit_ill;
10444 
10445 				ASSERT(oill->ill_dhcpinit != 0);
10446 				atomic_dec_32(&oill->ill_dhcpinit);
10447 				connp->conn_dhcpinit_ill = NULL;
10448 			}
10449 
10450 			if (ill != NULL) {
10451 				connp->conn_dhcpinit_ill = ill;
10452 				atomic_inc_32(&ill->ill_dhcpinit);
10453 			}
10454 			break;
10455 		}
10456 	} else {
10457 		switch (option) {
10458 		case IPV6_BOUND_IF:
10459 			connp->conn_incoming_ill = ill;
10460 			connp->conn_outgoing_ill = ill;
10461 			break;
10462 
10463 		case IPV6_MULTICAST_IF:
10464 			/*
10465 			 * Set conn_multicast_ill to be the IPv6 ill.
10466 			 * Set conn_multicast_ipif to be an IPv4 ipif
10467 			 * for ifindex to make IPv4 mapped addresses
10468 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10469 			 * Even if no IPv6 ill exists for the ifindex
10470 			 * we need to check for an IPv4 ifindex in order
10471 			 * for this to work with mapped addresses. In that
10472 			 * case only set conn_multicast_ipif.
10473 			 */
10474 			if (!checkonly) {
10475 				if (ifindex == 0) {
10476 					connp->conn_multicast_ill = NULL;
10477 					connp->conn_multicast_ipif = NULL;
10478 				} else if (ill != NULL) {
10479 					connp->conn_multicast_ill = ill;
10480 				}
10481 			}
10482 			break;
10483 		}
10484 	}
10485 
10486 	if (ill != NULL) {
10487 		mutex_exit(&ill->ill_lock);
10488 		mutex_exit(&connp->conn_lock);
10489 		ill_refrele(ill);
10490 		return (0);
10491 	}
10492 	mutex_exit(&connp->conn_lock);
10493 	/*
10494 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10495 	 * locate the ill and could not set the option (ifindex != 0)
10496 	 */
10497 	return (ifindex == 0 ? 0 : EINVAL);
10498 }
10499 
10500 /* This routine sets socket options. */
10501 /* ARGSUSED */
10502 int
10503 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10504     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10505     void *dummy, cred_t *cr, mblk_t *first_mp)
10506 {
10507 	int		*i1 = (int *)invalp;
10508 	conn_t		*connp = Q_TO_CONN(q);
10509 	int		error = 0;
10510 	boolean_t	checkonly;
10511 	ire_t		*ire;
10512 	boolean_t	found;
10513 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10514 
10515 	switch (optset_context) {
10516 
10517 	case SETFN_OPTCOM_CHECKONLY:
10518 		checkonly = B_TRUE;
10519 		/*
10520 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10521 		 * inlen != 0 implies value supplied and
10522 		 * 	we have to "pretend" to set it.
10523 		 * inlen == 0 implies that there is no
10524 		 * 	value part in T_CHECK request and just validation
10525 		 * done elsewhere should be enough, we just return here.
10526 		 */
10527 		if (inlen == 0) {
10528 			*outlenp = 0;
10529 			return (0);
10530 		}
10531 		break;
10532 	case SETFN_OPTCOM_NEGOTIATE:
10533 	case SETFN_UD_NEGOTIATE:
10534 	case SETFN_CONN_NEGOTIATE:
10535 		checkonly = B_FALSE;
10536 		break;
10537 	default:
10538 		/*
10539 		 * We should never get here
10540 		 */
10541 		*outlenp = 0;
10542 		return (EINVAL);
10543 	}
10544 
10545 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10546 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10547 
10548 	/*
10549 	 * For fixed length options, no sanity check
10550 	 * of passed in length is done. It is assumed *_optcom_req()
10551 	 * routines do the right thing.
10552 	 */
10553 
10554 	switch (level) {
10555 	case SOL_SOCKET:
10556 		/*
10557 		 * conn_lock protects the bitfields, and is used to
10558 		 * set the fields atomically.
10559 		 */
10560 		switch (name) {
10561 		case SO_BROADCAST:
10562 			if (!checkonly) {
10563 				/* TODO: use value someplace? */
10564 				mutex_enter(&connp->conn_lock);
10565 				connp->conn_broadcast = *i1 ? 1 : 0;
10566 				mutex_exit(&connp->conn_lock);
10567 			}
10568 			break;	/* goto sizeof (int) option return */
10569 		case SO_USELOOPBACK:
10570 			if (!checkonly) {
10571 				/* TODO: use value someplace? */
10572 				mutex_enter(&connp->conn_lock);
10573 				connp->conn_loopback = *i1 ? 1 : 0;
10574 				mutex_exit(&connp->conn_lock);
10575 			}
10576 			break;	/* goto sizeof (int) option return */
10577 		case SO_DONTROUTE:
10578 			if (!checkonly) {
10579 				mutex_enter(&connp->conn_lock);
10580 				connp->conn_dontroute = *i1 ? 1 : 0;
10581 				mutex_exit(&connp->conn_lock);
10582 			}
10583 			break;	/* goto sizeof (int) option return */
10584 		case SO_REUSEADDR:
10585 			if (!checkonly) {
10586 				mutex_enter(&connp->conn_lock);
10587 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10588 				mutex_exit(&connp->conn_lock);
10589 			}
10590 			break;	/* goto sizeof (int) option return */
10591 		case SO_PROTOTYPE:
10592 			if (!checkonly) {
10593 				mutex_enter(&connp->conn_lock);
10594 				connp->conn_proto = *i1;
10595 				mutex_exit(&connp->conn_lock);
10596 			}
10597 			break;	/* goto sizeof (int) option return */
10598 		case SO_ALLZONES:
10599 			if (!checkonly) {
10600 				mutex_enter(&connp->conn_lock);
10601 				if (IPCL_IS_BOUND(connp)) {
10602 					mutex_exit(&connp->conn_lock);
10603 					return (EINVAL);
10604 				}
10605 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10606 				mutex_exit(&connp->conn_lock);
10607 			}
10608 			break;	/* goto sizeof (int) option return */
10609 		case SO_ANON_MLP:
10610 			if (!checkonly) {
10611 				mutex_enter(&connp->conn_lock);
10612 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10613 				mutex_exit(&connp->conn_lock);
10614 			}
10615 			break;	/* goto sizeof (int) option return */
10616 		case SO_MAC_EXEMPT:
10617 			if (secpolicy_net_mac_aware(cr) != 0 ||
10618 			    IPCL_IS_BOUND(connp))
10619 				return (EACCES);
10620 			if (!checkonly) {
10621 				mutex_enter(&connp->conn_lock);
10622 				connp->conn_mac_mode = *i1 != 0 ?
10623 				    CONN_MAC_AWARE : CONN_MAC_DEFAULT;
10624 				mutex_exit(&connp->conn_lock);
10625 			}
10626 			break;	/* goto sizeof (int) option return */
10627 		case SO_MAC_IMPLICIT:
10628 			if (secpolicy_net_mac_implicit(cr) != 0)
10629 				return (EACCES);
10630 			if (!checkonly) {
10631 				mutex_enter(&connp->conn_lock);
10632 				connp->conn_mac_mode = *i1 != 0 ?
10633 				    CONN_MAC_IMPLICIT : CONN_MAC_DEFAULT;
10634 				mutex_exit(&connp->conn_lock);
10635 			}
10636 			break;	/* goto sizeof (int) option return */
10637 		default:
10638 			/*
10639 			 * "soft" error (negative)
10640 			 * option not handled at this level
10641 			 * Note: Do not modify *outlenp
10642 			 */
10643 			return (-EINVAL);
10644 		}
10645 		break;
10646 	case IPPROTO_IP:
10647 		switch (name) {
10648 		case IP_NEXTHOP:
10649 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10650 				return (EPERM);
10651 			/* FALLTHRU */
10652 		case IP_MULTICAST_IF: {
10653 			ipaddr_t addr = *i1;
10654 
10655 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10656 			    first_mp);
10657 			if (error != 0)
10658 				return (error);
10659 			break;	/* goto sizeof (int) option return */
10660 		}
10661 
10662 		case IP_MULTICAST_TTL:
10663 			/* Recorded in transport above IP */
10664 			*outvalp = *invalp;
10665 			*outlenp = sizeof (uchar_t);
10666 			return (0);
10667 		case IP_MULTICAST_LOOP:
10668 			if (!checkonly) {
10669 				mutex_enter(&connp->conn_lock);
10670 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10671 				mutex_exit(&connp->conn_lock);
10672 			}
10673 			*outvalp = *invalp;
10674 			*outlenp = sizeof (uchar_t);
10675 			return (0);
10676 		case IP_ADD_MEMBERSHIP:
10677 		case MCAST_JOIN_GROUP:
10678 		case IP_DROP_MEMBERSHIP:
10679 		case MCAST_LEAVE_GROUP: {
10680 			struct ip_mreq *mreqp;
10681 			struct group_req *greqp;
10682 			ire_t *ire;
10683 			boolean_t done = B_FALSE;
10684 			ipaddr_t group, ifaddr;
10685 			struct sockaddr_in *sin;
10686 			uint32_t *ifindexp;
10687 			boolean_t mcast_opt = B_TRUE;
10688 			mcast_record_t fmode;
10689 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10690 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10691 
10692 			switch (name) {
10693 			case IP_ADD_MEMBERSHIP:
10694 				mcast_opt = B_FALSE;
10695 				/* FALLTHRU */
10696 			case MCAST_JOIN_GROUP:
10697 				fmode = MODE_IS_EXCLUDE;
10698 				optfn = ip_opt_add_group;
10699 				break;
10700 
10701 			case IP_DROP_MEMBERSHIP:
10702 				mcast_opt = B_FALSE;
10703 				/* FALLTHRU */
10704 			case MCAST_LEAVE_GROUP:
10705 				fmode = MODE_IS_INCLUDE;
10706 				optfn = ip_opt_delete_group;
10707 				break;
10708 			}
10709 
10710 			if (mcast_opt) {
10711 				greqp = (struct group_req *)i1;
10712 				sin = (struct sockaddr_in *)&greqp->gr_group;
10713 				if (sin->sin_family != AF_INET) {
10714 					*outlenp = 0;
10715 					return (ENOPROTOOPT);
10716 				}
10717 				group = (ipaddr_t)sin->sin_addr.s_addr;
10718 				ifaddr = INADDR_ANY;
10719 				ifindexp = &greqp->gr_interface;
10720 			} else {
10721 				mreqp = (struct ip_mreq *)i1;
10722 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10723 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10724 				ifindexp = NULL;
10725 			}
10726 
10727 			/*
10728 			 * In the multirouting case, we need to replicate
10729 			 * the request on all interfaces that will take part
10730 			 * in replication.  We do so because multirouting is
10731 			 * reflective, thus we will probably receive multi-
10732 			 * casts on those interfaces.
10733 			 * The ip_multirt_apply_membership() succeeds if the
10734 			 * operation succeeds on at least one interface.
10735 			 */
10736 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10737 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10738 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10739 			if (ire != NULL) {
10740 				if (ire->ire_flags & RTF_MULTIRT) {
10741 					error = ip_multirt_apply_membership(
10742 					    optfn, ire, connp, checkonly, group,
10743 					    fmode, INADDR_ANY, first_mp);
10744 					done = B_TRUE;
10745 				}
10746 				ire_refrele(ire);
10747 			}
10748 			if (!done) {
10749 				error = optfn(connp, checkonly, group, ifaddr,
10750 				    ifindexp, fmode, INADDR_ANY, first_mp);
10751 			}
10752 			if (error) {
10753 				/*
10754 				 * EINPROGRESS is a soft error, needs retry
10755 				 * so don't make *outlenp zero.
10756 				 */
10757 				if (error != EINPROGRESS)
10758 					*outlenp = 0;
10759 				return (error);
10760 			}
10761 			/* OK return - copy input buffer into output buffer */
10762 			if (invalp != outvalp) {
10763 				/* don't trust bcopy for identical src/dst */
10764 				bcopy(invalp, outvalp, inlen);
10765 			}
10766 			*outlenp = inlen;
10767 			return (0);
10768 		}
10769 		case IP_BLOCK_SOURCE:
10770 		case IP_UNBLOCK_SOURCE:
10771 		case IP_ADD_SOURCE_MEMBERSHIP:
10772 		case IP_DROP_SOURCE_MEMBERSHIP:
10773 		case MCAST_BLOCK_SOURCE:
10774 		case MCAST_UNBLOCK_SOURCE:
10775 		case MCAST_JOIN_SOURCE_GROUP:
10776 		case MCAST_LEAVE_SOURCE_GROUP: {
10777 			struct ip_mreq_source *imreqp;
10778 			struct group_source_req *gsreqp;
10779 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10780 			uint32_t ifindex = 0;
10781 			mcast_record_t fmode;
10782 			struct sockaddr_in *sin;
10783 			ire_t *ire;
10784 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10785 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10786 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10787 
10788 			switch (name) {
10789 			case IP_BLOCK_SOURCE:
10790 				mcast_opt = B_FALSE;
10791 				/* FALLTHRU */
10792 			case MCAST_BLOCK_SOURCE:
10793 				fmode = MODE_IS_EXCLUDE;
10794 				optfn = ip_opt_add_group;
10795 				break;
10796 
10797 			case IP_UNBLOCK_SOURCE:
10798 				mcast_opt = B_FALSE;
10799 				/* FALLTHRU */
10800 			case MCAST_UNBLOCK_SOURCE:
10801 				fmode = MODE_IS_EXCLUDE;
10802 				optfn = ip_opt_delete_group;
10803 				break;
10804 
10805 			case IP_ADD_SOURCE_MEMBERSHIP:
10806 				mcast_opt = B_FALSE;
10807 				/* FALLTHRU */
10808 			case MCAST_JOIN_SOURCE_GROUP:
10809 				fmode = MODE_IS_INCLUDE;
10810 				optfn = ip_opt_add_group;
10811 				break;
10812 
10813 			case IP_DROP_SOURCE_MEMBERSHIP:
10814 				mcast_opt = B_FALSE;
10815 				/* FALLTHRU */
10816 			case MCAST_LEAVE_SOURCE_GROUP:
10817 				fmode = MODE_IS_INCLUDE;
10818 				optfn = ip_opt_delete_group;
10819 				break;
10820 			}
10821 
10822 			if (mcast_opt) {
10823 				gsreqp = (struct group_source_req *)i1;
10824 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10825 					*outlenp = 0;
10826 					return (ENOPROTOOPT);
10827 				}
10828 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10829 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10830 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10831 				src = (ipaddr_t)sin->sin_addr.s_addr;
10832 				ifindex = gsreqp->gsr_interface;
10833 			} else {
10834 				imreqp = (struct ip_mreq_source *)i1;
10835 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10836 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10837 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10838 			}
10839 
10840 			/*
10841 			 * In the multirouting case, we need to replicate
10842 			 * the request as noted in the mcast cases above.
10843 			 */
10844 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10845 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10846 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10847 			if (ire != NULL) {
10848 				if (ire->ire_flags & RTF_MULTIRT) {
10849 					error = ip_multirt_apply_membership(
10850 					    optfn, ire, connp, checkonly, grp,
10851 					    fmode, src, first_mp);
10852 					done = B_TRUE;
10853 				}
10854 				ire_refrele(ire);
10855 			}
10856 			if (!done) {
10857 				error = optfn(connp, checkonly, grp, ifaddr,
10858 				    &ifindex, fmode, src, first_mp);
10859 			}
10860 			if (error != 0) {
10861 				/*
10862 				 * EINPROGRESS is a soft error, needs retry
10863 				 * so don't make *outlenp zero.
10864 				 */
10865 				if (error != EINPROGRESS)
10866 					*outlenp = 0;
10867 				return (error);
10868 			}
10869 			/* OK return - copy input buffer into output buffer */
10870 			if (invalp != outvalp) {
10871 				bcopy(invalp, outvalp, inlen);
10872 			}
10873 			*outlenp = inlen;
10874 			return (0);
10875 		}
10876 		case IP_SEC_OPT:
10877 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10878 			if (error != 0) {
10879 				*outlenp = 0;
10880 				return (error);
10881 			}
10882 			break;
10883 		case IP_HDRINCL:
10884 		case IP_OPTIONS:
10885 		case T_IP_OPTIONS:
10886 		case IP_TOS:
10887 		case T_IP_TOS:
10888 		case IP_TTL:
10889 		case IP_RECVDSTADDR:
10890 		case IP_RECVOPTS:
10891 			/* OK return - copy input buffer into output buffer */
10892 			if (invalp != outvalp) {
10893 				/* don't trust bcopy for identical src/dst */
10894 				bcopy(invalp, outvalp, inlen);
10895 			}
10896 			*outlenp = inlen;
10897 			return (0);
10898 		case IP_RECVIF:
10899 			/* Retrieve the inbound interface index */
10900 			if (!checkonly) {
10901 				mutex_enter(&connp->conn_lock);
10902 				connp->conn_recvif = *i1 ? 1 : 0;
10903 				mutex_exit(&connp->conn_lock);
10904 			}
10905 			break;	/* goto sizeof (int) option return */
10906 		case IP_RECVPKTINFO:
10907 			if (!checkonly) {
10908 				mutex_enter(&connp->conn_lock);
10909 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10910 				mutex_exit(&connp->conn_lock);
10911 			}
10912 			break;	/* goto sizeof (int) option return */
10913 		case IP_RECVSLLA:
10914 			/* Retrieve the source link layer address */
10915 			if (!checkonly) {
10916 				mutex_enter(&connp->conn_lock);
10917 				connp->conn_recvslla = *i1 ? 1 : 0;
10918 				mutex_exit(&connp->conn_lock);
10919 			}
10920 			break;	/* goto sizeof (int) option return */
10921 		case MRT_INIT:
10922 		case MRT_DONE:
10923 		case MRT_ADD_VIF:
10924 		case MRT_DEL_VIF:
10925 		case MRT_ADD_MFC:
10926 		case MRT_DEL_MFC:
10927 		case MRT_ASSERT:
10928 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10929 				*outlenp = 0;
10930 				return (error);
10931 			}
10932 			error = ip_mrouter_set((int)name, q, checkonly,
10933 			    (uchar_t *)invalp, inlen, first_mp);
10934 			if (error) {
10935 				*outlenp = 0;
10936 				return (error);
10937 			}
10938 			/* OK return - copy input buffer into output buffer */
10939 			if (invalp != outvalp) {
10940 				/* don't trust bcopy for identical src/dst */
10941 				bcopy(invalp, outvalp, inlen);
10942 			}
10943 			*outlenp = inlen;
10944 			return (0);
10945 		case IP_BOUND_IF:
10946 		case IP_DHCPINIT_IF:
10947 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10948 			    level, name, first_mp);
10949 			if (error != 0)
10950 				return (error);
10951 			break; 		/* goto sizeof (int) option return */
10952 
10953 		case IP_UNSPEC_SRC:
10954 			/* Allow sending with a zero source address */
10955 			if (!checkonly) {
10956 				mutex_enter(&connp->conn_lock);
10957 				connp->conn_unspec_src = *i1 ? 1 : 0;
10958 				mutex_exit(&connp->conn_lock);
10959 			}
10960 			break;	/* goto sizeof (int) option return */
10961 		default:
10962 			/*
10963 			 * "soft" error (negative)
10964 			 * option not handled at this level
10965 			 * Note: Do not modify *outlenp
10966 			 */
10967 			return (-EINVAL);
10968 		}
10969 		break;
10970 	case IPPROTO_IPV6:
10971 		switch (name) {
10972 		case IPV6_BOUND_IF:
10973 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10974 			    level, name, first_mp);
10975 			if (error != 0)
10976 				return (error);
10977 			break; 		/* goto sizeof (int) option return */
10978 
10979 		case IPV6_MULTICAST_IF:
10980 			/*
10981 			 * The only possible errors are EINPROGRESS and
10982 			 * EINVAL. EINPROGRESS will be restarted and is not
10983 			 * a hard error. We call this option on both V4 and V6
10984 			 * If both return EINVAL, then this call returns
10985 			 * EINVAL. If at least one of them succeeds we
10986 			 * return success.
10987 			 */
10988 			found = B_FALSE;
10989 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10990 			    level, name, first_mp);
10991 			if (error == EINPROGRESS)
10992 				return (error);
10993 			if (error == 0)
10994 				found = B_TRUE;
10995 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10996 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10997 			if (error == 0)
10998 				found = B_TRUE;
10999 			if (!found)
11000 				return (error);
11001 			break; 		/* goto sizeof (int) option return */
11002 
11003 		case IPV6_MULTICAST_HOPS:
11004 			/* Recorded in transport above IP */
11005 			break;	/* goto sizeof (int) option return */
11006 		case IPV6_MULTICAST_LOOP:
11007 			if (!checkonly) {
11008 				mutex_enter(&connp->conn_lock);
11009 				connp->conn_multicast_loop = *i1;
11010 				mutex_exit(&connp->conn_lock);
11011 			}
11012 			break;	/* goto sizeof (int) option return */
11013 		case IPV6_JOIN_GROUP:
11014 		case MCAST_JOIN_GROUP:
11015 		case IPV6_LEAVE_GROUP:
11016 		case MCAST_LEAVE_GROUP: {
11017 			struct ipv6_mreq *ip_mreqp;
11018 			struct group_req *greqp;
11019 			ire_t *ire;
11020 			boolean_t done = B_FALSE;
11021 			in6_addr_t groupv6;
11022 			uint32_t ifindex;
11023 			boolean_t mcast_opt = B_TRUE;
11024 			mcast_record_t fmode;
11025 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11026 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11027 
11028 			switch (name) {
11029 			case IPV6_JOIN_GROUP:
11030 				mcast_opt = B_FALSE;
11031 				/* FALLTHRU */
11032 			case MCAST_JOIN_GROUP:
11033 				fmode = MODE_IS_EXCLUDE;
11034 				optfn = ip_opt_add_group_v6;
11035 				break;
11036 
11037 			case IPV6_LEAVE_GROUP:
11038 				mcast_opt = B_FALSE;
11039 				/* FALLTHRU */
11040 			case MCAST_LEAVE_GROUP:
11041 				fmode = MODE_IS_INCLUDE;
11042 				optfn = ip_opt_delete_group_v6;
11043 				break;
11044 			}
11045 
11046 			if (mcast_opt) {
11047 				struct sockaddr_in *sin;
11048 				struct sockaddr_in6 *sin6;
11049 				greqp = (struct group_req *)i1;
11050 				if (greqp->gr_group.ss_family == AF_INET) {
11051 					sin = (struct sockaddr_in *)
11052 					    &(greqp->gr_group);
11053 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11054 					    &groupv6);
11055 				} else {
11056 					sin6 = (struct sockaddr_in6 *)
11057 					    &(greqp->gr_group);
11058 					groupv6 = sin6->sin6_addr;
11059 				}
11060 				ifindex = greqp->gr_interface;
11061 			} else {
11062 				ip_mreqp = (struct ipv6_mreq *)i1;
11063 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11064 				ifindex = ip_mreqp->ipv6mr_interface;
11065 			}
11066 			/*
11067 			 * In the multirouting case, we need to replicate
11068 			 * the request on all interfaces that will take part
11069 			 * in replication.  We do so because multirouting is
11070 			 * reflective, thus we will probably receive multi-
11071 			 * casts on those interfaces.
11072 			 * The ip_multirt_apply_membership_v6() succeeds if
11073 			 * the operation succeeds on at least one interface.
11074 			 */
11075 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11076 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11077 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11078 			if (ire != NULL) {
11079 				if (ire->ire_flags & RTF_MULTIRT) {
11080 					error = ip_multirt_apply_membership_v6(
11081 					    optfn, ire, connp, checkonly,
11082 					    &groupv6, fmode, &ipv6_all_zeros,
11083 					    first_mp);
11084 					done = B_TRUE;
11085 				}
11086 				ire_refrele(ire);
11087 			}
11088 			if (!done) {
11089 				error = optfn(connp, checkonly, &groupv6,
11090 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11091 			}
11092 			if (error) {
11093 				/*
11094 				 * EINPROGRESS is a soft error, needs retry
11095 				 * so don't make *outlenp zero.
11096 				 */
11097 				if (error != EINPROGRESS)
11098 					*outlenp = 0;
11099 				return (error);
11100 			}
11101 			/* OK return - copy input buffer into output buffer */
11102 			if (invalp != outvalp) {
11103 				/* don't trust bcopy for identical src/dst */
11104 				bcopy(invalp, outvalp, inlen);
11105 			}
11106 			*outlenp = inlen;
11107 			return (0);
11108 		}
11109 		case MCAST_BLOCK_SOURCE:
11110 		case MCAST_UNBLOCK_SOURCE:
11111 		case MCAST_JOIN_SOURCE_GROUP:
11112 		case MCAST_LEAVE_SOURCE_GROUP: {
11113 			struct group_source_req *gsreqp;
11114 			in6_addr_t v6grp, v6src;
11115 			uint32_t ifindex;
11116 			mcast_record_t fmode;
11117 			ire_t *ire;
11118 			boolean_t done = B_FALSE;
11119 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11120 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11121 
11122 			switch (name) {
11123 			case MCAST_BLOCK_SOURCE:
11124 				fmode = MODE_IS_EXCLUDE;
11125 				optfn = ip_opt_add_group_v6;
11126 				break;
11127 			case MCAST_UNBLOCK_SOURCE:
11128 				fmode = MODE_IS_EXCLUDE;
11129 				optfn = ip_opt_delete_group_v6;
11130 				break;
11131 			case MCAST_JOIN_SOURCE_GROUP:
11132 				fmode = MODE_IS_INCLUDE;
11133 				optfn = ip_opt_add_group_v6;
11134 				break;
11135 			case MCAST_LEAVE_SOURCE_GROUP:
11136 				fmode = MODE_IS_INCLUDE;
11137 				optfn = ip_opt_delete_group_v6;
11138 				break;
11139 			}
11140 
11141 			gsreqp = (struct group_source_req *)i1;
11142 			ifindex = gsreqp->gsr_interface;
11143 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11144 				struct sockaddr_in *s;
11145 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11146 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11147 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11148 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11149 			} else {
11150 				struct sockaddr_in6 *s6;
11151 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11152 				v6grp = s6->sin6_addr;
11153 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11154 				v6src = s6->sin6_addr;
11155 			}
11156 
11157 			/*
11158 			 * In the multirouting case, we need to replicate
11159 			 * the request as noted in the mcast cases above.
11160 			 */
11161 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11162 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11163 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11164 			if (ire != NULL) {
11165 				if (ire->ire_flags & RTF_MULTIRT) {
11166 					error = ip_multirt_apply_membership_v6(
11167 					    optfn, ire, connp, checkonly,
11168 					    &v6grp, fmode, &v6src, first_mp);
11169 					done = B_TRUE;
11170 				}
11171 				ire_refrele(ire);
11172 			}
11173 			if (!done) {
11174 				error = optfn(connp, checkonly, &v6grp,
11175 				    ifindex, fmode, &v6src, first_mp);
11176 			}
11177 			if (error != 0) {
11178 				/*
11179 				 * EINPROGRESS is a soft error, needs retry
11180 				 * so don't make *outlenp zero.
11181 				 */
11182 				if (error != EINPROGRESS)
11183 					*outlenp = 0;
11184 				return (error);
11185 			}
11186 			/* OK return - copy input buffer into output buffer */
11187 			if (invalp != outvalp) {
11188 				bcopy(invalp, outvalp, inlen);
11189 			}
11190 			*outlenp = inlen;
11191 			return (0);
11192 		}
11193 		case IPV6_UNICAST_HOPS:
11194 			/* Recorded in transport above IP */
11195 			break;	/* goto sizeof (int) option return */
11196 		case IPV6_UNSPEC_SRC:
11197 			/* Allow sending with a zero source address */
11198 			if (!checkonly) {
11199 				mutex_enter(&connp->conn_lock);
11200 				connp->conn_unspec_src = *i1 ? 1 : 0;
11201 				mutex_exit(&connp->conn_lock);
11202 			}
11203 			break;	/* goto sizeof (int) option return */
11204 		case IPV6_RECVPKTINFO:
11205 			if (!checkonly) {
11206 				mutex_enter(&connp->conn_lock);
11207 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11208 				mutex_exit(&connp->conn_lock);
11209 			}
11210 			break;	/* goto sizeof (int) option return */
11211 		case IPV6_RECVTCLASS:
11212 			if (!checkonly) {
11213 				if (*i1 < 0 || *i1 > 1) {
11214 					return (EINVAL);
11215 				}
11216 				mutex_enter(&connp->conn_lock);
11217 				connp->conn_ipv6_recvtclass = *i1;
11218 				mutex_exit(&connp->conn_lock);
11219 			}
11220 			break;
11221 		case IPV6_RECVPATHMTU:
11222 			if (!checkonly) {
11223 				if (*i1 < 0 || *i1 > 1) {
11224 					return (EINVAL);
11225 				}
11226 				mutex_enter(&connp->conn_lock);
11227 				connp->conn_ipv6_recvpathmtu = *i1;
11228 				mutex_exit(&connp->conn_lock);
11229 			}
11230 			break;
11231 		case IPV6_RECVHOPLIMIT:
11232 			if (!checkonly) {
11233 				mutex_enter(&connp->conn_lock);
11234 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11235 				mutex_exit(&connp->conn_lock);
11236 			}
11237 			break;	/* goto sizeof (int) option return */
11238 		case IPV6_RECVHOPOPTS:
11239 			if (!checkonly) {
11240 				mutex_enter(&connp->conn_lock);
11241 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11242 				mutex_exit(&connp->conn_lock);
11243 			}
11244 			break;	/* goto sizeof (int) option return */
11245 		case IPV6_RECVDSTOPTS:
11246 			if (!checkonly) {
11247 				mutex_enter(&connp->conn_lock);
11248 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11249 				mutex_exit(&connp->conn_lock);
11250 			}
11251 			break;	/* goto sizeof (int) option return */
11252 		case IPV6_RECVRTHDR:
11253 			if (!checkonly) {
11254 				mutex_enter(&connp->conn_lock);
11255 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11256 				mutex_exit(&connp->conn_lock);
11257 			}
11258 			break;	/* goto sizeof (int) option return */
11259 		case IPV6_RECVRTHDRDSTOPTS:
11260 			if (!checkonly) {
11261 				mutex_enter(&connp->conn_lock);
11262 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11263 				mutex_exit(&connp->conn_lock);
11264 			}
11265 			break;	/* goto sizeof (int) option return */
11266 		case IPV6_PKTINFO:
11267 			if (inlen == 0)
11268 				return (-EINVAL);	/* clearing option */
11269 			error = ip6_set_pktinfo(cr, connp,
11270 			    (struct in6_pktinfo *)invalp);
11271 			if (error != 0)
11272 				*outlenp = 0;
11273 			else
11274 				*outlenp = inlen;
11275 			return (error);
11276 		case IPV6_NEXTHOP: {
11277 			struct sockaddr_in6 *sin6;
11278 
11279 			/* Verify that the nexthop is reachable */
11280 			if (inlen == 0)
11281 				return (-EINVAL);	/* clearing option */
11282 
11283 			sin6 = (struct sockaddr_in6 *)invalp;
11284 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11285 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11286 			    NULL, MATCH_IRE_DEFAULT, ipst);
11287 
11288 			if (ire == NULL) {
11289 				*outlenp = 0;
11290 				return (EHOSTUNREACH);
11291 			}
11292 			ire_refrele(ire);
11293 			return (-EINVAL);
11294 		}
11295 		case IPV6_SEC_OPT:
11296 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11297 			if (error != 0) {
11298 				*outlenp = 0;
11299 				return (error);
11300 			}
11301 			break;
11302 		case IPV6_SRC_PREFERENCES: {
11303 			/*
11304 			 * This is implemented strictly in the ip module
11305 			 * (here and in tcp_opt_*() to accomodate tcp
11306 			 * sockets).  Modules above ip pass this option
11307 			 * down here since ip is the only one that needs to
11308 			 * be aware of source address preferences.
11309 			 *
11310 			 * This socket option only affects connected
11311 			 * sockets that haven't already bound to a specific
11312 			 * IPv6 address.  In other words, sockets that
11313 			 * don't call bind() with an address other than the
11314 			 * unspecified address and that call connect().
11315 			 * ip_bind_connected_v6() passes these preferences
11316 			 * to the ipif_select_source_v6() function.
11317 			 */
11318 			if (inlen != sizeof (uint32_t))
11319 				return (EINVAL);
11320 			error = ip6_set_src_preferences(connp,
11321 			    *(uint32_t *)invalp);
11322 			if (error != 0) {
11323 				*outlenp = 0;
11324 				return (error);
11325 			} else {
11326 				*outlenp = sizeof (uint32_t);
11327 			}
11328 			break;
11329 		}
11330 		case IPV6_V6ONLY:
11331 			if (*i1 < 0 || *i1 > 1) {
11332 				return (EINVAL);
11333 			}
11334 			mutex_enter(&connp->conn_lock);
11335 			connp->conn_ipv6_v6only = *i1;
11336 			mutex_exit(&connp->conn_lock);
11337 			break;
11338 		default:
11339 			return (-EINVAL);
11340 		}
11341 		break;
11342 	default:
11343 		/*
11344 		 * "soft" error (negative)
11345 		 * option not handled at this level
11346 		 * Note: Do not modify *outlenp
11347 		 */
11348 		return (-EINVAL);
11349 	}
11350 	/*
11351 	 * Common case of return from an option that is sizeof (int)
11352 	 */
11353 	*(int *)outvalp = *i1;
11354 	*outlenp = sizeof (int);
11355 	return (0);
11356 }
11357 
11358 /*
11359  * This routine gets default values of certain options whose default
11360  * values are maintained by protocol specific code
11361  */
11362 /* ARGSUSED */
11363 int
11364 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11365 {
11366 	int *i1 = (int *)ptr;
11367 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11368 
11369 	switch (level) {
11370 	case IPPROTO_IP:
11371 		switch (name) {
11372 		case IP_MULTICAST_TTL:
11373 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11374 			return (sizeof (uchar_t));
11375 		case IP_MULTICAST_LOOP:
11376 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11377 			return (sizeof (uchar_t));
11378 		default:
11379 			return (-1);
11380 		}
11381 	case IPPROTO_IPV6:
11382 		switch (name) {
11383 		case IPV6_UNICAST_HOPS:
11384 			*i1 = ipst->ips_ipv6_def_hops;
11385 			return (sizeof (int));
11386 		case IPV6_MULTICAST_HOPS:
11387 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11388 			return (sizeof (int));
11389 		case IPV6_MULTICAST_LOOP:
11390 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11391 			return (sizeof (int));
11392 		case IPV6_V6ONLY:
11393 			*i1 = 1;
11394 			return (sizeof (int));
11395 		default:
11396 			return (-1);
11397 		}
11398 	default:
11399 		return (-1);
11400 	}
11401 	/* NOTREACHED */
11402 }
11403 
11404 /*
11405  * Given a destination address and a pointer to where to put the information
11406  * this routine fills in the mtuinfo.
11407  */
11408 int
11409 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11410     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11411 {
11412 	ire_t *ire;
11413 	ip_stack_t	*ipst = ns->netstack_ip;
11414 
11415 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11416 		return (-1);
11417 
11418 	bzero(mtuinfo, sizeof (*mtuinfo));
11419 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11420 	mtuinfo->ip6m_addr.sin6_port = port;
11421 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11422 
11423 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11424 	if (ire != NULL) {
11425 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11426 		ire_refrele(ire);
11427 	} else {
11428 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11429 	}
11430 	return (sizeof (struct ip6_mtuinfo));
11431 }
11432 
11433 /*
11434  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11435  * checking of cred and that ip_g_mrouter is set should be done and
11436  * isn't.  This doesn't matter as the error checking is done properly for the
11437  * other MRT options coming in through ip_opt_set.
11438  */
11439 int
11440 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11441 {
11442 	conn_t		*connp = Q_TO_CONN(q);
11443 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11444 
11445 	switch (level) {
11446 	case IPPROTO_IP:
11447 		switch (name) {
11448 		case MRT_VERSION:
11449 		case MRT_ASSERT:
11450 			(void) ip_mrouter_get(name, q, ptr);
11451 			return (sizeof (int));
11452 		case IP_SEC_OPT:
11453 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11454 		case IP_NEXTHOP:
11455 			if (connp->conn_nexthop_set) {
11456 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11457 				return (sizeof (ipaddr_t));
11458 			} else
11459 				return (0);
11460 		case IP_RECVPKTINFO:
11461 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11462 			return (sizeof (int));
11463 		default:
11464 			break;
11465 		}
11466 		break;
11467 	case IPPROTO_IPV6:
11468 		switch (name) {
11469 		case IPV6_SEC_OPT:
11470 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11471 		case IPV6_SRC_PREFERENCES: {
11472 			return (ip6_get_src_preferences(connp,
11473 			    (uint32_t *)ptr));
11474 		}
11475 		case IPV6_V6ONLY:
11476 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11477 			return (sizeof (int));
11478 		case IPV6_PATHMTU:
11479 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11480 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11481 		default:
11482 			break;
11483 		}
11484 		break;
11485 	default:
11486 		break;
11487 	}
11488 	return (-1);
11489 }
11490 /* Named Dispatch routine to get a current value out of our parameter table. */
11491 /* ARGSUSED */
11492 static int
11493 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11494 {
11495 	ipparam_t *ippa = (ipparam_t *)cp;
11496 
11497 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11498 	return (0);
11499 }
11500 
11501 /* ARGSUSED */
11502 static int
11503 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11504 {
11505 
11506 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11507 	return (0);
11508 }
11509 
11510 /*
11511  * Set ip{,6}_forwarding values.  This means walking through all of the
11512  * ill's and toggling their forwarding values.
11513  */
11514 /* ARGSUSED */
11515 static int
11516 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11517 {
11518 	long new_value;
11519 	int *forwarding_value = (int *)cp;
11520 	ill_t *ill;
11521 	boolean_t isv6;
11522 	ill_walk_context_t ctx;
11523 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11524 
11525 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11526 
11527 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11528 	    new_value < 0 || new_value > 1) {
11529 		return (EINVAL);
11530 	}
11531 
11532 	*forwarding_value = new_value;
11533 
11534 	/*
11535 	 * Regardless of the current value of ip_forwarding, set all per-ill
11536 	 * values of ip_forwarding to the value being set.
11537 	 *
11538 	 * Bring all the ill's up to date with the new global value.
11539 	 */
11540 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11541 
11542 	if (isv6)
11543 		ill = ILL_START_WALK_V6(&ctx, ipst);
11544 	else
11545 		ill = ILL_START_WALK_V4(&ctx, ipst);
11546 
11547 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11548 		(void) ill_forward_set(ill, new_value != 0);
11549 
11550 	rw_exit(&ipst->ips_ill_g_lock);
11551 	return (0);
11552 }
11553 
11554 /*
11555  * Walk through the param array specified registering each element with the
11556  * Named Dispatch handler. This is called only during init. So it is ok
11557  * not to acquire any locks
11558  */
11559 static boolean_t
11560 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11561     ipndp_t *ipnd, size_t ipnd_cnt)
11562 {
11563 	for (; ippa_cnt-- > 0; ippa++) {
11564 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11565 			if (!nd_load(ndp, ippa->ip_param_name,
11566 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11567 				nd_free(ndp);
11568 				return (B_FALSE);
11569 			}
11570 		}
11571 	}
11572 
11573 	for (; ipnd_cnt-- > 0; ipnd++) {
11574 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11575 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11576 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11577 			    ipnd->ip_ndp_data)) {
11578 				nd_free(ndp);
11579 				return (B_FALSE);
11580 			}
11581 		}
11582 	}
11583 
11584 	return (B_TRUE);
11585 }
11586 
11587 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11588 /* ARGSUSED */
11589 static int
11590 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11591 {
11592 	long		new_value;
11593 	ipparam_t	*ippa = (ipparam_t *)cp;
11594 
11595 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11596 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11597 		return (EINVAL);
11598 	}
11599 	ippa->ip_param_value = new_value;
11600 	return (0);
11601 }
11602 
11603 /*
11604  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11605  * When an ipf is passed here for the first time, if
11606  * we already have in-order fragments on the queue, we convert from the fast-
11607  * path reassembly scheme to the hard-case scheme.  From then on, additional
11608  * fragments are reassembled here.  We keep track of the start and end offsets
11609  * of each piece, and the number of holes in the chain.  When the hole count
11610  * goes to zero, we are done!
11611  *
11612  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11613  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11614  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11615  * after the call to ip_reassemble().
11616  */
11617 int
11618 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11619     size_t msg_len)
11620 {
11621 	uint_t	end;
11622 	mblk_t	*next_mp;
11623 	mblk_t	*mp1;
11624 	uint_t	offset;
11625 	boolean_t incr_dups = B_TRUE;
11626 	boolean_t offset_zero_seen = B_FALSE;
11627 	boolean_t pkt_boundary_checked = B_FALSE;
11628 
11629 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11630 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11631 
11632 	/* Add in byte count */
11633 	ipf->ipf_count += msg_len;
11634 	if (ipf->ipf_end) {
11635 		/*
11636 		 * We were part way through in-order reassembly, but now there
11637 		 * is a hole.  We walk through messages already queued, and
11638 		 * mark them for hard case reassembly.  We know that up till
11639 		 * now they were in order starting from offset zero.
11640 		 */
11641 		offset = 0;
11642 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11643 			IP_REASS_SET_START(mp1, offset);
11644 			if (offset == 0) {
11645 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11646 				offset = -ipf->ipf_nf_hdr_len;
11647 			}
11648 			offset += mp1->b_wptr - mp1->b_rptr;
11649 			IP_REASS_SET_END(mp1, offset);
11650 		}
11651 		/* One hole at the end. */
11652 		ipf->ipf_hole_cnt = 1;
11653 		/* Brand it as a hard case, forever. */
11654 		ipf->ipf_end = 0;
11655 	}
11656 	/* Walk through all the new pieces. */
11657 	do {
11658 		end = start + (mp->b_wptr - mp->b_rptr);
11659 		/*
11660 		 * If start is 0, decrease 'end' only for the first mblk of
11661 		 * the fragment. Otherwise 'end' can get wrong value in the
11662 		 * second pass of the loop if first mblk is exactly the
11663 		 * size of ipf_nf_hdr_len.
11664 		 */
11665 		if (start == 0 && !offset_zero_seen) {
11666 			/* First segment */
11667 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11668 			end -= ipf->ipf_nf_hdr_len;
11669 			offset_zero_seen = B_TRUE;
11670 		}
11671 		next_mp = mp->b_cont;
11672 		/*
11673 		 * We are checking to see if there is any interesing data
11674 		 * to process.  If there isn't and the mblk isn't the
11675 		 * one which carries the unfragmentable header then we
11676 		 * drop it.  It's possible to have just the unfragmentable
11677 		 * header come through without any data.  That needs to be
11678 		 * saved.
11679 		 *
11680 		 * If the assert at the top of this function holds then the
11681 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11682 		 * is infrequently traveled enough that the test is left in
11683 		 * to protect against future code changes which break that
11684 		 * invariant.
11685 		 */
11686 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11687 			/* Empty.  Blast it. */
11688 			IP_REASS_SET_START(mp, 0);
11689 			IP_REASS_SET_END(mp, 0);
11690 			/*
11691 			 * If the ipf points to the mblk we are about to free,
11692 			 * update ipf to point to the next mblk (or NULL
11693 			 * if none).
11694 			 */
11695 			if (ipf->ipf_mp->b_cont == mp)
11696 				ipf->ipf_mp->b_cont = next_mp;
11697 			freeb(mp);
11698 			continue;
11699 		}
11700 		mp->b_cont = NULL;
11701 		IP_REASS_SET_START(mp, start);
11702 		IP_REASS_SET_END(mp, end);
11703 		if (!ipf->ipf_tail_mp) {
11704 			ipf->ipf_tail_mp = mp;
11705 			ipf->ipf_mp->b_cont = mp;
11706 			if (start == 0 || !more) {
11707 				ipf->ipf_hole_cnt = 1;
11708 				/*
11709 				 * if the first fragment comes in more than one
11710 				 * mblk, this loop will be executed for each
11711 				 * mblk. Need to adjust hole count so exiting
11712 				 * this routine will leave hole count at 1.
11713 				 */
11714 				if (next_mp)
11715 					ipf->ipf_hole_cnt++;
11716 			} else
11717 				ipf->ipf_hole_cnt = 2;
11718 			continue;
11719 		} else if (ipf->ipf_last_frag_seen && !more &&
11720 		    !pkt_boundary_checked) {
11721 			/*
11722 			 * We check datagram boundary only if this fragment
11723 			 * claims to be the last fragment and we have seen a
11724 			 * last fragment in the past too. We do this only
11725 			 * once for a given fragment.
11726 			 *
11727 			 * start cannot be 0 here as fragments with start=0
11728 			 * and MF=0 gets handled as a complete packet. These
11729 			 * fragments should not reach here.
11730 			 */
11731 
11732 			if (start + msgdsize(mp) !=
11733 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11734 				/*
11735 				 * We have two fragments both of which claim
11736 				 * to be the last fragment but gives conflicting
11737 				 * information about the whole datagram size.
11738 				 * Something fishy is going on. Drop the
11739 				 * fragment and free up the reassembly list.
11740 				 */
11741 				return (IP_REASS_FAILED);
11742 			}
11743 
11744 			/*
11745 			 * We shouldn't come to this code block again for this
11746 			 * particular fragment.
11747 			 */
11748 			pkt_boundary_checked = B_TRUE;
11749 		}
11750 
11751 		/* New stuff at or beyond tail? */
11752 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11753 		if (start >= offset) {
11754 			if (ipf->ipf_last_frag_seen) {
11755 				/* current fragment is beyond last fragment */
11756 				return (IP_REASS_FAILED);
11757 			}
11758 			/* Link it on end. */
11759 			ipf->ipf_tail_mp->b_cont = mp;
11760 			ipf->ipf_tail_mp = mp;
11761 			if (more) {
11762 				if (start != offset)
11763 					ipf->ipf_hole_cnt++;
11764 			} else if (start == offset && next_mp == NULL)
11765 					ipf->ipf_hole_cnt--;
11766 			continue;
11767 		}
11768 		mp1 = ipf->ipf_mp->b_cont;
11769 		offset = IP_REASS_START(mp1);
11770 		/* New stuff at the front? */
11771 		if (start < offset) {
11772 			if (start == 0) {
11773 				if (end >= offset) {
11774 					/* Nailed the hole at the begining. */
11775 					ipf->ipf_hole_cnt--;
11776 				}
11777 			} else if (end < offset) {
11778 				/*
11779 				 * A hole, stuff, and a hole where there used
11780 				 * to be just a hole.
11781 				 */
11782 				ipf->ipf_hole_cnt++;
11783 			}
11784 			mp->b_cont = mp1;
11785 			/* Check for overlap. */
11786 			while (end > offset) {
11787 				if (end < IP_REASS_END(mp1)) {
11788 					mp->b_wptr -= end - offset;
11789 					IP_REASS_SET_END(mp, offset);
11790 					BUMP_MIB(ill->ill_ip_mib,
11791 					    ipIfStatsReasmPartDups);
11792 					break;
11793 				}
11794 				/* Did we cover another hole? */
11795 				if ((mp1->b_cont &&
11796 				    IP_REASS_END(mp1) !=
11797 				    IP_REASS_START(mp1->b_cont) &&
11798 				    end >= IP_REASS_START(mp1->b_cont)) ||
11799 				    (!ipf->ipf_last_frag_seen && !more)) {
11800 					ipf->ipf_hole_cnt--;
11801 				}
11802 				/* Clip out mp1. */
11803 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11804 					/*
11805 					 * After clipping out mp1, this guy
11806 					 * is now hanging off the end.
11807 					 */
11808 					ipf->ipf_tail_mp = mp;
11809 				}
11810 				IP_REASS_SET_START(mp1, 0);
11811 				IP_REASS_SET_END(mp1, 0);
11812 				/* Subtract byte count */
11813 				ipf->ipf_count -= mp1->b_datap->db_lim -
11814 				    mp1->b_datap->db_base;
11815 				freeb(mp1);
11816 				BUMP_MIB(ill->ill_ip_mib,
11817 				    ipIfStatsReasmPartDups);
11818 				mp1 = mp->b_cont;
11819 				if (!mp1)
11820 					break;
11821 				offset = IP_REASS_START(mp1);
11822 			}
11823 			ipf->ipf_mp->b_cont = mp;
11824 			continue;
11825 		}
11826 		/*
11827 		 * The new piece starts somewhere between the start of the head
11828 		 * and before the end of the tail.
11829 		 */
11830 		for (; mp1; mp1 = mp1->b_cont) {
11831 			offset = IP_REASS_END(mp1);
11832 			if (start < offset) {
11833 				if (end <= offset) {
11834 					/* Nothing new. */
11835 					IP_REASS_SET_START(mp, 0);
11836 					IP_REASS_SET_END(mp, 0);
11837 					/* Subtract byte count */
11838 					ipf->ipf_count -= mp->b_datap->db_lim -
11839 					    mp->b_datap->db_base;
11840 					if (incr_dups) {
11841 						ipf->ipf_num_dups++;
11842 						incr_dups = B_FALSE;
11843 					}
11844 					freeb(mp);
11845 					BUMP_MIB(ill->ill_ip_mib,
11846 					    ipIfStatsReasmDuplicates);
11847 					break;
11848 				}
11849 				/*
11850 				 * Trim redundant stuff off beginning of new
11851 				 * piece.
11852 				 */
11853 				IP_REASS_SET_START(mp, offset);
11854 				mp->b_rptr += offset - start;
11855 				BUMP_MIB(ill->ill_ip_mib,
11856 				    ipIfStatsReasmPartDups);
11857 				start = offset;
11858 				if (!mp1->b_cont) {
11859 					/*
11860 					 * After trimming, this guy is now
11861 					 * hanging off the end.
11862 					 */
11863 					mp1->b_cont = mp;
11864 					ipf->ipf_tail_mp = mp;
11865 					if (!more) {
11866 						ipf->ipf_hole_cnt--;
11867 					}
11868 					break;
11869 				}
11870 			}
11871 			if (start >= IP_REASS_START(mp1->b_cont))
11872 				continue;
11873 			/* Fill a hole */
11874 			if (start > offset)
11875 				ipf->ipf_hole_cnt++;
11876 			mp->b_cont = mp1->b_cont;
11877 			mp1->b_cont = mp;
11878 			mp1 = mp->b_cont;
11879 			offset = IP_REASS_START(mp1);
11880 			if (end >= offset) {
11881 				ipf->ipf_hole_cnt--;
11882 				/* Check for overlap. */
11883 				while (end > offset) {
11884 					if (end < IP_REASS_END(mp1)) {
11885 						mp->b_wptr -= end - offset;
11886 						IP_REASS_SET_END(mp, offset);
11887 						/*
11888 						 * TODO we might bump
11889 						 * this up twice if there is
11890 						 * overlap at both ends.
11891 						 */
11892 						BUMP_MIB(ill->ill_ip_mib,
11893 						    ipIfStatsReasmPartDups);
11894 						break;
11895 					}
11896 					/* Did we cover another hole? */
11897 					if ((mp1->b_cont &&
11898 					    IP_REASS_END(mp1)
11899 					    != IP_REASS_START(mp1->b_cont) &&
11900 					    end >=
11901 					    IP_REASS_START(mp1->b_cont)) ||
11902 					    (!ipf->ipf_last_frag_seen &&
11903 					    !more)) {
11904 						ipf->ipf_hole_cnt--;
11905 					}
11906 					/* Clip out mp1. */
11907 					if ((mp->b_cont = mp1->b_cont) ==
11908 					    NULL) {
11909 						/*
11910 						 * After clipping out mp1,
11911 						 * this guy is now hanging
11912 						 * off the end.
11913 						 */
11914 						ipf->ipf_tail_mp = mp;
11915 					}
11916 					IP_REASS_SET_START(mp1, 0);
11917 					IP_REASS_SET_END(mp1, 0);
11918 					/* Subtract byte count */
11919 					ipf->ipf_count -=
11920 					    mp1->b_datap->db_lim -
11921 					    mp1->b_datap->db_base;
11922 					freeb(mp1);
11923 					BUMP_MIB(ill->ill_ip_mib,
11924 					    ipIfStatsReasmPartDups);
11925 					mp1 = mp->b_cont;
11926 					if (!mp1)
11927 						break;
11928 					offset = IP_REASS_START(mp1);
11929 				}
11930 			}
11931 			break;
11932 		}
11933 	} while (start = end, mp = next_mp);
11934 
11935 	/* Fragment just processed could be the last one. Remember this fact */
11936 	if (!more)
11937 		ipf->ipf_last_frag_seen = B_TRUE;
11938 
11939 	/* Still got holes? */
11940 	if (ipf->ipf_hole_cnt)
11941 		return (IP_REASS_PARTIAL);
11942 	/* Clean up overloaded fields to avoid upstream disasters. */
11943 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11944 		IP_REASS_SET_START(mp1, 0);
11945 		IP_REASS_SET_END(mp1, 0);
11946 	}
11947 	return (IP_REASS_COMPLETE);
11948 }
11949 
11950 /*
11951  * ipsec processing for the fast path, used for input UDP Packets
11952  * Returns true if ready for passup to UDP.
11953  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
11954  * was an ESP-in-UDP packet, etc.).
11955  */
11956 static boolean_t
11957 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11958     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
11959 {
11960 	uint32_t	ill_index;
11961 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11962 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11963 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11964 	udp_t		*udp = connp->conn_udp;
11965 
11966 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11967 	/* The ill_index of the incoming ILL */
11968 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11969 
11970 	/* pass packet up to the transport */
11971 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11972 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11973 		    NULL, mctl_present);
11974 		if (*first_mpp == NULL) {
11975 			return (B_FALSE);
11976 		}
11977 	}
11978 
11979 	/* Initiate IPPF processing for fastpath UDP */
11980 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11981 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11982 		if (*mpp == NULL) {
11983 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11984 			    "deferred/dropped during IPPF processing\n"));
11985 			return (B_FALSE);
11986 		}
11987 	}
11988 	/*
11989 	 * Remove 0-spi if it's 0, or move everything behind
11990 	 * the UDP header over it and forward to ESP via
11991 	 * ip_proto_input().
11992 	 */
11993 	if (udp->udp_nat_t_endpoint) {
11994 		if (mctl_present) {
11995 			/* mctl_present *shouldn't* happen. */
11996 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
11997 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
11998 			    &ipss->ipsec_dropper);
11999 			*first_mpp = NULL;
12000 			return (B_FALSE);
12001 		}
12002 
12003 		/* "ill" is "recv_ill" in actuality. */
12004 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12005 			return (B_FALSE);
12006 
12007 		/* Else continue like a normal UDP packet. */
12008 	}
12009 
12010 	/*
12011 	 * We make the checks as below since we are in the fast path
12012 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12013 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12014 	 */
12015 	if (connp->conn_recvif || connp->conn_recvslla ||
12016 	    connp->conn_ip_recvpktinfo) {
12017 		if (connp->conn_recvif) {
12018 			in_flags = IPF_RECVIF;
12019 		}
12020 		/*
12021 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12022 		 * so the flag passed to ip_add_info is based on IP version
12023 		 * of connp.
12024 		 */
12025 		if (connp->conn_ip_recvpktinfo) {
12026 			if (connp->conn_af_isv6) {
12027 				/*
12028 				 * V6 only needs index
12029 				 */
12030 				in_flags |= IPF_RECVIF;
12031 			} else {
12032 				/*
12033 				 * V4 needs index + matching address.
12034 				 */
12035 				in_flags |= IPF_RECVADDR;
12036 			}
12037 		}
12038 		if (connp->conn_recvslla) {
12039 			in_flags |= IPF_RECVSLLA;
12040 		}
12041 		/*
12042 		 * since in_flags are being set ill will be
12043 		 * referenced in ip_add_info, so it better not
12044 		 * be NULL.
12045 		 */
12046 		/*
12047 		 * the actual data will be contained in b_cont
12048 		 * upon successful return of the following call.
12049 		 * If the call fails then the original mblk is
12050 		 * returned.
12051 		 */
12052 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12053 		    ipst);
12054 	}
12055 
12056 	return (B_TRUE);
12057 }
12058 
12059 /*
12060  * Fragmentation reassembly.  Each ILL has a hash table for
12061  * queuing packets undergoing reassembly for all IPIFs
12062  * associated with the ILL.  The hash is based on the packet
12063  * IP ident field.  The ILL frag hash table was allocated
12064  * as a timer block at the time the ILL was created.  Whenever
12065  * there is anything on the reassembly queue, the timer will
12066  * be running.  Returns B_TRUE if successful else B_FALSE;
12067  * frees mp on failure.
12068  */
12069 static boolean_t
12070 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12071     uint32_t *cksum_val, uint16_t *cksum_flags)
12072 {
12073 	uint32_t	frag_offset_flags;
12074 	mblk_t		*mp = *mpp;
12075 	mblk_t		*t_mp;
12076 	ipaddr_t	dst;
12077 	uint8_t		proto = ipha->ipha_protocol;
12078 	uint32_t	sum_val;
12079 	uint16_t	sum_flags;
12080 	ipf_t		*ipf;
12081 	ipf_t		**ipfp;
12082 	ipfb_t		*ipfb;
12083 	uint16_t	ident;
12084 	uint32_t	offset;
12085 	ipaddr_t	src;
12086 	uint_t		hdr_length;
12087 	uint32_t	end;
12088 	mblk_t		*mp1;
12089 	mblk_t		*tail_mp;
12090 	size_t		count;
12091 	size_t		msg_len;
12092 	uint8_t		ecn_info = 0;
12093 	uint32_t	packet_size;
12094 	boolean_t	pruned = B_FALSE;
12095 	ip_stack_t *ipst = ill->ill_ipst;
12096 
12097 	if (cksum_val != NULL)
12098 		*cksum_val = 0;
12099 	if (cksum_flags != NULL)
12100 		*cksum_flags = 0;
12101 
12102 	/*
12103 	 * Drop the fragmented as early as possible, if
12104 	 * we don't have resource(s) to re-assemble.
12105 	 */
12106 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12107 		freemsg(mp);
12108 		return (B_FALSE);
12109 	}
12110 
12111 	/* Check for fragmentation offset; return if there's none */
12112 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12113 	    (IPH_MF | IPH_OFFSET)) == 0)
12114 		return (B_TRUE);
12115 
12116 	/*
12117 	 * We utilize hardware computed checksum info only for UDP since
12118 	 * IP fragmentation is a normal occurrence for the protocol.  In
12119 	 * addition, checksum offload support for IP fragments carrying
12120 	 * UDP payload is commonly implemented across network adapters.
12121 	 */
12122 	ASSERT(recv_ill != NULL);
12123 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12124 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12125 		mblk_t *mp1 = mp->b_cont;
12126 		int32_t len;
12127 
12128 		/* Record checksum information from the packet */
12129 		sum_val = (uint32_t)DB_CKSUM16(mp);
12130 		sum_flags = DB_CKSUMFLAGS(mp);
12131 
12132 		/* IP payload offset from beginning of mblk */
12133 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12134 
12135 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12136 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12137 		    offset >= DB_CKSUMSTART(mp) &&
12138 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12139 			uint32_t adj;
12140 			/*
12141 			 * Partial checksum has been calculated by hardware
12142 			 * and attached to the packet; in addition, any
12143 			 * prepended extraneous data is even byte aligned.
12144 			 * If any such data exists, we adjust the checksum;
12145 			 * this would also handle any postpended data.
12146 			 */
12147 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12148 			    mp, mp1, len, adj);
12149 
12150 			/* One's complement subtract extraneous checksum */
12151 			if (adj >= sum_val)
12152 				sum_val = ~(adj - sum_val) & 0xFFFF;
12153 			else
12154 				sum_val -= adj;
12155 		}
12156 	} else {
12157 		sum_val = 0;
12158 		sum_flags = 0;
12159 	}
12160 
12161 	/* Clear hardware checksumming flag */
12162 	DB_CKSUMFLAGS(mp) = 0;
12163 
12164 	ident = ipha->ipha_ident;
12165 	offset = (frag_offset_flags << 3) & 0xFFFF;
12166 	src = ipha->ipha_src;
12167 	dst = ipha->ipha_dst;
12168 	hdr_length = IPH_HDR_LENGTH(ipha);
12169 	end = ntohs(ipha->ipha_length) - hdr_length;
12170 
12171 	/* If end == 0 then we have a packet with no data, so just free it */
12172 	if (end == 0) {
12173 		freemsg(mp);
12174 		return (B_FALSE);
12175 	}
12176 
12177 	/* Record the ECN field info. */
12178 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12179 	if (offset != 0) {
12180 		/*
12181 		 * If this isn't the first piece, strip the header, and
12182 		 * add the offset to the end value.
12183 		 */
12184 		mp->b_rptr += hdr_length;
12185 		end += offset;
12186 	}
12187 
12188 	msg_len = MBLKSIZE(mp);
12189 	tail_mp = mp;
12190 	while (tail_mp->b_cont != NULL) {
12191 		tail_mp = tail_mp->b_cont;
12192 		msg_len += MBLKSIZE(tail_mp);
12193 	}
12194 
12195 	/* If the reassembly list for this ILL will get too big, prune it */
12196 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12197 	    ipst->ips_ip_reass_queue_bytes) {
12198 		ill_frag_prune(ill,
12199 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12200 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12201 		pruned = B_TRUE;
12202 	}
12203 
12204 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12205 	mutex_enter(&ipfb->ipfb_lock);
12206 
12207 	ipfp = &ipfb->ipfb_ipf;
12208 	/* Try to find an existing fragment queue for this packet. */
12209 	for (;;) {
12210 		ipf = ipfp[0];
12211 		if (ipf != NULL) {
12212 			/*
12213 			 * It has to match on ident and src/dst address.
12214 			 */
12215 			if (ipf->ipf_ident == ident &&
12216 			    ipf->ipf_src == src &&
12217 			    ipf->ipf_dst == dst &&
12218 			    ipf->ipf_protocol == proto) {
12219 				/*
12220 				 * If we have received too many
12221 				 * duplicate fragments for this packet
12222 				 * free it.
12223 				 */
12224 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12225 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12226 					freemsg(mp);
12227 					mutex_exit(&ipfb->ipfb_lock);
12228 					return (B_FALSE);
12229 				}
12230 				/* Found it. */
12231 				break;
12232 			}
12233 			ipfp = &ipf->ipf_hash_next;
12234 			continue;
12235 		}
12236 
12237 		/*
12238 		 * If we pruned the list, do we want to store this new
12239 		 * fragment?. We apply an optimization here based on the
12240 		 * fact that most fragments will be received in order.
12241 		 * So if the offset of this incoming fragment is zero,
12242 		 * it is the first fragment of a new packet. We will
12243 		 * keep it.  Otherwise drop the fragment, as we have
12244 		 * probably pruned the packet already (since the
12245 		 * packet cannot be found).
12246 		 */
12247 		if (pruned && offset != 0) {
12248 			mutex_exit(&ipfb->ipfb_lock);
12249 			freemsg(mp);
12250 			return (B_FALSE);
12251 		}
12252 
12253 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12254 			/*
12255 			 * Too many fragmented packets in this hash
12256 			 * bucket. Free the oldest.
12257 			 */
12258 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12259 		}
12260 
12261 		/* New guy.  Allocate a frag message. */
12262 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12263 		if (mp1 == NULL) {
12264 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12265 			freemsg(mp);
12266 reass_done:
12267 			mutex_exit(&ipfb->ipfb_lock);
12268 			return (B_FALSE);
12269 		}
12270 
12271 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12272 		mp1->b_cont = mp;
12273 
12274 		/* Initialize the fragment header. */
12275 		ipf = (ipf_t *)mp1->b_rptr;
12276 		ipf->ipf_mp = mp1;
12277 		ipf->ipf_ptphn = ipfp;
12278 		ipfp[0] = ipf;
12279 		ipf->ipf_hash_next = NULL;
12280 		ipf->ipf_ident = ident;
12281 		ipf->ipf_protocol = proto;
12282 		ipf->ipf_src = src;
12283 		ipf->ipf_dst = dst;
12284 		ipf->ipf_nf_hdr_len = 0;
12285 		/* Record reassembly start time. */
12286 		ipf->ipf_timestamp = gethrestime_sec();
12287 		/* Record ipf generation and account for frag header */
12288 		ipf->ipf_gen = ill->ill_ipf_gen++;
12289 		ipf->ipf_count = MBLKSIZE(mp1);
12290 		ipf->ipf_last_frag_seen = B_FALSE;
12291 		ipf->ipf_ecn = ecn_info;
12292 		ipf->ipf_num_dups = 0;
12293 		ipfb->ipfb_frag_pkts++;
12294 		ipf->ipf_checksum = 0;
12295 		ipf->ipf_checksum_flags = 0;
12296 
12297 		/* Store checksum value in fragment header */
12298 		if (sum_flags != 0) {
12299 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12300 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12301 			ipf->ipf_checksum = sum_val;
12302 			ipf->ipf_checksum_flags = sum_flags;
12303 		}
12304 
12305 		/*
12306 		 * We handle reassembly two ways.  In the easy case,
12307 		 * where all the fragments show up in order, we do
12308 		 * minimal bookkeeping, and just clip new pieces on
12309 		 * the end.  If we ever see a hole, then we go off
12310 		 * to ip_reassemble which has to mark the pieces and
12311 		 * keep track of the number of holes, etc.  Obviously,
12312 		 * the point of having both mechanisms is so we can
12313 		 * handle the easy case as efficiently as possible.
12314 		 */
12315 		if (offset == 0) {
12316 			/* Easy case, in-order reassembly so far. */
12317 			ipf->ipf_count += msg_len;
12318 			ipf->ipf_tail_mp = tail_mp;
12319 			/*
12320 			 * Keep track of next expected offset in
12321 			 * ipf_end.
12322 			 */
12323 			ipf->ipf_end = end;
12324 			ipf->ipf_nf_hdr_len = hdr_length;
12325 		} else {
12326 			/* Hard case, hole at the beginning. */
12327 			ipf->ipf_tail_mp = NULL;
12328 			/*
12329 			 * ipf_end == 0 means that we have given up
12330 			 * on easy reassembly.
12331 			 */
12332 			ipf->ipf_end = 0;
12333 
12334 			/* Forget checksum offload from now on */
12335 			ipf->ipf_checksum_flags = 0;
12336 
12337 			/*
12338 			 * ipf_hole_cnt is set by ip_reassemble.
12339 			 * ipf_count is updated by ip_reassemble.
12340 			 * No need to check for return value here
12341 			 * as we don't expect reassembly to complete
12342 			 * or fail for the first fragment itself.
12343 			 */
12344 			(void) ip_reassemble(mp, ipf,
12345 			    (frag_offset_flags & IPH_OFFSET) << 3,
12346 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12347 		}
12348 		/* Update per ipfb and ill byte counts */
12349 		ipfb->ipfb_count += ipf->ipf_count;
12350 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12351 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12352 		/* If the frag timer wasn't already going, start it. */
12353 		mutex_enter(&ill->ill_lock);
12354 		ill_frag_timer_start(ill);
12355 		mutex_exit(&ill->ill_lock);
12356 		goto reass_done;
12357 	}
12358 
12359 	/*
12360 	 * If the packet's flag has changed (it could be coming up
12361 	 * from an interface different than the previous, therefore
12362 	 * possibly different checksum capability), then forget about
12363 	 * any stored checksum states.  Otherwise add the value to
12364 	 * the existing one stored in the fragment header.
12365 	 */
12366 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12367 		sum_val += ipf->ipf_checksum;
12368 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12369 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12370 		ipf->ipf_checksum = sum_val;
12371 	} else if (ipf->ipf_checksum_flags != 0) {
12372 		/* Forget checksum offload from now on */
12373 		ipf->ipf_checksum_flags = 0;
12374 	}
12375 
12376 	/*
12377 	 * We have a new piece of a datagram which is already being
12378 	 * reassembled.  Update the ECN info if all IP fragments
12379 	 * are ECN capable.  If there is one which is not, clear
12380 	 * all the info.  If there is at least one which has CE
12381 	 * code point, IP needs to report that up to transport.
12382 	 */
12383 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12384 		if (ecn_info == IPH_ECN_CE)
12385 			ipf->ipf_ecn = IPH_ECN_CE;
12386 	} else {
12387 		ipf->ipf_ecn = IPH_ECN_NECT;
12388 	}
12389 	if (offset && ipf->ipf_end == offset) {
12390 		/* The new fragment fits at the end */
12391 		ipf->ipf_tail_mp->b_cont = mp;
12392 		/* Update the byte count */
12393 		ipf->ipf_count += msg_len;
12394 		/* Update per ipfb and ill byte counts */
12395 		ipfb->ipfb_count += msg_len;
12396 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12397 		atomic_add_32(&ill->ill_frag_count, msg_len);
12398 		if (frag_offset_flags & IPH_MF) {
12399 			/* More to come. */
12400 			ipf->ipf_end = end;
12401 			ipf->ipf_tail_mp = tail_mp;
12402 			goto reass_done;
12403 		}
12404 	} else {
12405 		/* Go do the hard cases. */
12406 		int ret;
12407 
12408 		if (offset == 0)
12409 			ipf->ipf_nf_hdr_len = hdr_length;
12410 
12411 		/* Save current byte count */
12412 		count = ipf->ipf_count;
12413 		ret = ip_reassemble(mp, ipf,
12414 		    (frag_offset_flags & IPH_OFFSET) << 3,
12415 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12416 		/* Count of bytes added and subtracted (freeb()ed) */
12417 		count = ipf->ipf_count - count;
12418 		if (count) {
12419 			/* Update per ipfb and ill byte counts */
12420 			ipfb->ipfb_count += count;
12421 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12422 			atomic_add_32(&ill->ill_frag_count, count);
12423 		}
12424 		if (ret == IP_REASS_PARTIAL) {
12425 			goto reass_done;
12426 		} else if (ret == IP_REASS_FAILED) {
12427 			/* Reassembly failed. Free up all resources */
12428 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12429 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12430 				IP_REASS_SET_START(t_mp, 0);
12431 				IP_REASS_SET_END(t_mp, 0);
12432 			}
12433 			freemsg(mp);
12434 			goto reass_done;
12435 		}
12436 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12437 	}
12438 	/*
12439 	 * We have completed reassembly.  Unhook the frag header from
12440 	 * the reassembly list.
12441 	 *
12442 	 * Before we free the frag header, record the ECN info
12443 	 * to report back to the transport.
12444 	 */
12445 	ecn_info = ipf->ipf_ecn;
12446 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12447 	ipfp = ipf->ipf_ptphn;
12448 
12449 	/* We need to supply these to caller */
12450 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12451 		sum_val = ipf->ipf_checksum;
12452 	else
12453 		sum_val = 0;
12454 
12455 	mp1 = ipf->ipf_mp;
12456 	count = ipf->ipf_count;
12457 	ipf = ipf->ipf_hash_next;
12458 	if (ipf != NULL)
12459 		ipf->ipf_ptphn = ipfp;
12460 	ipfp[0] = ipf;
12461 	atomic_add_32(&ill->ill_frag_count, -count);
12462 	ASSERT(ipfb->ipfb_count >= count);
12463 	ipfb->ipfb_count -= count;
12464 	ipfb->ipfb_frag_pkts--;
12465 	mutex_exit(&ipfb->ipfb_lock);
12466 	/* Ditch the frag header. */
12467 	mp = mp1->b_cont;
12468 
12469 	freeb(mp1);
12470 
12471 	/* Restore original IP length in header. */
12472 	packet_size = (uint32_t)msgdsize(mp);
12473 	if (packet_size > IP_MAXPACKET) {
12474 		freemsg(mp);
12475 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12476 		return (B_FALSE);
12477 	}
12478 
12479 	if (DB_REF(mp) > 1) {
12480 		mblk_t *mp2 = copymsg(mp);
12481 
12482 		freemsg(mp);
12483 		if (mp2 == NULL) {
12484 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12485 			return (B_FALSE);
12486 		}
12487 		mp = mp2;
12488 	}
12489 	ipha = (ipha_t *)mp->b_rptr;
12490 
12491 	ipha->ipha_length = htons((uint16_t)packet_size);
12492 	/* We're now complete, zip the frag state */
12493 	ipha->ipha_fragment_offset_and_flags = 0;
12494 	/* Record the ECN info. */
12495 	ipha->ipha_type_of_service &= 0xFC;
12496 	ipha->ipha_type_of_service |= ecn_info;
12497 	*mpp = mp;
12498 
12499 	/* Reassembly is successful; return checksum information if needed */
12500 	if (cksum_val != NULL)
12501 		*cksum_val = sum_val;
12502 	if (cksum_flags != NULL)
12503 		*cksum_flags = sum_flags;
12504 
12505 	return (B_TRUE);
12506 }
12507 
12508 /*
12509  * Perform ip header check sum update local options.
12510  * return B_TRUE if all is well, else return B_FALSE and release
12511  * the mp. caller is responsible for decrementing ire ref cnt.
12512  */
12513 static boolean_t
12514 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12515     ip_stack_t *ipst)
12516 {
12517 	mblk_t		*first_mp;
12518 	boolean_t	mctl_present;
12519 	uint16_t	sum;
12520 
12521 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12522 	/*
12523 	 * Don't do the checksum if it has gone through AH/ESP
12524 	 * processing.
12525 	 */
12526 	if (!mctl_present) {
12527 		sum = ip_csum_hdr(ipha);
12528 		if (sum != 0) {
12529 			if (ill != NULL) {
12530 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12531 			} else {
12532 				BUMP_MIB(&ipst->ips_ip_mib,
12533 				    ipIfStatsInCksumErrs);
12534 			}
12535 			freemsg(first_mp);
12536 			return (B_FALSE);
12537 		}
12538 	}
12539 
12540 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12541 		if (mctl_present)
12542 			freeb(first_mp);
12543 		return (B_FALSE);
12544 	}
12545 
12546 	return (B_TRUE);
12547 }
12548 
12549 /*
12550  * All udp packet are delivered to the local host via this routine.
12551  */
12552 void
12553 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12554     ill_t *recv_ill)
12555 {
12556 	uint32_t	sum;
12557 	uint32_t	u1;
12558 	boolean_t	mctl_present;
12559 	conn_t		*connp;
12560 	mblk_t		*first_mp;
12561 	uint16_t	*up;
12562 	ill_t		*ill = (ill_t *)q->q_ptr;
12563 	uint16_t	reass_hck_flags = 0;
12564 	ip_stack_t	*ipst;
12565 
12566 	ASSERT(recv_ill != NULL);
12567 	ipst = recv_ill->ill_ipst;
12568 
12569 #define	rptr    ((uchar_t *)ipha)
12570 
12571 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12572 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12573 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12574 	ASSERT(ill != NULL);
12575 
12576 	/*
12577 	 * FAST PATH for udp packets
12578 	 */
12579 
12580 	/* u1 is # words of IP options */
12581 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12582 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12583 
12584 	/* IP options present */
12585 	if (u1 != 0)
12586 		goto ipoptions;
12587 
12588 	/* Check the IP header checksum.  */
12589 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12590 		/* Clear the IP header h/w cksum flag */
12591 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12592 	} else if (!mctl_present) {
12593 		/*
12594 		 * Don't verify header checksum if this packet is coming
12595 		 * back from AH/ESP as we already did it.
12596 		 */
12597 #define	uph	((uint16_t *)ipha)
12598 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12599 		    uph[6] + uph[7] + uph[8] + uph[9];
12600 #undef	uph
12601 		/* finish doing IP checksum */
12602 		sum = (sum & 0xFFFF) + (sum >> 16);
12603 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12604 		if (sum != 0 && sum != 0xFFFF) {
12605 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12606 			freemsg(first_mp);
12607 			return;
12608 		}
12609 	}
12610 
12611 	/*
12612 	 * Count for SNMP of inbound packets for ire.
12613 	 * if mctl is present this might be a secure packet and
12614 	 * has already been counted for in ip_proto_input().
12615 	 */
12616 	if (!mctl_present) {
12617 		UPDATE_IB_PKT_COUNT(ire);
12618 		ire->ire_last_used_time = lbolt;
12619 	}
12620 
12621 	/* packet part of fragmented IP packet? */
12622 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12623 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12624 		goto fragmented;
12625 	}
12626 
12627 	/* u1 = IP header length (20 bytes) */
12628 	u1 = IP_SIMPLE_HDR_LENGTH;
12629 
12630 	/* packet does not contain complete IP & UDP headers */
12631 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12632 		goto udppullup;
12633 
12634 	/* up points to UDP header */
12635 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12636 #define	iphs    ((uint16_t *)ipha)
12637 
12638 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12639 	if (up[3] != 0) {
12640 		mblk_t *mp1 = mp->b_cont;
12641 		boolean_t cksum_err;
12642 		uint16_t hck_flags = 0;
12643 
12644 		/* Pseudo-header checksum */
12645 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12646 		    iphs[9] + up[2];
12647 
12648 		/*
12649 		 * Revert to software checksum calculation if the interface
12650 		 * isn't capable of checksum offload or if IPsec is present.
12651 		 */
12652 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12653 			hck_flags = DB_CKSUMFLAGS(mp);
12654 
12655 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12656 			IP_STAT(ipst, ip_in_sw_cksum);
12657 
12658 		IP_CKSUM_RECV(hck_flags, u1,
12659 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12660 		    (int32_t)((uchar_t *)up - rptr),
12661 		    mp, mp1, cksum_err);
12662 
12663 		if (cksum_err) {
12664 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12665 			if (hck_flags & HCK_FULLCKSUM)
12666 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12667 			else if (hck_flags & HCK_PARTIALCKSUM)
12668 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12669 			else
12670 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12671 
12672 			freemsg(first_mp);
12673 			return;
12674 		}
12675 	}
12676 
12677 	/* Non-fragmented broadcast or multicast packet? */
12678 	if (ire->ire_type == IRE_BROADCAST)
12679 		goto udpslowpath;
12680 
12681 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12682 	    ire->ire_zoneid, ipst)) != NULL) {
12683 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12684 		IP_STAT(ipst, ip_udp_fast_path);
12685 
12686 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12687 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12688 			freemsg(mp);
12689 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12690 		} else {
12691 			if (!mctl_present) {
12692 				BUMP_MIB(ill->ill_ip_mib,
12693 				    ipIfStatsHCInDelivers);
12694 			}
12695 			/*
12696 			 * mp and first_mp can change.
12697 			 */
12698 			if (ip_udp_check(q, connp, recv_ill,
12699 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12700 				/* Send it upstream */
12701 				(connp->conn_recv)(connp, mp, NULL);
12702 			}
12703 		}
12704 		/*
12705 		 * freeb() cannot deal with null mblk being passed
12706 		 * in and first_mp can be set to null in the call
12707 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12708 		 */
12709 		if (mctl_present && first_mp != NULL) {
12710 			freeb(first_mp);
12711 		}
12712 		CONN_DEC_REF(connp);
12713 		return;
12714 	}
12715 
12716 	/*
12717 	 * if we got here we know the packet is not fragmented and
12718 	 * has no options. The classifier could not find a conn_t and
12719 	 * most likely its an icmp packet so send it through slow path.
12720 	 */
12721 
12722 	goto udpslowpath;
12723 
12724 ipoptions:
12725 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12726 		goto slow_done;
12727 	}
12728 
12729 	UPDATE_IB_PKT_COUNT(ire);
12730 	ire->ire_last_used_time = lbolt;
12731 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12732 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12733 fragmented:
12734 		/*
12735 		 * "sum" and "reass_hck_flags" are non-zero if the
12736 		 * reassembled packet has a valid hardware computed
12737 		 * checksum information associated with it.
12738 		 */
12739 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12740 		    &reass_hck_flags)) {
12741 			goto slow_done;
12742 		}
12743 
12744 		/*
12745 		 * Make sure that first_mp points back to mp as
12746 		 * the mp we came in with could have changed in
12747 		 * ip_rput_fragment().
12748 		 */
12749 		ASSERT(!mctl_present);
12750 		ipha = (ipha_t *)mp->b_rptr;
12751 		first_mp = mp;
12752 	}
12753 
12754 	/* Now we have a complete datagram, destined for this machine. */
12755 	u1 = IPH_HDR_LENGTH(ipha);
12756 	/* Pull up the UDP header, if necessary. */
12757 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12758 udppullup:
12759 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12760 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12761 			freemsg(first_mp);
12762 			goto slow_done;
12763 		}
12764 		ipha = (ipha_t *)mp->b_rptr;
12765 	}
12766 
12767 	/*
12768 	 * Validate the checksum for the reassembled packet; for the
12769 	 * pullup case we calculate the payload checksum in software.
12770 	 */
12771 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12772 	if (up[3] != 0) {
12773 		boolean_t cksum_err;
12774 
12775 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12776 			IP_STAT(ipst, ip_in_sw_cksum);
12777 
12778 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12779 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12780 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12781 		    iphs[9] + up[2], sum, cksum_err);
12782 
12783 		if (cksum_err) {
12784 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12785 
12786 			if (reass_hck_flags & HCK_FULLCKSUM)
12787 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12788 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12789 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12790 			else
12791 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12792 
12793 			freemsg(first_mp);
12794 			goto slow_done;
12795 		}
12796 	}
12797 udpslowpath:
12798 
12799 	/* Clear hardware checksum flag to be safe */
12800 	DB_CKSUMFLAGS(mp) = 0;
12801 
12802 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12803 	    (ire->ire_type == IRE_BROADCAST),
12804 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12805 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12806 
12807 slow_done:
12808 	IP_STAT(ipst, ip_udp_slow_path);
12809 	return;
12810 
12811 #undef  iphs
12812 #undef  rptr
12813 }
12814 
12815 static boolean_t
12816 ip_iptun_input(mblk_t *ipsec_mp, mblk_t *data_mp, ipha_t *ipha, ill_t *ill,
12817     ire_t *ire, ip_stack_t *ipst)
12818 {
12819 	conn_t	*connp;
12820 
12821 	ASSERT(ipsec_mp == NULL || ipsec_mp->b_cont == data_mp);
12822 
12823 	if ((connp = ipcl_classify_v4(data_mp, ipha->ipha_protocol,
12824 	    IP_SIMPLE_HDR_LENGTH, ire->ire_zoneid, ipst)) != NULL) {
12825 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12826 		connp->conn_recv(connp, ipsec_mp != NULL ? ipsec_mp : data_mp,
12827 		    NULL);
12828 		CONN_DEC_REF(connp);
12829 		return (B_TRUE);
12830 	}
12831 	return (B_FALSE);
12832 }
12833 
12834 /* ARGSUSED */
12835 static mblk_t *
12836 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12837     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12838     ill_rx_ring_t *ill_ring)
12839 {
12840 	conn_t		*connp;
12841 	uint32_t	sum;
12842 	uint32_t	u1;
12843 	uint16_t	*up;
12844 	int		offset;
12845 	ssize_t		len;
12846 	mblk_t		*mp1;
12847 	boolean_t	syn_present = B_FALSE;
12848 	tcph_t		*tcph;
12849 	uint_t		tcph_flags;
12850 	uint_t		ip_hdr_len;
12851 	ill_t		*ill = (ill_t *)q->q_ptr;
12852 	zoneid_t	zoneid = ire->ire_zoneid;
12853 	boolean_t	cksum_err;
12854 	uint16_t	hck_flags = 0;
12855 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12856 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12857 
12858 #define	rptr	((uchar_t *)ipha)
12859 
12860 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12861 	ASSERT(ill != NULL);
12862 
12863 	/*
12864 	 * FAST PATH for tcp packets
12865 	 */
12866 
12867 	/* u1 is # words of IP options */
12868 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12869 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12870 
12871 	/* IP options present */
12872 	if (u1) {
12873 		goto ipoptions;
12874 	} else if (!mctl_present) {
12875 		/* Check the IP header checksum.  */
12876 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12877 			/* Clear the IP header h/w cksum flag */
12878 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12879 		} else if (!mctl_present) {
12880 			/*
12881 			 * Don't verify header checksum if this packet
12882 			 * is coming back from AH/ESP as we already did it.
12883 			 */
12884 #define	uph	((uint16_t *)ipha)
12885 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12886 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12887 #undef	uph
12888 			/* finish doing IP checksum */
12889 			sum = (sum & 0xFFFF) + (sum >> 16);
12890 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12891 			if (sum != 0 && sum != 0xFFFF) {
12892 				BUMP_MIB(ill->ill_ip_mib,
12893 				    ipIfStatsInCksumErrs);
12894 				goto error;
12895 			}
12896 		}
12897 	}
12898 
12899 	if (!mctl_present) {
12900 		UPDATE_IB_PKT_COUNT(ire);
12901 		ire->ire_last_used_time = lbolt;
12902 	}
12903 
12904 	/* packet part of fragmented IP packet? */
12905 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12906 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12907 		goto fragmented;
12908 	}
12909 
12910 	/* u1 = IP header length (20 bytes) */
12911 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12912 
12913 	/* does packet contain IP+TCP headers? */
12914 	len = mp->b_wptr - rptr;
12915 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12916 		IP_STAT(ipst, ip_tcppullup);
12917 		goto tcppullup;
12918 	}
12919 
12920 	/* TCP options present? */
12921 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12922 
12923 	/*
12924 	 * If options need to be pulled up, then goto tcpoptions.
12925 	 * otherwise we are still in the fast path
12926 	 */
12927 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12928 		IP_STAT(ipst, ip_tcpoptions);
12929 		goto tcpoptions;
12930 	}
12931 
12932 	/* multiple mblks of tcp data? */
12933 	if ((mp1 = mp->b_cont) != NULL) {
12934 		IP_STAT(ipst, ip_multipkttcp);
12935 		len += msgdsize(mp1);
12936 	}
12937 
12938 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12939 
12940 	/* part of pseudo checksum */
12941 
12942 	/* TCP datagram length */
12943 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12944 
12945 #define	iphs    ((uint16_t *)ipha)
12946 
12947 #ifdef	_BIG_ENDIAN
12948 	u1 += IPPROTO_TCP;
12949 #else
12950 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12951 #endif
12952 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12953 
12954 	/*
12955 	 * Revert to software checksum calculation if the interface
12956 	 * isn't capable of checksum offload or if IPsec is present.
12957 	 */
12958 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12959 		hck_flags = DB_CKSUMFLAGS(mp);
12960 
12961 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12962 		IP_STAT(ipst, ip_in_sw_cksum);
12963 
12964 	IP_CKSUM_RECV(hck_flags, u1,
12965 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12966 	    (int32_t)((uchar_t *)up - rptr),
12967 	    mp, mp1, cksum_err);
12968 
12969 	if (cksum_err) {
12970 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12971 
12972 		if (hck_flags & HCK_FULLCKSUM)
12973 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12974 		else if (hck_flags & HCK_PARTIALCKSUM)
12975 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12976 		else
12977 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12978 
12979 		goto error;
12980 	}
12981 
12982 try_again:
12983 
12984 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12985 	    zoneid, ipst)) == NULL) {
12986 		/* Send the TH_RST */
12987 		goto no_conn;
12988 	}
12989 
12990 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12991 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
12992 
12993 	/*
12994 	 * TCP FAST PATH for AF_INET socket.
12995 	 *
12996 	 * TCP fast path to avoid extra work. An AF_INET socket type
12997 	 * does not have facility to receive extra information via
12998 	 * ip_process or ip_add_info. Also, when the connection was
12999 	 * established, we made a check if this connection is impacted
13000 	 * by any global IPsec policy or per connection policy (a
13001 	 * policy that comes in effect later will not apply to this
13002 	 * connection). Since all this can be determined at the
13003 	 * connection establishment time, a quick check of flags
13004 	 * can avoid extra work.
13005 	 */
13006 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13007 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13008 		ASSERT(first_mp == mp);
13009 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13010 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13011 			SET_SQUEUE(mp, tcp_rput_data, connp);
13012 			return (mp);
13013 		}
13014 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13015 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13016 		SET_SQUEUE(mp, tcp_input, connp);
13017 		return (mp);
13018 	}
13019 
13020 	if (tcph_flags == TH_SYN) {
13021 		if (IPCL_IS_TCP(connp)) {
13022 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13023 			DB_CKSUMSTART(mp) =
13024 			    (intptr_t)ip_squeue_get(ill_ring);
13025 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13026 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13027 				BUMP_MIB(ill->ill_ip_mib,
13028 				    ipIfStatsHCInDelivers);
13029 				SET_SQUEUE(mp, connp->conn_recv, connp);
13030 				return (mp);
13031 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13032 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13033 				BUMP_MIB(ill->ill_ip_mib,
13034 				    ipIfStatsHCInDelivers);
13035 				ip_squeue_enter_unbound++;
13036 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13037 				    connp);
13038 				return (mp);
13039 			}
13040 			syn_present = B_TRUE;
13041 		}
13042 	}
13043 
13044 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13045 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13046 
13047 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13048 		/* No need to send this packet to TCP */
13049 		if ((flags & TH_RST) || (flags & TH_URG)) {
13050 			CONN_DEC_REF(connp);
13051 			freemsg(first_mp);
13052 			return (NULL);
13053 		}
13054 		if (flags & TH_ACK) {
13055 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13056 			    ipst->ips_netstack->netstack_tcp, connp);
13057 			CONN_DEC_REF(connp);
13058 			return (NULL);
13059 		}
13060 
13061 		CONN_DEC_REF(connp);
13062 		freemsg(first_mp);
13063 		return (NULL);
13064 	}
13065 
13066 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13067 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13068 		    ipha, NULL, mctl_present);
13069 		if (first_mp == NULL) {
13070 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13071 			CONN_DEC_REF(connp);
13072 			return (NULL);
13073 		}
13074 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13075 			ASSERT(syn_present);
13076 			if (mctl_present) {
13077 				ASSERT(first_mp != mp);
13078 				first_mp->b_datap->db_struioflag |=
13079 				    STRUIO_POLICY;
13080 			} else {
13081 				ASSERT(first_mp == mp);
13082 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13083 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13084 			}
13085 		} else {
13086 			/*
13087 			 * Discard first_mp early since we're dealing with a
13088 			 * fully-connected conn_t and tcp doesn't do policy in
13089 			 * this case.
13090 			 */
13091 			if (mctl_present) {
13092 				freeb(first_mp);
13093 				mctl_present = B_FALSE;
13094 			}
13095 			first_mp = mp;
13096 		}
13097 	}
13098 
13099 	/* Initiate IPPF processing for fastpath */
13100 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13101 		uint32_t	ill_index;
13102 
13103 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13104 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13105 		if (mp == NULL) {
13106 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13107 			    "deferred/dropped during IPPF processing\n"));
13108 			CONN_DEC_REF(connp);
13109 			if (mctl_present)
13110 				freeb(first_mp);
13111 			return (NULL);
13112 		} else if (mctl_present) {
13113 			/*
13114 			 * ip_process might return a new mp.
13115 			 */
13116 			ASSERT(first_mp != mp);
13117 			first_mp->b_cont = mp;
13118 		} else {
13119 			first_mp = mp;
13120 		}
13121 
13122 	}
13123 
13124 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13125 		/*
13126 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13127 		 * make sure IPF_RECVIF is passed to ip_add_info.
13128 		 */
13129 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13130 		    IPCL_ZONEID(connp), ipst);
13131 		if (mp == NULL) {
13132 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13133 			CONN_DEC_REF(connp);
13134 			if (mctl_present)
13135 				freeb(first_mp);
13136 			return (NULL);
13137 		} else if (mctl_present) {
13138 			/*
13139 			 * ip_add_info might return a new mp.
13140 			 */
13141 			ASSERT(first_mp != mp);
13142 			first_mp->b_cont = mp;
13143 		} else {
13144 			first_mp = mp;
13145 		}
13146 	}
13147 
13148 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13149 	if (IPCL_IS_TCP(connp)) {
13150 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13151 		return (first_mp);
13152 	} else {
13153 		/* SOCK_RAW, IPPROTO_TCP case */
13154 		(connp->conn_recv)(connp, first_mp, NULL);
13155 		CONN_DEC_REF(connp);
13156 		return (NULL);
13157 	}
13158 
13159 no_conn:
13160 	/* Initiate IPPf processing, if needed. */
13161 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13162 		uint32_t ill_index;
13163 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13164 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13165 		if (first_mp == NULL) {
13166 			return (NULL);
13167 		}
13168 	}
13169 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13170 
13171 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13172 	    ipst->ips_netstack->netstack_tcp, NULL);
13173 	return (NULL);
13174 ipoptions:
13175 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13176 		goto slow_done;
13177 	}
13178 
13179 	UPDATE_IB_PKT_COUNT(ire);
13180 	ire->ire_last_used_time = lbolt;
13181 
13182 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13183 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13184 fragmented:
13185 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13186 			if (mctl_present)
13187 				freeb(first_mp);
13188 			goto slow_done;
13189 		}
13190 		/*
13191 		 * Make sure that first_mp points back to mp as
13192 		 * the mp we came in with could have changed in
13193 		 * ip_rput_fragment().
13194 		 */
13195 		ASSERT(!mctl_present);
13196 		ipha = (ipha_t *)mp->b_rptr;
13197 		first_mp = mp;
13198 	}
13199 
13200 	/* Now we have a complete datagram, destined for this machine. */
13201 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13202 
13203 	len = mp->b_wptr - mp->b_rptr;
13204 	/* Pull up a minimal TCP header, if necessary. */
13205 	if (len < (u1 + 20)) {
13206 tcppullup:
13207 		if (!pullupmsg(mp, u1 + 20)) {
13208 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13209 			goto error;
13210 		}
13211 		ipha = (ipha_t *)mp->b_rptr;
13212 		len = mp->b_wptr - mp->b_rptr;
13213 	}
13214 
13215 	/*
13216 	 * Extract the offset field from the TCP header.  As usual, we
13217 	 * try to help the compiler more than the reader.
13218 	 */
13219 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13220 	if (offset != 5) {
13221 tcpoptions:
13222 		if (offset < 5) {
13223 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13224 			goto error;
13225 		}
13226 		/*
13227 		 * There must be TCP options.
13228 		 * Make sure we can grab them.
13229 		 */
13230 		offset <<= 2;
13231 		offset += u1;
13232 		if (len < offset) {
13233 			if (!pullupmsg(mp, offset)) {
13234 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13235 				goto error;
13236 			}
13237 			ipha = (ipha_t *)mp->b_rptr;
13238 			len = mp->b_wptr - rptr;
13239 		}
13240 	}
13241 
13242 	/* Get the total packet length in len, including headers. */
13243 	if (mp->b_cont)
13244 		len = msgdsize(mp);
13245 
13246 	/*
13247 	 * Check the TCP checksum by pulling together the pseudo-
13248 	 * header checksum, and passing it to ip_csum to be added in
13249 	 * with the TCP datagram.
13250 	 *
13251 	 * Since we are not using the hwcksum if available we must
13252 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13253 	 * If either of these fails along the way the mblk is freed.
13254 	 * If this logic ever changes and mblk is reused to say send
13255 	 * ICMP's back, then this flag may need to be cleared in
13256 	 * other places as well.
13257 	 */
13258 	DB_CKSUMFLAGS(mp) = 0;
13259 
13260 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13261 
13262 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13263 #ifdef	_BIG_ENDIAN
13264 	u1 += IPPROTO_TCP;
13265 #else
13266 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13267 #endif
13268 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13269 	/*
13270 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13271 	 */
13272 	IP_STAT(ipst, ip_in_sw_cksum);
13273 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13274 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13275 		goto error;
13276 	}
13277 
13278 	IP_STAT(ipst, ip_tcp_slow_path);
13279 	goto try_again;
13280 #undef  iphs
13281 #undef  rptr
13282 
13283 error:
13284 	freemsg(first_mp);
13285 slow_done:
13286 	return (NULL);
13287 }
13288 
13289 /* ARGSUSED */
13290 static void
13291 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13292     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13293 {
13294 	conn_t		*connp;
13295 	uint32_t	sum;
13296 	uint32_t	u1;
13297 	ssize_t		len;
13298 	sctp_hdr_t	*sctph;
13299 	zoneid_t	zoneid = ire->ire_zoneid;
13300 	uint32_t	pktsum;
13301 	uint32_t	calcsum;
13302 	uint32_t	ports;
13303 	in6_addr_t	map_src, map_dst;
13304 	ill_t		*ill = (ill_t *)q->q_ptr;
13305 	ip_stack_t	*ipst;
13306 	sctp_stack_t	*sctps;
13307 	boolean_t	sctp_csum_err = B_FALSE;
13308 
13309 	ASSERT(recv_ill != NULL);
13310 	ipst = recv_ill->ill_ipst;
13311 	sctps = ipst->ips_netstack->netstack_sctp;
13312 
13313 #define	rptr	((uchar_t *)ipha)
13314 
13315 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13316 	ASSERT(ill != NULL);
13317 
13318 	/* u1 is # words of IP options */
13319 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13320 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13321 
13322 	/* IP options present */
13323 	if (u1 > 0) {
13324 		goto ipoptions;
13325 	} else {
13326 		/* Check the IP header checksum.  */
13327 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13328 		    !mctl_present) {
13329 #define	uph	((uint16_t *)ipha)
13330 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13331 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13332 #undef	uph
13333 			/* finish doing IP checksum */
13334 			sum = (sum & 0xFFFF) + (sum >> 16);
13335 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13336 			/*
13337 			 * Don't verify header checksum if this packet
13338 			 * is coming back from AH/ESP as we already did it.
13339 			 */
13340 			if (sum != 0 && sum != 0xFFFF) {
13341 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13342 				goto error;
13343 			}
13344 		}
13345 		/*
13346 		 * Since there is no SCTP h/w cksum support yet, just
13347 		 * clear the flag.
13348 		 */
13349 		DB_CKSUMFLAGS(mp) = 0;
13350 	}
13351 
13352 	/*
13353 	 * Don't verify header checksum if this packet is coming
13354 	 * back from AH/ESP as we already did it.
13355 	 */
13356 	if (!mctl_present) {
13357 		UPDATE_IB_PKT_COUNT(ire);
13358 		ire->ire_last_used_time = lbolt;
13359 	}
13360 
13361 	/* packet part of fragmented IP packet? */
13362 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13363 	if (u1 & (IPH_MF | IPH_OFFSET))
13364 		goto fragmented;
13365 
13366 	/* u1 = IP header length (20 bytes) */
13367 	u1 = IP_SIMPLE_HDR_LENGTH;
13368 
13369 find_sctp_client:
13370 	/* Pullup if we don't have the sctp common header. */
13371 	len = MBLKL(mp);
13372 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13373 		if (mp->b_cont == NULL ||
13374 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13375 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13376 			goto error;
13377 		}
13378 		ipha = (ipha_t *)mp->b_rptr;
13379 		len = MBLKL(mp);
13380 	}
13381 
13382 	sctph = (sctp_hdr_t *)(rptr + u1);
13383 #ifdef	DEBUG
13384 	if (!skip_sctp_cksum) {
13385 #endif
13386 		pktsum = sctph->sh_chksum;
13387 		sctph->sh_chksum = 0;
13388 		calcsum = sctp_cksum(mp, u1);
13389 		sctph->sh_chksum = pktsum;
13390 		if (calcsum != pktsum)
13391 			sctp_csum_err = B_TRUE;
13392 #ifdef	DEBUG	/* skip_sctp_cksum */
13393 	}
13394 #endif
13395 	/* get the ports */
13396 	ports = *(uint32_t *)&sctph->sh_sport;
13397 
13398 	IRE_REFRELE(ire);
13399 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13400 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13401 	if (sctp_csum_err) {
13402 		/*
13403 		 * No potential sctp checksum errors go to the Sun
13404 		 * sctp stack however they might be Adler-32 summed
13405 		 * packets a userland stack bound to a raw IP socket
13406 		 * could reasonably use. Note though that Adler-32 is
13407 		 * a long deprecated algorithm and customer sctp
13408 		 * networks should eventually migrate to CRC-32 at
13409 		 * which time this facility should be removed.
13410 		 */
13411 		flags |= IP_FF_SCTP_CSUM_ERR;
13412 		goto no_conn;
13413 	}
13414 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13415 	    sctps)) == NULL) {
13416 		/* Check for raw socket or OOTB handling */
13417 		goto no_conn;
13418 	}
13419 
13420 	/* Found a client; up it goes */
13421 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13422 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13423 	return;
13424 
13425 no_conn:
13426 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13427 	    ports, mctl_present, flags, B_TRUE, zoneid);
13428 	return;
13429 
13430 ipoptions:
13431 	DB_CKSUMFLAGS(mp) = 0;
13432 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13433 		goto slow_done;
13434 
13435 	UPDATE_IB_PKT_COUNT(ire);
13436 	ire->ire_last_used_time = lbolt;
13437 
13438 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13439 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13440 fragmented:
13441 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13442 			goto slow_done;
13443 		/*
13444 		 * Make sure that first_mp points back to mp as
13445 		 * the mp we came in with could have changed in
13446 		 * ip_rput_fragment().
13447 		 */
13448 		ASSERT(!mctl_present);
13449 		ipha = (ipha_t *)mp->b_rptr;
13450 		first_mp = mp;
13451 	}
13452 
13453 	/* Now we have a complete datagram, destined for this machine. */
13454 	u1 = IPH_HDR_LENGTH(ipha);
13455 	goto find_sctp_client;
13456 #undef  iphs
13457 #undef  rptr
13458 
13459 error:
13460 	freemsg(first_mp);
13461 slow_done:
13462 	IRE_REFRELE(ire);
13463 }
13464 
13465 #define	VER_BITS	0xF0
13466 #define	VERSION_6	0x60
13467 
13468 static boolean_t
13469 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13470     ipaddr_t *dstp, ip_stack_t *ipst)
13471 {
13472 	uint_t	opt_len;
13473 	ipha_t *ipha;
13474 	ssize_t len;
13475 	uint_t	pkt_len;
13476 
13477 	ASSERT(ill != NULL);
13478 	IP_STAT(ipst, ip_ipoptions);
13479 	ipha = *iphapp;
13480 
13481 #define	rptr    ((uchar_t *)ipha)
13482 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13483 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13484 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13485 		freemsg(mp);
13486 		return (B_FALSE);
13487 	}
13488 
13489 	/* multiple mblk or too short */
13490 	pkt_len = ntohs(ipha->ipha_length);
13491 
13492 	/* Get the number of words of IP options in the IP header. */
13493 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13494 	if (opt_len) {
13495 		/* IP Options present!  Validate and process. */
13496 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13497 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13498 			goto done;
13499 		}
13500 		/*
13501 		 * Recompute complete header length and make sure we
13502 		 * have access to all of it.
13503 		 */
13504 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13505 		if (len > (mp->b_wptr - rptr)) {
13506 			if (len > pkt_len) {
13507 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13508 				goto done;
13509 			}
13510 			if (!pullupmsg(mp, len)) {
13511 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13512 				goto done;
13513 			}
13514 			ipha = (ipha_t *)mp->b_rptr;
13515 		}
13516 		/*
13517 		 * Go off to ip_rput_options which returns the next hop
13518 		 * destination address, which may have been affected
13519 		 * by source routing.
13520 		 */
13521 		IP_STAT(ipst, ip_opt);
13522 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13523 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13524 			return (B_FALSE);
13525 		}
13526 	}
13527 	*iphapp = ipha;
13528 	return (B_TRUE);
13529 done:
13530 	/* clear b_prev - used by ip_mroute_decap */
13531 	mp->b_prev = NULL;
13532 	freemsg(mp);
13533 	return (B_FALSE);
13534 #undef  rptr
13535 }
13536 
13537 /*
13538  * Deal with the fact that there is no ire for the destination.
13539  */
13540 static ire_t *
13541 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13542 {
13543 	ipha_t	*ipha;
13544 	ill_t	*ill;
13545 	ire_t	*ire;
13546 	ip_stack_t *ipst;
13547 	enum	ire_forward_action ret_action;
13548 
13549 	ipha = (ipha_t *)mp->b_rptr;
13550 	ill = (ill_t *)q->q_ptr;
13551 
13552 	ASSERT(ill != NULL);
13553 	ipst = ill->ill_ipst;
13554 
13555 	/*
13556 	 * No IRE for this destination, so it can't be for us.
13557 	 * Unless we are forwarding, drop the packet.
13558 	 * We have to let source routed packets through
13559 	 * since we don't yet know if they are 'ping -l'
13560 	 * packets i.e. if they will go out over the
13561 	 * same interface as they came in on.
13562 	 */
13563 	if (ll_multicast) {
13564 		freemsg(mp);
13565 		return (NULL);
13566 	}
13567 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13568 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13569 		freemsg(mp);
13570 		return (NULL);
13571 	}
13572 
13573 	/*
13574 	 * Mark this packet as having originated externally.
13575 	 *
13576 	 * For non-forwarding code path, ire_send later double
13577 	 * checks this interface to see if it is still exists
13578 	 * post-ARP resolution.
13579 	 *
13580 	 * Also, IPQOS uses this to differentiate between
13581 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13582 	 * QOS packet processing in ip_wput_attach_llhdr().
13583 	 * The QoS module can mark the b_band for a fastpath message
13584 	 * or the dl_priority field in a unitdata_req header for
13585 	 * CoS marking. This info can only be found in
13586 	 * ip_wput_attach_llhdr().
13587 	 */
13588 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13589 	/*
13590 	 * Clear the indication that this may have a hardware checksum
13591 	 * as we are not using it
13592 	 */
13593 	DB_CKSUMFLAGS(mp) = 0;
13594 
13595 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13596 	    msg_getlabel(mp), ipst);
13597 
13598 	if (ire == NULL && ret_action == Forward_check_multirt) {
13599 		/* Let ip_newroute handle CGTP  */
13600 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13601 		return (NULL);
13602 	}
13603 
13604 	if (ire != NULL)
13605 		return (ire);
13606 
13607 	mp->b_prev = mp->b_next = 0;
13608 
13609 	if (ret_action == Forward_blackhole) {
13610 		freemsg(mp);
13611 		return (NULL);
13612 	}
13613 	/* send icmp unreachable */
13614 	q = WR(q);
13615 	/* Sent by forwarding path, and router is global zone */
13616 	if (ip_source_routed(ipha, ipst)) {
13617 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13618 		    GLOBAL_ZONEID, ipst);
13619 	} else {
13620 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13621 		    ipst);
13622 	}
13623 
13624 	return (NULL);
13625 
13626 }
13627 
13628 /*
13629  * check ip header length and align it.
13630  */
13631 static boolean_t
13632 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13633 {
13634 	ssize_t len;
13635 	ill_t *ill;
13636 	ipha_t	*ipha;
13637 
13638 	len = MBLKL(mp);
13639 
13640 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13641 		ill = (ill_t *)q->q_ptr;
13642 
13643 		if (!OK_32PTR(mp->b_rptr))
13644 			IP_STAT(ipst, ip_notaligned1);
13645 		else
13646 			IP_STAT(ipst, ip_notaligned2);
13647 		/* Guard against bogus device drivers */
13648 		if (len < 0) {
13649 			/* clear b_prev - used by ip_mroute_decap */
13650 			mp->b_prev = NULL;
13651 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13652 			freemsg(mp);
13653 			return (B_FALSE);
13654 		}
13655 
13656 		if (ip_rput_pullups++ == 0) {
13657 			ipha = (ipha_t *)mp->b_rptr;
13658 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13659 			    "ip_check_and_align_header: %s forced us to "
13660 			    " pullup pkt, hdr len %ld, hdr addr %p",
13661 			    ill->ill_name, len, (void *)ipha);
13662 		}
13663 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13664 			/* clear b_prev - used by ip_mroute_decap */
13665 			mp->b_prev = NULL;
13666 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13667 			freemsg(mp);
13668 			return (B_FALSE);
13669 		}
13670 	}
13671 	return (B_TRUE);
13672 }
13673 
13674 /*
13675  * Handle the situation where a packet came in on `ill' but matched an IRE
13676  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13677  * for interface statistics.
13678  */
13679 ire_t *
13680 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13681 {
13682 	ire_t		*new_ire;
13683 	ill_t		*ire_ill;
13684 	uint_t		ifindex;
13685 	ip_stack_t	*ipst = ill->ill_ipst;
13686 	boolean_t	strict_check = B_FALSE;
13687 
13688 	/*
13689 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13690 	 * issue (e.g. packet received on an underlying interface matched an
13691 	 * IRE_LOCAL on its associated group interface).
13692 	 */
13693 	if (ire->ire_rfq != NULL &&
13694 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13695 		return (ire);
13696 	}
13697 
13698 	/*
13699 	 * Do another ire lookup here, using the ingress ill, to see if the
13700 	 * interface is in a usesrc group.
13701 	 * As long as the ills belong to the same group, we don't consider
13702 	 * them to be arriving on the wrong interface. Thus, if the switch
13703 	 * is doing inbound load spreading, we won't drop packets when the
13704 	 * ip*_strict_dst_multihoming switch is on.
13705 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13706 	 * where the local address may not be unique. In this case we were
13707 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13708 	 * actually returned. The new lookup, which is more specific, should
13709 	 * only find the IRE_LOCAL associated with the ingress ill if one
13710 	 * exists.
13711 	 */
13712 
13713 	if (ire->ire_ipversion == IPV4_VERSION) {
13714 		if (ipst->ips_ip_strict_dst_multihoming)
13715 			strict_check = B_TRUE;
13716 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13717 		    ill->ill_ipif, ALL_ZONES, NULL,
13718 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13719 	} else {
13720 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13721 		if (ipst->ips_ipv6_strict_dst_multihoming)
13722 			strict_check = B_TRUE;
13723 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13724 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13725 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13726 	}
13727 	/*
13728 	 * If the same ire that was returned in ip_input() is found then this
13729 	 * is an indication that usesrc groups are in use. The packet
13730 	 * arrived on a different ill in the group than the one associated with
13731 	 * the destination address.  If a different ire was found then the same
13732 	 * IP address must be hosted on multiple ills. This is possible with
13733 	 * unnumbered point2point interfaces. We switch to use this new ire in
13734 	 * order to have accurate interface statistics.
13735 	 */
13736 	if (new_ire != NULL) {
13737 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13738 			ire_refrele(ire);
13739 			ire = new_ire;
13740 		} else {
13741 			ire_refrele(new_ire);
13742 		}
13743 		return (ire);
13744 	} else if ((ire->ire_rfq == NULL) &&
13745 	    (ire->ire_ipversion == IPV4_VERSION)) {
13746 		/*
13747 		 * The best match could have been the original ire which
13748 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13749 		 * the strict multihoming checks are irrelevant as we consider
13750 		 * local addresses hosted on lo0 to be interface agnostic. We
13751 		 * only expect a null ire_rfq on IREs which are associated with
13752 		 * lo0 hence we can return now.
13753 		 */
13754 		return (ire);
13755 	}
13756 
13757 	/*
13758 	 * Chase pointers once and store locally.
13759 	 */
13760 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13761 	    (ill_t *)(ire->ire_rfq->q_ptr);
13762 	ifindex = ill->ill_usesrc_ifindex;
13763 
13764 	/*
13765 	 * Check if it's a legal address on the 'usesrc' interface.
13766 	 */
13767 	if ((ifindex != 0) && (ire_ill != NULL) &&
13768 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13769 		return (ire);
13770 	}
13771 
13772 	/*
13773 	 * If the ip*_strict_dst_multihoming switch is on then we can
13774 	 * only accept this packet if the interface is marked as routing.
13775 	 */
13776 	if (!(strict_check))
13777 		return (ire);
13778 
13779 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13780 	    ILLF_ROUTER) != 0) {
13781 		return (ire);
13782 	}
13783 
13784 	ire_refrele(ire);
13785 	return (NULL);
13786 }
13787 
13788 /*
13789  *
13790  * This is the fast forward path. If we are here, we dont need to
13791  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13792  * needed to find the nexthop in this case is much simpler
13793  */
13794 ire_t *
13795 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13796 {
13797 	ipha_t	*ipha;
13798 	ire_t	*src_ire;
13799 	ill_t	*stq_ill;
13800 	uint_t	hlen;
13801 	uint_t	pkt_len;
13802 	uint32_t sum;
13803 	queue_t	*dev_q;
13804 	ip_stack_t *ipst = ill->ill_ipst;
13805 	mblk_t *fpmp;
13806 	enum	ire_forward_action ret_action;
13807 
13808 	ipha = (ipha_t *)mp->b_rptr;
13809 
13810 	if (ire != NULL &&
13811 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13812 	    ire->ire_zoneid != ALL_ZONES) {
13813 		/*
13814 		 * Should only use IREs that are visible to the global
13815 		 * zone for forwarding.
13816 		 */
13817 		ire_refrele(ire);
13818 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13819 		/*
13820 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13821 		 * transient cases. In such case, just drop the packet
13822 		 */
13823 		if (ire != NULL && ire->ire_type != IRE_CACHE)
13824 			goto indiscard;
13825 	}
13826 
13827 	/*
13828 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13829 	 * The loopback address check for both src and dst has already
13830 	 * been checked in ip_input
13831 	 */
13832 
13833 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13834 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13835 		goto drop;
13836 	}
13837 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13838 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13839 
13840 	if (src_ire != NULL) {
13841 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13842 		ire_refrele(src_ire);
13843 		goto drop;
13844 	}
13845 
13846 	/* No ire cache of nexthop. So first create one  */
13847 	if (ire == NULL) {
13848 
13849 		ire = ire_forward_simple(dst, &ret_action, ipst);
13850 
13851 		/*
13852 		 * We only come to ip_fast_forward if ip_cgtp_filter
13853 		 * is not set. So ire_forward() should not return with
13854 		 * Forward_check_multirt as the next action.
13855 		 */
13856 		ASSERT(ret_action != Forward_check_multirt);
13857 		if (ire == NULL) {
13858 			/* An attempt was made to forward the packet */
13859 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13860 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13861 			mp->b_prev = mp->b_next = 0;
13862 			/* send icmp unreachable */
13863 			/* Sent by forwarding path, and router is global zone */
13864 			if (ret_action == Forward_ret_icmp_err) {
13865 				if (ip_source_routed(ipha, ipst)) {
13866 					icmp_unreachable(ill->ill_wq, mp,
13867 					    ICMP_SOURCE_ROUTE_FAILED,
13868 					    GLOBAL_ZONEID, ipst);
13869 				} else {
13870 					icmp_unreachable(ill->ill_wq, mp,
13871 					    ICMP_HOST_UNREACHABLE,
13872 					    GLOBAL_ZONEID, ipst);
13873 				}
13874 			} else {
13875 				freemsg(mp);
13876 			}
13877 			return (NULL);
13878 		}
13879 	}
13880 
13881 	/*
13882 	 * Forwarding fastpath exception case:
13883 	 * If any of the following are true, we take the slowpath:
13884 	 *	o forwarding is not enabled
13885 	 *	o incoming and outgoing interface are the same, or in the same
13886 	 *	  IPMP group.
13887 	 *	o corresponding ire is in incomplete state
13888 	 *	o packet needs fragmentation
13889 	 *	o ARP cache is not resolved
13890 	 *
13891 	 * The codeflow from here on is thus:
13892 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13893 	 */
13894 	pkt_len = ntohs(ipha->ipha_length);
13895 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13896 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13897 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13898 	    (ire->ire_nce == NULL) ||
13899 	    (pkt_len > ire->ire_max_frag) ||
13900 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13901 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13902 	    ipha->ipha_ttl <= 1) {
13903 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13904 		    ipha, ill, B_FALSE, B_TRUE);
13905 		return (ire);
13906 	}
13907 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13908 
13909 	DTRACE_PROBE4(ip4__forwarding__start,
13910 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13911 
13912 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13913 	    ipst->ips_ipv4firewall_forwarding,
13914 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13915 
13916 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13917 
13918 	if (mp == NULL)
13919 		goto drop;
13920 
13921 	mp->b_datap->db_struioun.cksum.flags = 0;
13922 	/* Adjust the checksum to reflect the ttl decrement. */
13923 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13924 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13925 	ipha->ipha_ttl--;
13926 
13927 	/*
13928 	 * Write the link layer header.  We can do this safely here,
13929 	 * because we have already tested to make sure that the IP
13930 	 * policy is not set, and that we have a fast path destination
13931 	 * header.
13932 	 */
13933 	mp->b_rptr -= hlen;
13934 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13935 
13936 	UPDATE_IB_PKT_COUNT(ire);
13937 	ire->ire_last_used_time = lbolt;
13938 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13939 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13940 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13941 
13942 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13943 		dev_q = ire->ire_stq->q_next;
13944 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13945 			goto indiscard;
13946 	}
13947 
13948 	DTRACE_PROBE4(ip4__physical__out__start,
13949 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13950 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13951 	    ipst->ips_ipv4firewall_physical_out,
13952 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13953 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13954 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13955 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13956 	    ip6_t *, NULL, int, 0);
13957 
13958 	if (mp != NULL) {
13959 		if (ipst->ips_ip4_observe.he_interested) {
13960 			zoneid_t szone;
13961 
13962 			/*
13963 			 * Both of these functions expect b_rptr to be
13964 			 * where the IP header starts, so advance past the
13965 			 * link layer header if present.
13966 			 */
13967 			mp->b_rptr += hlen;
13968 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13969 			    ipst, ALL_ZONES);
13970 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
13971 			    ALL_ZONES, ill, ipst);
13972 			mp->b_rptr -= hlen;
13973 		}
13974 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
13975 	}
13976 	return (ire);
13977 
13978 indiscard:
13979 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13980 drop:
13981 	if (mp != NULL)
13982 		freemsg(mp);
13983 	return (ire);
13984 
13985 }
13986 
13987 /*
13988  * This function is called in the forwarding slowpath, when
13989  * either the ire lacks the link-layer address, or the packet needs
13990  * further processing(eg. fragmentation), before transmission.
13991  */
13992 
13993 static void
13994 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13995     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
13996 {
13997 	queue_t		*dev_q;
13998 	ire_t		*src_ire;
13999 	ip_stack_t	*ipst = ill->ill_ipst;
14000 	boolean_t	same_illgrp = B_FALSE;
14001 
14002 	ASSERT(ire->ire_stq != NULL);
14003 
14004 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14005 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14006 
14007 	/*
14008 	 * If the caller of this function is ip_fast_forward() skip the
14009 	 * next three checks as it does not apply.
14010 	 */
14011 	if (from_ip_fast_forward)
14012 		goto skip;
14013 
14014 	if (ll_multicast != 0) {
14015 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14016 		goto drop_pkt;
14017 	}
14018 
14019 	/*
14020 	 * check if ipha_src is a broadcast address. Note that this
14021 	 * check is redundant when we get here from ip_fast_forward()
14022 	 * which has already done this check. However, since we can
14023 	 * also get here from ip_rput_process_broadcast() or, for
14024 	 * for the slow path through ip_fast_forward(), we perform
14025 	 * the check again for code-reusability
14026 	 */
14027 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14028 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14029 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14030 		if (src_ire != NULL)
14031 			ire_refrele(src_ire);
14032 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14033 		ip2dbg(("ip_rput_process_forward: Received packet with"
14034 		    " bad src/dst address on %s\n", ill->ill_name));
14035 		goto drop_pkt;
14036 	}
14037 
14038 	/*
14039 	 * Check if we want to forward this one at this time.
14040 	 * We allow source routed packets on a host provided that
14041 	 * they go out the same ill or illgrp as they came in on.
14042 	 *
14043 	 * XXX To be quicker, we may wish to not chase pointers to
14044 	 * get the ILLF_ROUTER flag and instead store the
14045 	 * forwarding policy in the ire.  An unfortunate
14046 	 * side-effect of that would be requiring an ire flush
14047 	 * whenever the ILLF_ROUTER flag changes.
14048 	 */
14049 skip:
14050 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14051 
14052 	if (((ill->ill_flags &
14053 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14054 	    !(ip_source_routed(ipha, ipst) &&
14055 	    (ire->ire_rfq == q || same_illgrp))) {
14056 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14057 		if (ip_source_routed(ipha, ipst)) {
14058 			q = WR(q);
14059 			/*
14060 			 * Clear the indication that this may have
14061 			 * hardware checksum as we are not using it.
14062 			 */
14063 			DB_CKSUMFLAGS(mp) = 0;
14064 			/* Sent by forwarding path, and router is global zone */
14065 			icmp_unreachable(q, mp,
14066 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14067 			return;
14068 		}
14069 		goto drop_pkt;
14070 	}
14071 
14072 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14073 
14074 	/* Packet is being forwarded. Turning off hwcksum flag. */
14075 	DB_CKSUMFLAGS(mp) = 0;
14076 	if (ipst->ips_ip_g_send_redirects) {
14077 		/*
14078 		 * Check whether the incoming interface and outgoing
14079 		 * interface is part of the same group. If so,
14080 		 * send redirects.
14081 		 *
14082 		 * Check the source address to see if it originated
14083 		 * on the same logical subnet it is going back out on.
14084 		 * If so, we should be able to send it a redirect.
14085 		 * Avoid sending a redirect if the destination
14086 		 * is directly connected (i.e., ipha_dst is the same
14087 		 * as ire_gateway_addr or the ire_addr of the
14088 		 * nexthop IRE_CACHE ), or if the packet was source
14089 		 * routed out this interface.
14090 		 */
14091 		ipaddr_t src, nhop;
14092 		mblk_t	*mp1;
14093 		ire_t	*nhop_ire = NULL;
14094 
14095 		/*
14096 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14097 		 * If so, send redirects.
14098 		 */
14099 		if ((ire->ire_rfq == q || same_illgrp) &&
14100 		    !ip_source_routed(ipha, ipst)) {
14101 
14102 			nhop = (ire->ire_gateway_addr != 0 ?
14103 			    ire->ire_gateway_addr : ire->ire_addr);
14104 
14105 			if (ipha->ipha_dst == nhop) {
14106 				/*
14107 				 * We avoid sending a redirect if the
14108 				 * destination is directly connected
14109 				 * because it is possible that multiple
14110 				 * IP subnets may have been configured on
14111 				 * the link, and the source may not
14112 				 * be on the same subnet as ip destination,
14113 				 * even though they are on the same
14114 				 * physical link.
14115 				 */
14116 				goto sendit;
14117 			}
14118 
14119 			src = ipha->ipha_src;
14120 
14121 			/*
14122 			 * We look up the interface ire for the nexthop,
14123 			 * to see if ipha_src is in the same subnet
14124 			 * as the nexthop.
14125 			 *
14126 			 * Note that, if, in the future, IRE_CACHE entries
14127 			 * are obsoleted,  this lookup will not be needed,
14128 			 * as the ire passed to this function will be the
14129 			 * same as the nhop_ire computed below.
14130 			 */
14131 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14132 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14133 			    0, NULL, MATCH_IRE_TYPE, ipst);
14134 
14135 			if (nhop_ire != NULL) {
14136 				if ((src & nhop_ire->ire_mask) ==
14137 				    (nhop & nhop_ire->ire_mask)) {
14138 					/*
14139 					 * The source is directly connected.
14140 					 * Just copy the ip header (which is
14141 					 * in the first mblk)
14142 					 */
14143 					mp1 = copyb(mp);
14144 					if (mp1 != NULL) {
14145 						icmp_send_redirect(WR(q), mp1,
14146 						    nhop, ipst);
14147 					}
14148 				}
14149 				ire_refrele(nhop_ire);
14150 			}
14151 		}
14152 	}
14153 sendit:
14154 	dev_q = ire->ire_stq->q_next;
14155 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14156 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14157 		freemsg(mp);
14158 		return;
14159 	}
14160 
14161 	ip_rput_forward(ire, ipha, mp, ill);
14162 	return;
14163 
14164 drop_pkt:
14165 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14166 	freemsg(mp);
14167 }
14168 
14169 ire_t *
14170 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14171     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14172 {
14173 	queue_t		*q;
14174 	uint16_t	hcksumflags;
14175 	ip_stack_t	*ipst = ill->ill_ipst;
14176 
14177 	q = *qp;
14178 
14179 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14180 
14181 	/*
14182 	 * Clear the indication that this may have hardware
14183 	 * checksum as we are not using it for forwarding.
14184 	 */
14185 	hcksumflags = DB_CKSUMFLAGS(mp);
14186 	DB_CKSUMFLAGS(mp) = 0;
14187 
14188 	/*
14189 	 * Directed broadcast forwarding: if the packet came in over a
14190 	 * different interface then it is routed out over we can forward it.
14191 	 */
14192 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14193 		ire_refrele(ire);
14194 		freemsg(mp);
14195 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14196 		return (NULL);
14197 	}
14198 	/*
14199 	 * For multicast we have set dst to be INADDR_BROADCAST
14200 	 * for delivering to all STREAMS.
14201 	 */
14202 	if (!CLASSD(ipha->ipha_dst)) {
14203 		ire_t *new_ire;
14204 		ipif_t *ipif;
14205 
14206 		ipif = ipif_get_next_ipif(NULL, ill);
14207 		if (ipif == NULL) {
14208 discard:		ire_refrele(ire);
14209 			freemsg(mp);
14210 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14211 			return (NULL);
14212 		}
14213 		new_ire = ire_ctable_lookup(dst, 0, 0,
14214 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14215 		ipif_refrele(ipif);
14216 
14217 		if (new_ire != NULL) {
14218 			/*
14219 			 * If the matching IRE_BROADCAST is part of an IPMP
14220 			 * group, then drop the packet unless our ill has been
14221 			 * nominated to receive for the group.
14222 			 */
14223 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14224 			    new_ire->ire_rfq != q) {
14225 				ire_refrele(new_ire);
14226 				goto discard;
14227 			}
14228 
14229 			/*
14230 			 * In the special case of multirouted broadcast
14231 			 * packets, we unconditionally need to "gateway"
14232 			 * them to the appropriate interface here.
14233 			 * In the normal case, this cannot happen, because
14234 			 * there is no broadcast IRE tagged with the
14235 			 * RTF_MULTIRT flag.
14236 			 */
14237 			if (new_ire->ire_flags & RTF_MULTIRT) {
14238 				ire_refrele(new_ire);
14239 				if (ire->ire_rfq != NULL) {
14240 					q = ire->ire_rfq;
14241 					*qp = q;
14242 				}
14243 			} else {
14244 				ire_refrele(ire);
14245 				ire = new_ire;
14246 			}
14247 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14248 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14249 				/*
14250 				 * Free the message if
14251 				 * ip_g_forward_directed_bcast is turned
14252 				 * off for non-local broadcast.
14253 				 */
14254 				ire_refrele(ire);
14255 				freemsg(mp);
14256 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14257 				return (NULL);
14258 			}
14259 		} else {
14260 			/*
14261 			 * This CGTP packet successfully passed the
14262 			 * CGTP filter, but the related CGTP
14263 			 * broadcast IRE has not been found,
14264 			 * meaning that the redundant ipif is
14265 			 * probably down. However, if we discarded
14266 			 * this packet, its duplicate would be
14267 			 * filtered out by the CGTP filter so none
14268 			 * of them would get through. So we keep
14269 			 * going with this one.
14270 			 */
14271 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14272 			if (ire->ire_rfq != NULL) {
14273 				q = ire->ire_rfq;
14274 				*qp = q;
14275 			}
14276 		}
14277 	}
14278 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14279 		/*
14280 		 * Verify that there are not more then one
14281 		 * IRE_BROADCAST with this broadcast address which
14282 		 * has ire_stq set.
14283 		 * TODO: simplify, loop over all IRE's
14284 		 */
14285 		ire_t	*ire1;
14286 		int	num_stq = 0;
14287 		mblk_t	*mp1;
14288 
14289 		/* Find the first one with ire_stq set */
14290 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14291 		for (ire1 = ire; ire1 &&
14292 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14293 		    ire1 = ire1->ire_next)
14294 			;
14295 		if (ire1) {
14296 			ire_refrele(ire);
14297 			ire = ire1;
14298 			IRE_REFHOLD(ire);
14299 		}
14300 
14301 		/* Check if there are additional ones with stq set */
14302 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14303 			if (ire->ire_addr != ire1->ire_addr)
14304 				break;
14305 			if (ire1->ire_stq) {
14306 				num_stq++;
14307 				break;
14308 			}
14309 		}
14310 		rw_exit(&ire->ire_bucket->irb_lock);
14311 		if (num_stq == 1 && ire->ire_stq != NULL) {
14312 			ip1dbg(("ip_rput_process_broadcast: directed "
14313 			    "broadcast to 0x%x\n",
14314 			    ntohl(ire->ire_addr)));
14315 			mp1 = copymsg(mp);
14316 			if (mp1) {
14317 				switch (ipha->ipha_protocol) {
14318 				case IPPROTO_UDP:
14319 					ip_udp_input(q, mp1, ipha, ire, ill);
14320 					break;
14321 				default:
14322 					ip_proto_input(q, mp1, ipha, ire, ill,
14323 					    0);
14324 					break;
14325 				}
14326 			}
14327 			/*
14328 			 * Adjust ttl to 2 (1+1 - the forward engine
14329 			 * will decrement it by one.
14330 			 */
14331 			if (ip_csum_hdr(ipha)) {
14332 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14333 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14334 				freemsg(mp);
14335 				ire_refrele(ire);
14336 				return (NULL);
14337 			}
14338 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14339 			ipha->ipha_hdr_checksum = 0;
14340 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14341 			ip_rput_process_forward(q, mp, ire, ipha,
14342 			    ill, ll_multicast, B_FALSE);
14343 			ire_refrele(ire);
14344 			return (NULL);
14345 		}
14346 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14347 		    ntohl(ire->ire_addr)));
14348 	}
14349 
14350 	/* Restore any hardware checksum flags */
14351 	DB_CKSUMFLAGS(mp) = hcksumflags;
14352 	return (ire);
14353 }
14354 
14355 /* ARGSUSED */
14356 static boolean_t
14357 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14358     int *ll_multicast, ipaddr_t *dstp)
14359 {
14360 	ip_stack_t	*ipst = ill->ill_ipst;
14361 
14362 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14363 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14364 	    ntohs(ipha->ipha_length));
14365 
14366 	/*
14367 	 * So that we don't end up with dups, only one ill in an IPMP group is
14368 	 * nominated to receive multicast traffic.
14369 	 */
14370 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14371 		goto drop_pkt;
14372 
14373 	/*
14374 	 * Forward packets only if we have joined the allmulti
14375 	 * group on this interface.
14376 	 */
14377 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14378 		int retval;
14379 
14380 		/*
14381 		 * Clear the indication that this may have hardware
14382 		 * checksum as we are not using it.
14383 		 */
14384 		DB_CKSUMFLAGS(mp) = 0;
14385 		retval = ip_mforward(ill, ipha, mp);
14386 		/* ip_mforward updates mib variables if needed */
14387 		/* clear b_prev - used by ip_mroute_decap */
14388 		mp->b_prev = NULL;
14389 
14390 		switch (retval) {
14391 		case 0:
14392 			/*
14393 			 * pkt is okay and arrived on phyint.
14394 			 *
14395 			 * If we are running as a multicast router
14396 			 * we need to see all IGMP and/or PIM packets.
14397 			 */
14398 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14399 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14400 				goto done;
14401 			}
14402 			break;
14403 		case -1:
14404 			/* pkt is mal-formed, toss it */
14405 			goto drop_pkt;
14406 		case 1:
14407 			/* pkt is okay and arrived on a tunnel */
14408 			/*
14409 			 * If we are running a multicast router
14410 			 *  we need to see all igmp packets.
14411 			 */
14412 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14413 				*dstp = INADDR_BROADCAST;
14414 				*ll_multicast = 1;
14415 				return (B_FALSE);
14416 			}
14417 
14418 			goto drop_pkt;
14419 		}
14420 	}
14421 
14422 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14423 		/*
14424 		 * This might just be caused by the fact that
14425 		 * multiple IP Multicast addresses map to the same
14426 		 * link layer multicast - no need to increment counter!
14427 		 */
14428 		freemsg(mp);
14429 		return (B_TRUE);
14430 	}
14431 done:
14432 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14433 	/*
14434 	 * This assumes the we deliver to all streams for multicast
14435 	 * and broadcast packets.
14436 	 */
14437 	*dstp = INADDR_BROADCAST;
14438 	*ll_multicast = 1;
14439 	return (B_FALSE);
14440 drop_pkt:
14441 	ip2dbg(("ip_rput: drop pkt\n"));
14442 	freemsg(mp);
14443 	return (B_TRUE);
14444 }
14445 
14446 /*
14447  * This function is used to both return an indication of whether or not
14448  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14449  * and in doing so, determine whether or not it is broadcast vs multicast.
14450  * For it to be a broadcast packet, we must have the appropriate mblk_t
14451  * hanging off the ill_t.  If this is either not present or doesn't match
14452  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14453  * to be multicast.  Thus NICs that have no broadcast address (or no
14454  * capability for one, such as point to point links) cannot return as
14455  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14456  * the return values simplifies the current use of the return value of this
14457  * function, which is to pass through the multicast/broadcast characteristic
14458  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14459  * changing the return value to some other symbol demands the appropriate
14460  * "translation" when hpe_flags is set prior to calling hook_run() for
14461  * packet events.
14462  */
14463 int
14464 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14465 {
14466 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14467 	mblk_t *bmp;
14468 
14469 	if (ind->dl_group_address) {
14470 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14471 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14472 		    MBLKL(mb) &&
14473 		    (bmp = ill->ill_bcast_mp) != NULL) {
14474 			dl_unitdata_req_t *dlur;
14475 			uint8_t *bphys_addr;
14476 
14477 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14478 			if (ill->ill_sap_length < 0)
14479 				bphys_addr = (uchar_t *)dlur +
14480 				    dlur->dl_dest_addr_offset;
14481 			else
14482 				bphys_addr = (uchar_t *)dlur +
14483 				    dlur->dl_dest_addr_offset +
14484 				    ill->ill_sap_length;
14485 
14486 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14487 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14488 				return (HPE_BROADCAST);
14489 			}
14490 			return (HPE_MULTICAST);
14491 		}
14492 		return (HPE_MULTICAST);
14493 	}
14494 	return (0);
14495 }
14496 
14497 static boolean_t
14498 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14499     int *ll_multicast, mblk_t **mpp)
14500 {
14501 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14502 	boolean_t must_copy = B_FALSE;
14503 	struct iocblk   *iocp;
14504 	ipha_t		*ipha;
14505 	ip_stack_t	*ipst = ill->ill_ipst;
14506 
14507 #define	rptr    ((uchar_t *)ipha)
14508 
14509 	first_mp = *first_mpp;
14510 	mp = *mpp;
14511 
14512 	ASSERT(first_mp == mp);
14513 
14514 	/*
14515 	 * if db_ref > 1 then copymsg and free original. Packet may be
14516 	 * changed and do not want other entity who has a reference to this
14517 	 * message to trip over the changes. This is a blind change because
14518 	 * trying to catch all places that might change packet is too
14519 	 * difficult (since it may be a module above this one)
14520 	 *
14521 	 * This corresponds to the non-fast path case. We walk down the full
14522 	 * chain in this case, and check the db_ref count of all the dblks,
14523 	 * and do a copymsg if required. It is possible that the db_ref counts
14524 	 * of the data blocks in the mblk chain can be different.
14525 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14526 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14527 	 * 'snoop' is running.
14528 	 */
14529 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14530 		if (mp1->b_datap->db_ref > 1) {
14531 			must_copy = B_TRUE;
14532 			break;
14533 		}
14534 	}
14535 
14536 	if (must_copy) {
14537 		mp1 = copymsg(mp);
14538 		if (mp1 == NULL) {
14539 			for (mp1 = mp; mp1 != NULL;
14540 			    mp1 = mp1->b_cont) {
14541 				mp1->b_next = NULL;
14542 				mp1->b_prev = NULL;
14543 			}
14544 			freemsg(mp);
14545 			if (ill != NULL) {
14546 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14547 			} else {
14548 				BUMP_MIB(&ipst->ips_ip_mib,
14549 				    ipIfStatsInDiscards);
14550 			}
14551 			return (B_TRUE);
14552 		}
14553 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14554 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14555 			/* Copy b_prev - used by ip_mroute_decap */
14556 			to_mp->b_prev = from_mp->b_prev;
14557 			from_mp->b_prev = NULL;
14558 		}
14559 		*first_mpp = first_mp = mp1;
14560 		freemsg(mp);
14561 		mp = mp1;
14562 		*mpp = mp1;
14563 	}
14564 
14565 	ipha = (ipha_t *)mp->b_rptr;
14566 
14567 	/*
14568 	 * previous code has a case for M_DATA.
14569 	 * We want to check how that happens.
14570 	 */
14571 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14572 	switch (first_mp->b_datap->db_type) {
14573 	case M_PROTO:
14574 	case M_PCPROTO:
14575 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14576 		    DL_UNITDATA_IND) {
14577 			/* Go handle anything other than data elsewhere. */
14578 			ip_rput_dlpi(q, mp);
14579 			return (B_TRUE);
14580 		}
14581 
14582 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14583 		/* Ditch the DLPI header. */
14584 		mp1 = mp->b_cont;
14585 		ASSERT(first_mp == mp);
14586 		*first_mpp = mp1;
14587 		freeb(mp);
14588 		*mpp = mp1;
14589 		return (B_FALSE);
14590 	case M_IOCACK:
14591 		ip1dbg(("got iocack "));
14592 		iocp = (struct iocblk *)mp->b_rptr;
14593 		switch (iocp->ioc_cmd) {
14594 		case DL_IOC_HDR_INFO:
14595 			ill = (ill_t *)q->q_ptr;
14596 			ill_fastpath_ack(ill, mp);
14597 			return (B_TRUE);
14598 		default:
14599 			putnext(q, mp);
14600 			return (B_TRUE);
14601 		}
14602 		/* FALLTHRU */
14603 	case M_ERROR:
14604 	case M_HANGUP:
14605 		/*
14606 		 * Since this is on the ill stream we unconditionally
14607 		 * bump up the refcount
14608 		 */
14609 		ill_refhold(ill);
14610 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14611 		return (B_TRUE);
14612 	case M_CTL:
14613 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14614 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14615 		    IPHADA_M_CTL)) {
14616 			/*
14617 			 * It's an IPsec accelerated packet.
14618 			 * Make sure that the ill from which we received the
14619 			 * packet has enabled IPsec hardware acceleration.
14620 			 */
14621 			if (!(ill->ill_capabilities &
14622 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14623 				/* IPsec kstats: bean counter */
14624 				freemsg(mp);
14625 				return (B_TRUE);
14626 			}
14627 
14628 			/*
14629 			 * Make mp point to the mblk following the M_CTL,
14630 			 * then process according to type of mp.
14631 			 * After this processing, first_mp will point to
14632 			 * the data-attributes and mp to the pkt following
14633 			 * the M_CTL.
14634 			 */
14635 			mp = first_mp->b_cont;
14636 			if (mp == NULL) {
14637 				freemsg(first_mp);
14638 				return (B_TRUE);
14639 			}
14640 			/*
14641 			 * A Hardware Accelerated packet can only be M_DATA
14642 			 * ESP or AH packet.
14643 			 */
14644 			if (mp->b_datap->db_type != M_DATA) {
14645 				/* non-M_DATA IPsec accelerated packet */
14646 				IPSECHW_DEBUG(IPSECHW_PKT,
14647 				    ("non-M_DATA IPsec accelerated pkt\n"));
14648 				freemsg(first_mp);
14649 				return (B_TRUE);
14650 			}
14651 			ipha = (ipha_t *)mp->b_rptr;
14652 			if (ipha->ipha_protocol != IPPROTO_AH &&
14653 			    ipha->ipha_protocol != IPPROTO_ESP) {
14654 				IPSECHW_DEBUG(IPSECHW_PKT,
14655 				    ("non-M_DATA IPsec accelerated pkt\n"));
14656 				freemsg(first_mp);
14657 				return (B_TRUE);
14658 			}
14659 			*mpp = mp;
14660 			return (B_FALSE);
14661 		}
14662 		putnext(q, mp);
14663 		return (B_TRUE);
14664 	case M_IOCNAK:
14665 		ip1dbg(("got iocnak "));
14666 		iocp = (struct iocblk *)mp->b_rptr;
14667 		switch (iocp->ioc_cmd) {
14668 		case DL_IOC_HDR_INFO:
14669 			ip_rput_other(NULL, q, mp, NULL);
14670 			return (B_TRUE);
14671 		default:
14672 			break;
14673 		}
14674 		/* FALLTHRU */
14675 	default:
14676 		putnext(q, mp);
14677 		return (B_TRUE);
14678 	}
14679 }
14680 
14681 /* Read side put procedure.  Packets coming from the wire arrive here. */
14682 void
14683 ip_rput(queue_t *q, mblk_t *mp)
14684 {
14685 	ill_t	*ill;
14686 	union DL_primitives *dl;
14687 
14688 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14689 
14690 	ill = (ill_t *)q->q_ptr;
14691 
14692 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14693 		/*
14694 		 * If things are opening or closing, only accept high-priority
14695 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14696 		 * created; on close, things hanging off the ill may have been
14697 		 * freed already.)
14698 		 */
14699 		dl = (union DL_primitives *)mp->b_rptr;
14700 		if (DB_TYPE(mp) != M_PCPROTO ||
14701 		    dl->dl_primitive == DL_UNITDATA_IND) {
14702 			inet_freemsg(mp);
14703 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14704 			    "ip_rput_end: q %p (%S)", q, "uninit");
14705 			return;
14706 		}
14707 	}
14708 
14709 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14710 	    "ip_rput_end: q %p (%S)", q, "end");
14711 
14712 	ip_input(ill, NULL, mp, NULL);
14713 }
14714 
14715 static mblk_t *
14716 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14717 {
14718 	mblk_t *mp1;
14719 	boolean_t adjusted = B_FALSE;
14720 	ip_stack_t *ipst = ill->ill_ipst;
14721 
14722 	IP_STAT(ipst, ip_db_ref);
14723 	/*
14724 	 * The IP_RECVSLLA option depends on having the
14725 	 * link layer header. First check that:
14726 	 * a> the underlying device is of type ether,
14727 	 * since this option is currently supported only
14728 	 * over ethernet.
14729 	 * b> there is enough room to copy over the link
14730 	 * layer header.
14731 	 *
14732 	 * Once the checks are done, adjust rptr so that
14733 	 * the link layer header will be copied via
14734 	 * copymsg. Note that, IFT_ETHER may be returned
14735 	 * by some non-ethernet drivers but in this case
14736 	 * the second check will fail.
14737 	 */
14738 	if (ill->ill_type == IFT_ETHER &&
14739 	    (mp->b_rptr - mp->b_datap->db_base) >=
14740 	    sizeof (struct ether_header)) {
14741 		mp->b_rptr -= sizeof (struct ether_header);
14742 		adjusted = B_TRUE;
14743 	}
14744 	mp1 = copymsg(mp);
14745 
14746 	if (mp1 == NULL) {
14747 		mp->b_next = NULL;
14748 		/* clear b_prev - used by ip_mroute_decap */
14749 		mp->b_prev = NULL;
14750 		freemsg(mp);
14751 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14752 		return (NULL);
14753 	}
14754 
14755 	if (adjusted) {
14756 		/*
14757 		 * Copy is done. Restore the pointer in
14758 		 * the _new_ mblk
14759 		 */
14760 		mp1->b_rptr += sizeof (struct ether_header);
14761 	}
14762 
14763 	/* Copy b_prev - used by ip_mroute_decap */
14764 	mp1->b_prev = mp->b_prev;
14765 	mp->b_prev = NULL;
14766 
14767 	/* preserve the hardware checksum flags and data, if present */
14768 	if (DB_CKSUMFLAGS(mp) != 0) {
14769 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14770 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14771 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14772 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14773 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14774 	}
14775 
14776 	freemsg(mp);
14777 	return (mp1);
14778 }
14779 
14780 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14781 	if (tail != NULL)					\
14782 		tail->b_next = mp;				\
14783 	else							\
14784 		head = mp;					\
14785 	tail = mp;						\
14786 	cnt++;							\
14787 }
14788 
14789 /*
14790  * Direct read side procedure capable of dealing with chains. GLDv3 based
14791  * drivers call this function directly with mblk chains while STREAMS
14792  * read side procedure ip_rput() calls this for single packet with ip_ring
14793  * set to NULL to process one packet at a time.
14794  *
14795  * The ill will always be valid if this function is called directly from
14796  * the driver.
14797  *
14798  * If ip_input() is called from GLDv3:
14799  *
14800  *   - This must be a non-VLAN IP stream.
14801  *   - 'mp' is either an untagged or a special priority-tagged packet.
14802  *   - Any VLAN tag that was in the MAC header has been stripped.
14803  *
14804  * If the IP header in packet is not 32-bit aligned, every message in the
14805  * chain will be aligned before further operations. This is required on SPARC
14806  * platform.
14807  */
14808 /* ARGSUSED */
14809 void
14810 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14811     struct mac_header_info_s *mhip)
14812 {
14813 	ipaddr_t		dst = NULL;
14814 	ipaddr_t		prev_dst;
14815 	ire_t			*ire = NULL;
14816 	ipha_t			*ipha;
14817 	uint_t			pkt_len;
14818 	ssize_t			len;
14819 	uint_t			opt_len;
14820 	int			ll_multicast;
14821 	int			cgtp_flt_pkt;
14822 	queue_t			*q = ill->ill_rq;
14823 	squeue_t		*curr_sqp = NULL;
14824 	mblk_t 			*head = NULL;
14825 	mblk_t			*tail = NULL;
14826 	mblk_t			*first_mp;
14827 	int			cnt = 0;
14828 	ip_stack_t		*ipst = ill->ill_ipst;
14829 	mblk_t			*mp;
14830 	mblk_t			*dmp;
14831 	uint8_t			tag;
14832 
14833 	ASSERT(mp_chain != NULL);
14834 	ASSERT(ill != NULL);
14835 
14836 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14837 
14838 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14839 
14840 #define	rptr	((uchar_t *)ipha)
14841 
14842 	while (mp_chain != NULL) {
14843 		mp = mp_chain;
14844 		mp_chain = mp_chain->b_next;
14845 		mp->b_next = NULL;
14846 		ll_multicast = 0;
14847 
14848 		/*
14849 		 * We do ire caching from one iteration to
14850 		 * another. In the event the packet chain contains
14851 		 * all packets from the same dst, this caching saves
14852 		 * an ire_cache_lookup for each of the succeeding
14853 		 * packets in a packet chain.
14854 		 */
14855 		prev_dst = dst;
14856 
14857 		/*
14858 		 * if db_ref > 1 then copymsg and free original. Packet
14859 		 * may be changed and we do not want the other entity
14860 		 * who has a reference to this message to trip over the
14861 		 * changes. This is a blind change because trying to
14862 		 * catch all places that might change the packet is too
14863 		 * difficult.
14864 		 *
14865 		 * This corresponds to the fast path case, where we have
14866 		 * a chain of M_DATA mblks.  We check the db_ref count
14867 		 * of only the 1st data block in the mblk chain. There
14868 		 * doesn't seem to be a reason why a device driver would
14869 		 * send up data with varying db_ref counts in the mblk
14870 		 * chain. In any case the Fast path is a private
14871 		 * interface, and our drivers don't do such a thing.
14872 		 * Given the above assumption, there is no need to walk
14873 		 * down the entire mblk chain (which could have a
14874 		 * potential performance problem)
14875 		 *
14876 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14877 		 * to here because of exclusive ip stacks and vnics.
14878 		 * Packets transmitted from exclusive stack over vnic
14879 		 * can have db_ref > 1 and when it gets looped back to
14880 		 * another vnic in a different zone, you have ip_input()
14881 		 * getting dblks with db_ref > 1. So if someone
14882 		 * complains of TCP performance under this scenario,
14883 		 * take a serious look here on the impact of copymsg().
14884 		 */
14885 
14886 		if (DB_REF(mp) > 1) {
14887 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14888 				continue;
14889 		}
14890 
14891 		/*
14892 		 * Check and align the IP header.
14893 		 */
14894 		first_mp = mp;
14895 		if (DB_TYPE(mp) == M_DATA) {
14896 			dmp = mp;
14897 		} else if (DB_TYPE(mp) == M_PROTO &&
14898 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14899 			dmp = mp->b_cont;
14900 		} else {
14901 			dmp = NULL;
14902 		}
14903 		if (dmp != NULL) {
14904 			/*
14905 			 * IP header ptr not aligned?
14906 			 * OR IP header not complete in first mblk
14907 			 */
14908 			if (!OK_32PTR(dmp->b_rptr) ||
14909 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14910 				if (!ip_check_and_align_header(q, dmp, ipst))
14911 					continue;
14912 			}
14913 		}
14914 
14915 		/*
14916 		 * ip_input fast path
14917 		 */
14918 
14919 		/* mblk type is not M_DATA */
14920 		if (DB_TYPE(mp) != M_DATA) {
14921 			if (ip_rput_process_notdata(q, &first_mp, ill,
14922 			    &ll_multicast, &mp))
14923 				continue;
14924 
14925 			/*
14926 			 * The only way we can get here is if we had a
14927 			 * packet that was either a DL_UNITDATA_IND or
14928 			 * an M_CTL for an IPsec accelerated packet.
14929 			 *
14930 			 * In either case, the first_mp will point to
14931 			 * the leading M_PROTO or M_CTL.
14932 			 */
14933 			ASSERT(first_mp != NULL);
14934 		} else if (mhip != NULL) {
14935 			/*
14936 			 * ll_multicast is set here so that it is ready
14937 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14938 			 * manipulates ll_multicast in the same fashion when
14939 			 * called from ip_rput_process_notdata.
14940 			 */
14941 			switch (mhip->mhi_dsttype) {
14942 			case MAC_ADDRTYPE_MULTICAST :
14943 				ll_multicast = HPE_MULTICAST;
14944 				break;
14945 			case MAC_ADDRTYPE_BROADCAST :
14946 				ll_multicast = HPE_BROADCAST;
14947 				break;
14948 			default :
14949 				break;
14950 			}
14951 		}
14952 
14953 		/* Only M_DATA can come here and it is always aligned */
14954 		ASSERT(DB_TYPE(mp) == M_DATA);
14955 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14956 
14957 		ipha = (ipha_t *)mp->b_rptr;
14958 		len = mp->b_wptr - rptr;
14959 		pkt_len = ntohs(ipha->ipha_length);
14960 
14961 		/*
14962 		 * We must count all incoming packets, even if they end
14963 		 * up being dropped later on.
14964 		 */
14965 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14966 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14967 
14968 		/* multiple mblk or too short */
14969 		len -= pkt_len;
14970 		if (len != 0) {
14971 			/*
14972 			 * Make sure we have data length consistent
14973 			 * with the IP header.
14974 			 */
14975 			if (mp->b_cont == NULL) {
14976 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14977 					BUMP_MIB(ill->ill_ip_mib,
14978 					    ipIfStatsInHdrErrors);
14979 					ip2dbg(("ip_input: drop pkt\n"));
14980 					freemsg(mp);
14981 					continue;
14982 				}
14983 				mp->b_wptr = rptr + pkt_len;
14984 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14985 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14986 					BUMP_MIB(ill->ill_ip_mib,
14987 					    ipIfStatsInHdrErrors);
14988 					ip2dbg(("ip_input: drop pkt\n"));
14989 					freemsg(mp);
14990 					continue;
14991 				}
14992 				(void) adjmsg(mp, -len);
14993 				/*
14994 				 * adjmsg may have freed an mblk from the chain,
14995 				 * hence invalidate any hw checksum here. This
14996 				 * will force IP to calculate the checksum in
14997 				 * sw, but only for this packet.
14998 				 */
14999 				DB_CKSUMFLAGS(mp) = 0;
15000 				IP_STAT(ipst, ip_multimblk3);
15001 			}
15002 		}
15003 
15004 		/* Obtain the dst of the current packet */
15005 		dst = ipha->ipha_dst;
15006 
15007 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15008 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15009 		    ipha, ip6_t *, NULL, int, 0);
15010 
15011 		/*
15012 		 * The following test for loopback is faster than
15013 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15014 		 * operations.
15015 		 * Note that these addresses are always in network byte order
15016 		 */
15017 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15018 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15019 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15020 			freemsg(mp);
15021 			continue;
15022 		}
15023 
15024 		/*
15025 		 * The event for packets being received from a 'physical'
15026 		 * interface is placed after validation of the source and/or
15027 		 * destination address as being local so that packets can be
15028 		 * redirected to loopback addresses using ipnat.
15029 		 */
15030 		DTRACE_PROBE4(ip4__physical__in__start,
15031 		    ill_t *, ill, ill_t *, NULL,
15032 		    ipha_t *, ipha, mblk_t *, first_mp);
15033 
15034 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15035 		    ipst->ips_ipv4firewall_physical_in,
15036 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15037 
15038 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15039 
15040 		if (first_mp == NULL) {
15041 			continue;
15042 		}
15043 		dst = ipha->ipha_dst;
15044 		/*
15045 		 * Attach any necessary label information to
15046 		 * this packet
15047 		 */
15048 		if (is_system_labeled() &&
15049 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15050 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15051 			freemsg(mp);
15052 			continue;
15053 		}
15054 
15055 		if (ipst->ips_ip4_observe.he_interested) {
15056 			zoneid_t dzone;
15057 
15058 			/*
15059 			 * On the inbound path the src zone will be unknown as
15060 			 * this packet has come from the wire.
15061 			 */
15062 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15063 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15064 			    ill, ipst);
15065 		}
15066 
15067 		/*
15068 		 * Reuse the cached ire only if the ipha_dst of the previous
15069 		 * packet is the same as the current packet AND it is not
15070 		 * INADDR_ANY.
15071 		 */
15072 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15073 		    (ire != NULL)) {
15074 			ire_refrele(ire);
15075 			ire = NULL;
15076 		}
15077 
15078 		opt_len = ipha->ipha_version_and_hdr_length -
15079 		    IP_SIMPLE_HDR_VERSION;
15080 
15081 		/*
15082 		 * Check to see if we can take the fastpath.
15083 		 * That is possible if the following conditions are met
15084 		 *	o Tsol disabled
15085 		 *	o CGTP disabled
15086 		 *	o ipp_action_count is 0
15087 		 *	o no options in the packet
15088 		 *	o not a RSVP packet
15089 		 * 	o not a multicast packet
15090 		 *	o ill not in IP_DHCPINIT_IF mode
15091 		 */
15092 		if (!is_system_labeled() &&
15093 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15094 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15095 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15096 			if (ire == NULL)
15097 				ire = ire_cache_lookup_simple(dst, ipst);
15098 			/*
15099 			 * Unless forwarding is enabled, dont call
15100 			 * ip_fast_forward(). Incoming packet is for forwarding
15101 			 */
15102 			if ((ill->ill_flags & ILLF_ROUTER) &&
15103 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15104 				ire = ip_fast_forward(ire, dst, ill, mp);
15105 				continue;
15106 			}
15107 			/* incoming packet is for local consumption */
15108 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15109 				goto local;
15110 		}
15111 
15112 		/*
15113 		 * Disable ire caching for anything more complex
15114 		 * than the simple fast path case we checked for above.
15115 		 */
15116 		if (ire != NULL) {
15117 			ire_refrele(ire);
15118 			ire = NULL;
15119 		}
15120 
15121 		/*
15122 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15123 		 * server to unicast DHCP packets to a DHCP client using the
15124 		 * IP address it is offering to the client.  This can be
15125 		 * disabled through the "broadcast bit", but not all DHCP
15126 		 * servers honor that bit.  Therefore, to interoperate with as
15127 		 * many DHCP servers as possible, the DHCP client allows the
15128 		 * server to unicast, but we treat those packets as broadcast
15129 		 * here.  Note that we don't rewrite the packet itself since
15130 		 * (a) that would mess up the checksums and (b) the DHCP
15131 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15132 		 * hand it the packet regardless.
15133 		 */
15134 		if (ill->ill_dhcpinit != 0 &&
15135 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15136 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15137 			udpha_t *udpha;
15138 
15139 			/*
15140 			 * Reload ipha since pullupmsg() can change b_rptr.
15141 			 */
15142 			ipha = (ipha_t *)mp->b_rptr;
15143 			udpha = (udpha_t *)&ipha[1];
15144 
15145 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15146 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15147 				    mblk_t *, mp);
15148 				dst = INADDR_BROADCAST;
15149 			}
15150 		}
15151 
15152 		/* Full-blown slow path */
15153 		if (opt_len != 0) {
15154 			if (len != 0)
15155 				IP_STAT(ipst, ip_multimblk4);
15156 			else
15157 				IP_STAT(ipst, ip_ipoptions);
15158 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15159 			    &dst, ipst))
15160 				continue;
15161 		}
15162 
15163 		/*
15164 		 * Invoke the CGTP (multirouting) filtering module to process
15165 		 * the incoming packet. Packets identified as duplicates
15166 		 * must be discarded. Filtering is active only if the
15167 		 * the ip_cgtp_filter ndd variable is non-zero.
15168 		 */
15169 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15170 		if (ipst->ips_ip_cgtp_filter &&
15171 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15172 			netstackid_t stackid;
15173 
15174 			stackid = ipst->ips_netstack->netstack_stackid;
15175 			cgtp_flt_pkt =
15176 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15177 			    ill->ill_phyint->phyint_ifindex, mp);
15178 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15179 				freemsg(first_mp);
15180 				continue;
15181 			}
15182 		}
15183 
15184 		/*
15185 		 * If rsvpd is running, let RSVP daemon handle its processing
15186 		 * and forwarding of RSVP multicast/unicast packets.
15187 		 * If rsvpd is not running but mrouted is running, RSVP
15188 		 * multicast packets are forwarded as multicast traffic
15189 		 * and RSVP unicast packets are forwarded by unicast router.
15190 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15191 		 * packets are not forwarded, but the unicast packets are
15192 		 * forwarded like unicast traffic.
15193 		 */
15194 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15195 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15196 		    NULL) {
15197 			/* RSVP packet and rsvpd running. Treat as ours */
15198 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15199 			/*
15200 			 * This assumes that we deliver to all streams for
15201 			 * multicast and broadcast packets.
15202 			 * We have to force ll_multicast to 1 to handle the
15203 			 * M_DATA messages passed in from ip_mroute_decap.
15204 			 */
15205 			dst = INADDR_BROADCAST;
15206 			ll_multicast = 1;
15207 		} else if (CLASSD(dst)) {
15208 			/* packet is multicast */
15209 			mp->b_next = NULL;
15210 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15211 			    &ll_multicast, &dst))
15212 				continue;
15213 		}
15214 
15215 		if (ire == NULL) {
15216 			ire = ire_cache_lookup(dst, ALL_ZONES,
15217 			    msg_getlabel(mp), ipst);
15218 		}
15219 
15220 		if (ire != NULL && ire->ire_stq != NULL &&
15221 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15222 		    ire->ire_zoneid != ALL_ZONES) {
15223 			/*
15224 			 * Should only use IREs that are visible from the
15225 			 * global zone for forwarding.
15226 			 */
15227 			ire_refrele(ire);
15228 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15229 			    msg_getlabel(mp), ipst);
15230 		}
15231 
15232 		if (ire == NULL) {
15233 			/*
15234 			 * No IRE for this destination, so it can't be for us.
15235 			 * Unless we are forwarding, drop the packet.
15236 			 * We have to let source routed packets through
15237 			 * since we don't yet know if they are 'ping -l'
15238 			 * packets i.e. if they will go out over the
15239 			 * same interface as they came in on.
15240 			 */
15241 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15242 			if (ire == NULL)
15243 				continue;
15244 		}
15245 
15246 		/*
15247 		 * Broadcast IRE may indicate either broadcast or
15248 		 * multicast packet
15249 		 */
15250 		if (ire->ire_type == IRE_BROADCAST) {
15251 			/*
15252 			 * Skip broadcast checks if packet is UDP multicast;
15253 			 * we'd rather not enter ip_rput_process_broadcast()
15254 			 * unless the packet is broadcast for real, since
15255 			 * that routine is a no-op for multicast.
15256 			 */
15257 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15258 			    !CLASSD(ipha->ipha_dst)) {
15259 				ire = ip_rput_process_broadcast(&q, mp,
15260 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15261 				    ll_multicast);
15262 				if (ire == NULL)
15263 					continue;
15264 			}
15265 		} else if (ire->ire_stq != NULL) {
15266 			/* fowarding? */
15267 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15268 			    ll_multicast, B_FALSE);
15269 			/* ip_rput_process_forward consumed the packet */
15270 			continue;
15271 		}
15272 
15273 local:
15274 		/*
15275 		 * If the queue in the ire is different to the ingress queue
15276 		 * then we need to check to see if we can accept the packet.
15277 		 * Note that for multicast packets and broadcast packets sent
15278 		 * to a broadcast address which is shared between multiple
15279 		 * interfaces we should not do this since we just got a random
15280 		 * broadcast ire.
15281 		 */
15282 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15283 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15284 			if (ire == NULL) {
15285 				/* Drop packet */
15286 				BUMP_MIB(ill->ill_ip_mib,
15287 				    ipIfStatsForwProhibits);
15288 				freemsg(mp);
15289 				continue;
15290 			}
15291 			if (ire->ire_rfq != NULL)
15292 				q = ire->ire_rfq;
15293 		}
15294 
15295 		switch (ipha->ipha_protocol) {
15296 		case IPPROTO_TCP:
15297 			ASSERT(first_mp == mp);
15298 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15299 			    mp, 0, q, ip_ring)) != NULL) {
15300 				if (curr_sqp == NULL) {
15301 					curr_sqp = GET_SQUEUE(mp);
15302 					ASSERT(cnt == 0);
15303 					cnt++;
15304 					head = tail = mp;
15305 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15306 					ASSERT(tail != NULL);
15307 					cnt++;
15308 					tail->b_next = mp;
15309 					tail = mp;
15310 				} else {
15311 					/*
15312 					 * A different squeue. Send the
15313 					 * chain for the previous squeue on
15314 					 * its way. This shouldn't happen
15315 					 * often unless interrupt binding
15316 					 * changes.
15317 					 */
15318 					IP_STAT(ipst, ip_input_multi_squeue);
15319 					SQUEUE_ENTER(curr_sqp, head,
15320 					    tail, cnt, SQ_PROCESS, tag);
15321 					curr_sqp = GET_SQUEUE(mp);
15322 					head = mp;
15323 					tail = mp;
15324 					cnt = 1;
15325 				}
15326 			}
15327 			continue;
15328 		case IPPROTO_UDP:
15329 			ASSERT(first_mp == mp);
15330 			ip_udp_input(q, mp, ipha, ire, ill);
15331 			continue;
15332 		case IPPROTO_SCTP:
15333 			ASSERT(first_mp == mp);
15334 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15335 			    q, dst);
15336 			/* ire has been released by ip_sctp_input */
15337 			ire = NULL;
15338 			continue;
15339 		case IPPROTO_ENCAP:
15340 		case IPPROTO_IPV6:
15341 			ASSERT(first_mp == mp);
15342 			if (ip_iptun_input(NULL, mp, ipha, ill, ire, ipst))
15343 				break;
15344 			/*
15345 			 * If there was no IP tunnel data-link bound to
15346 			 * receive this packet, then we fall through to
15347 			 * allow potential raw sockets bound to either of
15348 			 * these protocols to pick it up.
15349 			 */
15350 		default:
15351 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15352 			continue;
15353 		}
15354 	}
15355 
15356 	if (ire != NULL)
15357 		ire_refrele(ire);
15358 
15359 	if (head != NULL)
15360 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15361 
15362 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15363 	    "ip_input_end: q %p (%S)", q, "end");
15364 #undef  rptr
15365 }
15366 
15367 /*
15368  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15369  * a chain of packets in the poll mode. The packets have gone through the
15370  * data link processing but not IP processing. For performance and latency
15371  * reasons, the squeue wants to process the chain in line instead of feeding
15372  * it back via ip_input path.
15373  *
15374  * So this is a light weight function which checks to see if the packets
15375  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15376  * but we still do the paranoid check) meant for local machine and we don't
15377  * have labels etc enabled. Packets that meet the criterion are returned to
15378  * the squeue and processed inline while the rest go via ip_input path.
15379  */
15380 /*ARGSUSED*/
15381 mblk_t *
15382 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15383     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15384 {
15385 	mblk_t 		*mp;
15386 	ipaddr_t	dst = NULL;
15387 	ipaddr_t	prev_dst;
15388 	ire_t		*ire = NULL;
15389 	ipha_t		*ipha;
15390 	uint_t		pkt_len;
15391 	ssize_t		len;
15392 	uint_t		opt_len;
15393 	queue_t		*q = ill->ill_rq;
15394 	squeue_t	*curr_sqp;
15395 	mblk_t 		*ahead = NULL;	/* Accepted head */
15396 	mblk_t		*atail = NULL;	/* Accepted tail */
15397 	uint_t		acnt = 0;	/* Accepted count */
15398 	mblk_t		*utail = NULL;	/* Unaccepted head */
15399 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15400 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15401 	ip_stack_t	*ipst = ill->ill_ipst;
15402 
15403 	*cnt = 0;
15404 
15405 	ASSERT(ill != NULL);
15406 	ASSERT(ip_ring != NULL);
15407 
15408 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15409 
15410 #define	rptr	((uchar_t *)ipha)
15411 
15412 	while (mp_chain != NULL) {
15413 		mp = mp_chain;
15414 		mp_chain = mp_chain->b_next;
15415 		mp->b_next = NULL;
15416 
15417 		/*
15418 		 * We do ire caching from one iteration to
15419 		 * another. In the event the packet chain contains
15420 		 * all packets from the same dst, this caching saves
15421 		 * an ire_cache_lookup for each of the succeeding
15422 		 * packets in a packet chain.
15423 		 */
15424 		prev_dst = dst;
15425 
15426 		ipha = (ipha_t *)mp->b_rptr;
15427 		len = mp->b_wptr - rptr;
15428 
15429 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15430 
15431 		/*
15432 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15433 		 * or doesn't have min len, reject.
15434 		 */
15435 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15436 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15437 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15438 			continue;
15439 		}
15440 
15441 		pkt_len = ntohs(ipha->ipha_length);
15442 		if (len != pkt_len) {
15443 			if (len > pkt_len) {
15444 				mp->b_wptr = rptr + pkt_len;
15445 			} else {
15446 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15447 				continue;
15448 			}
15449 		}
15450 
15451 		opt_len = ipha->ipha_version_and_hdr_length -
15452 		    IP_SIMPLE_HDR_VERSION;
15453 		dst = ipha->ipha_dst;
15454 
15455 		/* IP version bad or there are IP options */
15456 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15457 		    mp, &ipha, &dst, ipst)))
15458 			continue;
15459 
15460 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15461 		    (ipst->ips_ip_cgtp_filter &&
15462 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15463 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15464 			continue;
15465 		}
15466 
15467 		/*
15468 		 * Reuse the cached ire only if the ipha_dst of the previous
15469 		 * packet is the same as the current packet AND it is not
15470 		 * INADDR_ANY.
15471 		 */
15472 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15473 		    (ire != NULL)) {
15474 			ire_refrele(ire);
15475 			ire = NULL;
15476 		}
15477 
15478 		if (ire == NULL)
15479 			ire = ire_cache_lookup_simple(dst, ipst);
15480 
15481 		/*
15482 		 * Unless forwarding is enabled, dont call
15483 		 * ip_fast_forward(). Incoming packet is for forwarding
15484 		 */
15485 		if ((ill->ill_flags & ILLF_ROUTER) &&
15486 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15487 
15488 			DTRACE_PROBE4(ip4__physical__in__start,
15489 			    ill_t *, ill, ill_t *, NULL,
15490 			    ipha_t *, ipha, mblk_t *, mp);
15491 
15492 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15493 			    ipst->ips_ipv4firewall_physical_in,
15494 			    ill, NULL, ipha, mp, mp, 0, ipst);
15495 
15496 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15497 
15498 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15499 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15500 			    pkt_len);
15501 
15502 			if (mp != NULL)
15503 				ire = ip_fast_forward(ire, dst, ill, mp);
15504 			continue;
15505 		}
15506 
15507 		/* incoming packet is for local consumption */
15508 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15509 			goto local_accept;
15510 
15511 		/*
15512 		 * Disable ire caching for anything more complex
15513 		 * than the simple fast path case we checked for above.
15514 		 */
15515 		if (ire != NULL) {
15516 			ire_refrele(ire);
15517 			ire = NULL;
15518 		}
15519 
15520 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15521 		    ipst);
15522 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15523 		    ire->ire_stq != NULL) {
15524 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15525 			if (ire != NULL) {
15526 				ire_refrele(ire);
15527 				ire = NULL;
15528 			}
15529 			continue;
15530 		}
15531 
15532 local_accept:
15533 
15534 		if (ire->ire_rfq != q) {
15535 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15536 			if (ire != NULL) {
15537 				ire_refrele(ire);
15538 				ire = NULL;
15539 			}
15540 			continue;
15541 		}
15542 
15543 		/*
15544 		 * The event for packets being received from a 'physical'
15545 		 * interface is placed after validation of the source and/or
15546 		 * destination address as being local so that packets can be
15547 		 * redirected to loopback addresses using ipnat.
15548 		 */
15549 		DTRACE_PROBE4(ip4__physical__in__start,
15550 		    ill_t *, ill, ill_t *, NULL,
15551 		    ipha_t *, ipha, mblk_t *, mp);
15552 
15553 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15554 		    ipst->ips_ipv4firewall_physical_in,
15555 		    ill, NULL, ipha, mp, mp, 0, ipst);
15556 
15557 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15558 
15559 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15560 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15561 
15562 		if (mp != NULL &&
15563 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15564 		    0, q, ip_ring)) != NULL) {
15565 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15566 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15567 			} else {
15568 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15569 				    SQ_FILL, SQTAG_IP_INPUT);
15570 			}
15571 		}
15572 	}
15573 
15574 	if (ire != NULL)
15575 		ire_refrele(ire);
15576 
15577 	if (uhead != NULL)
15578 		ip_input(ill, ip_ring, uhead, NULL);
15579 
15580 	if (ahead != NULL) {
15581 		*last = atail;
15582 		*cnt = acnt;
15583 		return (ahead);
15584 	}
15585 
15586 	return (NULL);
15587 #undef  rptr
15588 }
15589 
15590 static void
15591 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15592     t_uscalar_t err)
15593 {
15594 	if (dl_err == DL_SYSERR) {
15595 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15596 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15597 		    ill->ill_name, dl_primstr(prim), err);
15598 		return;
15599 	}
15600 
15601 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15602 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15603 	    dl_errstr(dl_err));
15604 }
15605 
15606 /*
15607  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15608  * than DL_UNITDATA_IND messages. If we need to process this message
15609  * exclusively, we call qwriter_ip, in which case we also need to call
15610  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15611  */
15612 void
15613 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15614 {
15615 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15616 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15617 	ill_t		*ill = q->q_ptr;
15618 	t_uscalar_t	prim = dloa->dl_primitive;
15619 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15620 
15621 	ip1dbg(("ip_rput_dlpi"));
15622 
15623 	/*
15624 	 * If we received an ACK but didn't send a request for it, then it
15625 	 * can't be part of any pending operation; discard up-front.
15626 	 */
15627 	switch (prim) {
15628 	case DL_ERROR_ACK:
15629 		reqprim = dlea->dl_error_primitive;
15630 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15631 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15632 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15633 		    dlea->dl_unix_errno));
15634 		break;
15635 	case DL_OK_ACK:
15636 		reqprim = dloa->dl_correct_primitive;
15637 		break;
15638 	case DL_INFO_ACK:
15639 		reqprim = DL_INFO_REQ;
15640 		break;
15641 	case DL_BIND_ACK:
15642 		reqprim = DL_BIND_REQ;
15643 		break;
15644 	case DL_PHYS_ADDR_ACK:
15645 		reqprim = DL_PHYS_ADDR_REQ;
15646 		break;
15647 	case DL_NOTIFY_ACK:
15648 		reqprim = DL_NOTIFY_REQ;
15649 		break;
15650 	case DL_CONTROL_ACK:
15651 		reqprim = DL_CONTROL_REQ;
15652 		break;
15653 	case DL_CAPABILITY_ACK:
15654 		reqprim = DL_CAPABILITY_REQ;
15655 		break;
15656 	}
15657 
15658 	if (prim != DL_NOTIFY_IND) {
15659 		if (reqprim == DL_PRIM_INVAL ||
15660 		    !ill_dlpi_pending(ill, reqprim)) {
15661 			/* Not a DLPI message we support or expected */
15662 			freemsg(mp);
15663 			return;
15664 		}
15665 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15666 		    dl_primstr(reqprim)));
15667 	}
15668 
15669 	switch (reqprim) {
15670 	case DL_UNBIND_REQ:
15671 		/*
15672 		 * NOTE: we mark the unbind as complete even if we got a
15673 		 * DL_ERROR_ACK, since there's not much else we can do.
15674 		 */
15675 		mutex_enter(&ill->ill_lock);
15676 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15677 		cv_signal(&ill->ill_cv);
15678 		mutex_exit(&ill->ill_lock);
15679 		break;
15680 
15681 	case DL_ENABMULTI_REQ:
15682 		if (prim == DL_OK_ACK) {
15683 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15684 				ill->ill_dlpi_multicast_state = IDS_OK;
15685 		}
15686 		break;
15687 	}
15688 
15689 	/*
15690 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15691 	 * need to become writer to continue to process it.  Because an
15692 	 * exclusive operation doesn't complete until replies to all queued
15693 	 * DLPI messages have been received, we know we're in the middle of an
15694 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15695 	 *
15696 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15697 	 * Since this is on the ill stream we unconditionally bump up the
15698 	 * refcount without doing ILL_CAN_LOOKUP().
15699 	 */
15700 	ill_refhold(ill);
15701 	if (prim == DL_NOTIFY_IND)
15702 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15703 	else
15704 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15705 }
15706 
15707 /*
15708  * Handling of DLPI messages that require exclusive access to the ipsq.
15709  *
15710  * Need to do ill_pending_mp_release on ioctl completion, which could
15711  * happen here. (along with mi_copy_done)
15712  */
15713 /* ARGSUSED */
15714 static void
15715 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15716 {
15717 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15718 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15719 	int		err = 0;
15720 	ill_t		*ill;
15721 	ipif_t		*ipif = NULL;
15722 	mblk_t		*mp1 = NULL;
15723 	conn_t		*connp = NULL;
15724 	t_uscalar_t	paddrreq;
15725 	mblk_t		*mp_hw;
15726 	boolean_t	success;
15727 	boolean_t	ioctl_aborted = B_FALSE;
15728 	boolean_t	log = B_TRUE;
15729 	ip_stack_t		*ipst;
15730 
15731 	ip1dbg(("ip_rput_dlpi_writer .."));
15732 	ill = (ill_t *)q->q_ptr;
15733 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15734 	ASSERT(IAM_WRITER_ILL(ill));
15735 
15736 	ipst = ill->ill_ipst;
15737 
15738 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15739 	/*
15740 	 * The current ioctl could have been aborted by the user and a new
15741 	 * ioctl to bring up another ill could have started. We could still
15742 	 * get a response from the driver later.
15743 	 */
15744 	if (ipif != NULL && ipif->ipif_ill != ill)
15745 		ioctl_aborted = B_TRUE;
15746 
15747 	switch (dloa->dl_primitive) {
15748 	case DL_ERROR_ACK:
15749 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15750 		    dl_primstr(dlea->dl_error_primitive)));
15751 
15752 		switch (dlea->dl_error_primitive) {
15753 		case DL_DISABMULTI_REQ:
15754 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15755 			break;
15756 		case DL_PROMISCON_REQ:
15757 		case DL_PROMISCOFF_REQ:
15758 		case DL_UNBIND_REQ:
15759 		case DL_ATTACH_REQ:
15760 		case DL_INFO_REQ:
15761 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15762 			break;
15763 		case DL_NOTIFY_REQ:
15764 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15765 			log = B_FALSE;
15766 			break;
15767 		case DL_PHYS_ADDR_REQ:
15768 			/*
15769 			 * For IPv6 only, there are two additional
15770 			 * phys_addr_req's sent to the driver to get the
15771 			 * IPv6 token and lla. This allows IP to acquire
15772 			 * the hardware address format for a given interface
15773 			 * without having built in knowledge of the hardware
15774 			 * address. ill_phys_addr_pend keeps track of the last
15775 			 * DL_PAR sent so we know which response we are
15776 			 * dealing with. ill_dlpi_done will update
15777 			 * ill_phys_addr_pend when it sends the next req.
15778 			 * We don't complete the IOCTL until all three DL_PARs
15779 			 * have been attempted, so set *_len to 0 and break.
15780 			 */
15781 			paddrreq = ill->ill_phys_addr_pend;
15782 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15783 			if (paddrreq == DL_IPV6_TOKEN) {
15784 				ill->ill_token_length = 0;
15785 				log = B_FALSE;
15786 				break;
15787 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15788 				ill->ill_nd_lla_len = 0;
15789 				log = B_FALSE;
15790 				break;
15791 			}
15792 			/*
15793 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15794 			 * We presumably have an IOCTL hanging out waiting
15795 			 * for completion. Find it and complete the IOCTL
15796 			 * with the error noted.
15797 			 * However, ill_dl_phys was called on an ill queue
15798 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15799 			 * set. But the ioctl is known to be pending on ill_wq.
15800 			 */
15801 			if (!ill->ill_ifname_pending)
15802 				break;
15803 			ill->ill_ifname_pending = 0;
15804 			if (!ioctl_aborted)
15805 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15806 			if (mp1 != NULL) {
15807 				/*
15808 				 * This operation (SIOCSLIFNAME) must have
15809 				 * happened on the ill. Assert there is no conn
15810 				 */
15811 				ASSERT(connp == NULL);
15812 				q = ill->ill_wq;
15813 			}
15814 			break;
15815 		case DL_BIND_REQ:
15816 			ill_dlpi_done(ill, DL_BIND_REQ);
15817 			if (ill->ill_ifname_pending)
15818 				break;
15819 			/*
15820 			 * Something went wrong with the bind.  We presumably
15821 			 * have an IOCTL hanging out waiting for completion.
15822 			 * Find it, take down the interface that was coming
15823 			 * up, and complete the IOCTL with the error noted.
15824 			 */
15825 			if (!ioctl_aborted)
15826 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15827 			if (mp1 != NULL) {
15828 				/*
15829 				 * This might be a result of a DL_NOTE_REPLUMB
15830 				 * notification. In that case, connp is NULL.
15831 				 */
15832 				if (connp != NULL)
15833 					q = CONNP_TO_WQ(connp);
15834 
15835 				(void) ipif_down(ipif, NULL, NULL);
15836 				/* error is set below the switch */
15837 			}
15838 			break;
15839 		case DL_ENABMULTI_REQ:
15840 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15841 
15842 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15843 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15844 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15845 				ipif_t *ipif;
15846 
15847 				printf("ip: joining multicasts failed (%d)"
15848 				    " on %s - will use link layer "
15849 				    "broadcasts for multicast\n",
15850 				    dlea->dl_errno, ill->ill_name);
15851 
15852 				/*
15853 				 * Set up the multicast mapping alone.
15854 				 * writer, so ok to access ill->ill_ipif
15855 				 * without any lock.
15856 				 */
15857 				ipif = ill->ill_ipif;
15858 				mutex_enter(&ill->ill_phyint->phyint_lock);
15859 				ill->ill_phyint->phyint_flags |=
15860 				    PHYI_MULTI_BCAST;
15861 				mutex_exit(&ill->ill_phyint->phyint_lock);
15862 
15863 				if (!ill->ill_isv6) {
15864 					(void) ipif_arp_setup_multicast(ipif,
15865 					    NULL);
15866 				} else {
15867 					(void) ipif_ndp_setup_multicast(ipif,
15868 					    NULL);
15869 				}
15870 			}
15871 			freemsg(mp);	/* Don't want to pass this up */
15872 			return;
15873 		case DL_CONTROL_REQ:
15874 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15875 			    "DL_CONTROL_REQ\n"));
15876 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15877 			freemsg(mp);
15878 			return;
15879 		case DL_CAPABILITY_REQ:
15880 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15881 			    "DL_CAPABILITY REQ\n"));
15882 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15883 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15884 			ill_capability_done(ill);
15885 			freemsg(mp);
15886 			return;
15887 		}
15888 		/*
15889 		 * Note the error for IOCTL completion (mp1 is set when
15890 		 * ready to complete ioctl). If ill_ifname_pending_err is
15891 		 * set, an error occured during plumbing (ill_ifname_pending),
15892 		 * so we want to report that error.
15893 		 *
15894 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15895 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15896 		 * expected to get errack'd if the driver doesn't support
15897 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15898 		 * if these error conditions are encountered.
15899 		 */
15900 		if (mp1 != NULL) {
15901 			if (ill->ill_ifname_pending_err != 0)  {
15902 				err = ill->ill_ifname_pending_err;
15903 				ill->ill_ifname_pending_err = 0;
15904 			} else {
15905 				err = dlea->dl_unix_errno ?
15906 				    dlea->dl_unix_errno : ENXIO;
15907 			}
15908 		/*
15909 		 * If we're plumbing an interface and an error hasn't already
15910 		 * been saved, set ill_ifname_pending_err to the error passed
15911 		 * up. Ignore the error if log is B_FALSE (see comment above).
15912 		 */
15913 		} else if (log && ill->ill_ifname_pending &&
15914 		    ill->ill_ifname_pending_err == 0) {
15915 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15916 			    dlea->dl_unix_errno : ENXIO;
15917 		}
15918 
15919 		if (log)
15920 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15921 			    dlea->dl_errno, dlea->dl_unix_errno);
15922 		break;
15923 	case DL_CAPABILITY_ACK:
15924 		ill_capability_ack(ill, mp);
15925 		/*
15926 		 * The message has been handed off to ill_capability_ack
15927 		 * and must not be freed below
15928 		 */
15929 		mp = NULL;
15930 		break;
15931 
15932 	case DL_CONTROL_ACK:
15933 		/* We treat all of these as "fire and forget" */
15934 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15935 		break;
15936 	case DL_INFO_ACK:
15937 		/* Call a routine to handle this one. */
15938 		ill_dlpi_done(ill, DL_INFO_REQ);
15939 		ip_ll_subnet_defaults(ill, mp);
15940 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15941 		return;
15942 	case DL_BIND_ACK:
15943 		/*
15944 		 * We should have an IOCTL waiting on this unless
15945 		 * sent by ill_dl_phys, in which case just return
15946 		 */
15947 		ill_dlpi_done(ill, DL_BIND_REQ);
15948 		if (ill->ill_ifname_pending)
15949 			break;
15950 
15951 		if (!ioctl_aborted)
15952 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15953 		if (mp1 == NULL)
15954 			break;
15955 		/*
15956 		 * mp1 was added by ill_dl_up(). if that is a result of
15957 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
15958 		 */
15959 		if (connp != NULL)
15960 			q = CONNP_TO_WQ(connp);
15961 
15962 		/*
15963 		 * We are exclusive. So nothing can change even after
15964 		 * we get the pending mp. If need be we can put it back
15965 		 * and restart, as in calling ipif_arp_up()  below.
15966 		 */
15967 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15968 
15969 		mutex_enter(&ill->ill_lock);
15970 		ill->ill_dl_up = 1;
15971 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15972 		mutex_exit(&ill->ill_lock);
15973 
15974 		/*
15975 		 * Now bring up the resolver; when that is complete, we'll
15976 		 * create IREs.  Note that we intentionally mirror what
15977 		 * ipif_up() would have done, because we got here by way of
15978 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15979 		 */
15980 		if (ill->ill_isv6) {
15981 			if (ill->ill_flags & ILLF_XRESOLV) {
15982 				if (connp != NULL)
15983 					mutex_enter(&connp->conn_lock);
15984 				mutex_enter(&ill->ill_lock);
15985 				success = ipsq_pending_mp_add(connp, ipif, q,
15986 				    mp1, 0);
15987 				mutex_exit(&ill->ill_lock);
15988 				if (connp != NULL)
15989 					mutex_exit(&connp->conn_lock);
15990 				if (success) {
15991 					err = ipif_resolver_up(ipif,
15992 					    Res_act_initial);
15993 					if (err == EINPROGRESS) {
15994 						freemsg(mp);
15995 						return;
15996 					}
15997 					ASSERT(err != 0);
15998 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
15999 					ASSERT(mp1 != NULL);
16000 				} else {
16001 					/* conn has started closing */
16002 					err = EINTR;
16003 				}
16004 			} else { /* Non XRESOLV interface */
16005 				(void) ipif_resolver_up(ipif, Res_act_initial);
16006 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16007 					err = ipif_up_done_v6(ipif);
16008 			}
16009 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16010 			/*
16011 			 * ARP and other v4 external resolvers.
16012 			 * Leave the pending mblk intact so that
16013 			 * the ioctl completes in ip_rput().
16014 			 */
16015 			if (connp != NULL)
16016 				mutex_enter(&connp->conn_lock);
16017 			mutex_enter(&ill->ill_lock);
16018 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16019 			mutex_exit(&ill->ill_lock);
16020 			if (connp != NULL)
16021 				mutex_exit(&connp->conn_lock);
16022 			if (success) {
16023 				err = ipif_resolver_up(ipif, Res_act_initial);
16024 				if (err == EINPROGRESS) {
16025 					freemsg(mp);
16026 					return;
16027 				}
16028 				ASSERT(err != 0);
16029 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16030 			} else {
16031 				/* The conn has started closing */
16032 				err = EINTR;
16033 			}
16034 		} else {
16035 			/*
16036 			 * This one is complete. Reply to pending ioctl.
16037 			 */
16038 			(void) ipif_resolver_up(ipif, Res_act_initial);
16039 			err = ipif_up_done(ipif);
16040 		}
16041 
16042 		if ((err == 0) && (ill->ill_up_ipifs)) {
16043 			err = ill_up_ipifs(ill, q, mp1);
16044 			if (err == EINPROGRESS) {
16045 				freemsg(mp);
16046 				return;
16047 			}
16048 		}
16049 
16050 		/*
16051 		 * If we have a moved ipif to bring up, and everything has
16052 		 * succeeded to this point, bring it up on the IPMP ill.
16053 		 * Otherwise, leave it down -- the admin can try to bring it
16054 		 * up by hand if need be.
16055 		 */
16056 		if (ill->ill_move_ipif != NULL) {
16057 			if (err != 0) {
16058 				ill->ill_move_ipif = NULL;
16059 			} else {
16060 				ipif = ill->ill_move_ipif;
16061 				ill->ill_move_ipif = NULL;
16062 				err = ipif_up(ipif, q, mp1);
16063 				if (err == EINPROGRESS) {
16064 					freemsg(mp);
16065 					return;
16066 				}
16067 			}
16068 		}
16069 		break;
16070 
16071 	case DL_NOTIFY_IND: {
16072 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16073 		ire_t *ire;
16074 		uint_t orig_mtu;
16075 		boolean_t need_ire_walk_v4 = B_FALSE;
16076 		boolean_t need_ire_walk_v6 = B_FALSE;
16077 
16078 		switch (notify->dl_notification) {
16079 		case DL_NOTE_PHYS_ADDR:
16080 			err = ill_set_phys_addr(ill, mp);
16081 			break;
16082 
16083 		case DL_NOTE_REPLUMB:
16084 			/*
16085 			 * Directly return after calling ill_replumb().
16086 			 * Note that we should not free mp as it is reused
16087 			 * in the ill_replumb() function.
16088 			 */
16089 			err = ill_replumb(ill, mp);
16090 			return;
16091 
16092 		case DL_NOTE_FASTPATH_FLUSH:
16093 			ill_fastpath_flush(ill);
16094 			break;
16095 
16096 		case DL_NOTE_SDU_SIZE:
16097 			/*
16098 			 * Change the MTU size of the interface, of all
16099 			 * attached ipif's, and of all relevant ire's.  The
16100 			 * new value's a uint32_t at notify->dl_data.
16101 			 * Mtu change Vs. new ire creation - protocol below.
16102 			 *
16103 			 * a Mark the ipif as IPIF_CHANGING.
16104 			 * b Set the new mtu in the ipif.
16105 			 * c Change the ire_max_frag on all affected ires
16106 			 * d Unmark the IPIF_CHANGING
16107 			 *
16108 			 * To see how the protocol works, assume an interface
16109 			 * route is also being added simultaneously by
16110 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16111 			 * the ire. If the ire is created before step a,
16112 			 * it will be cleaned up by step c. If the ire is
16113 			 * created after step d, it will see the new value of
16114 			 * ipif_mtu. Any attempt to create the ire between
16115 			 * steps a to d will fail because of the IPIF_CHANGING
16116 			 * flag. Note that ire_create() is passed a pointer to
16117 			 * the ipif_mtu, and not the value. During ire_add
16118 			 * under the bucket lock, the ire_max_frag of the
16119 			 * new ire being created is set from the ipif/ire from
16120 			 * which it is being derived.
16121 			 */
16122 			mutex_enter(&ill->ill_lock);
16123 
16124 			orig_mtu = ill->ill_max_mtu;
16125 			ill->ill_max_frag = (uint_t)notify->dl_data;
16126 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16127 
16128 			/*
16129 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16130 			 * clamp ill_max_mtu at it.
16131 			 */
16132 			if (ill->ill_user_mtu != 0 &&
16133 			    ill->ill_user_mtu < ill->ill_max_mtu)
16134 				ill->ill_max_mtu = ill->ill_user_mtu;
16135 
16136 			/*
16137 			 * If the MTU is unchanged, we're done.
16138 			 */
16139 			if (orig_mtu == ill->ill_max_mtu) {
16140 				mutex_exit(&ill->ill_lock);
16141 				break;
16142 			}
16143 
16144 			if (ill->ill_isv6) {
16145 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16146 					ill->ill_max_mtu = IPV6_MIN_MTU;
16147 			} else {
16148 				if (ill->ill_max_mtu < IP_MIN_MTU)
16149 					ill->ill_max_mtu = IP_MIN_MTU;
16150 			}
16151 			for (ipif = ill->ill_ipif; ipif != NULL;
16152 			    ipif = ipif->ipif_next) {
16153 				/*
16154 				 * Don't override the mtu if the user
16155 				 * has explicitly set it.
16156 				 */
16157 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16158 					continue;
16159 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16160 				if (ipif->ipif_isv6)
16161 					ire = ipif_to_ire_v6(ipif);
16162 				else
16163 					ire = ipif_to_ire(ipif);
16164 				if (ire != NULL) {
16165 					ire->ire_max_frag = ipif->ipif_mtu;
16166 					ire_refrele(ire);
16167 				}
16168 				if (ipif->ipif_flags & IPIF_UP) {
16169 					if (ill->ill_isv6)
16170 						need_ire_walk_v6 = B_TRUE;
16171 					else
16172 						need_ire_walk_v4 = B_TRUE;
16173 				}
16174 			}
16175 			mutex_exit(&ill->ill_lock);
16176 			if (need_ire_walk_v4)
16177 				ire_walk_v4(ill_mtu_change, (char *)ill,
16178 				    ALL_ZONES, ipst);
16179 			if (need_ire_walk_v6)
16180 				ire_walk_v6(ill_mtu_change, (char *)ill,
16181 				    ALL_ZONES, ipst);
16182 
16183 			/*
16184 			 * Refresh IPMP meta-interface MTU if necessary.
16185 			 */
16186 			if (IS_UNDER_IPMP(ill))
16187 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16188 			break;
16189 
16190 		case DL_NOTE_LINK_UP:
16191 		case DL_NOTE_LINK_DOWN: {
16192 			/*
16193 			 * We are writer. ill / phyint / ipsq assocs stable.
16194 			 * The RUNNING flag reflects the state of the link.
16195 			 */
16196 			phyint_t *phyint = ill->ill_phyint;
16197 			uint64_t new_phyint_flags;
16198 			boolean_t changed = B_FALSE;
16199 			boolean_t went_up;
16200 
16201 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16202 			mutex_enter(&phyint->phyint_lock);
16203 
16204 			new_phyint_flags = went_up ?
16205 			    phyint->phyint_flags | PHYI_RUNNING :
16206 			    phyint->phyint_flags & ~PHYI_RUNNING;
16207 
16208 			if (IS_IPMP(ill)) {
16209 				new_phyint_flags = went_up ?
16210 				    new_phyint_flags & ~PHYI_FAILED :
16211 				    new_phyint_flags | PHYI_FAILED;
16212 			}
16213 
16214 			if (new_phyint_flags != phyint->phyint_flags) {
16215 				phyint->phyint_flags = new_phyint_flags;
16216 				changed = B_TRUE;
16217 			}
16218 			mutex_exit(&phyint->phyint_lock);
16219 			/*
16220 			 * ill_restart_dad handles the DAD restart and routing
16221 			 * socket notification logic.
16222 			 */
16223 			if (changed) {
16224 				ill_restart_dad(phyint->phyint_illv4, went_up);
16225 				ill_restart_dad(phyint->phyint_illv6, went_up);
16226 			}
16227 			break;
16228 		}
16229 		case DL_NOTE_PROMISC_ON_PHYS: {
16230 			phyint_t *phyint = ill->ill_phyint;
16231 
16232 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16233 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16234 			mutex_enter(&phyint->phyint_lock);
16235 			phyint->phyint_flags |= PHYI_PROMISC;
16236 			mutex_exit(&phyint->phyint_lock);
16237 			break;
16238 		}
16239 		case DL_NOTE_PROMISC_OFF_PHYS: {
16240 			phyint_t *phyint = ill->ill_phyint;
16241 
16242 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16243 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16244 			mutex_enter(&phyint->phyint_lock);
16245 			phyint->phyint_flags &= ~PHYI_PROMISC;
16246 			mutex_exit(&phyint->phyint_lock);
16247 			break;
16248 		}
16249 		case DL_NOTE_CAPAB_RENEG:
16250 			/*
16251 			 * Something changed on the driver side.
16252 			 * It wants us to renegotiate the capabilities
16253 			 * on this ill. One possible cause is the aggregation
16254 			 * interface under us where a port got added or
16255 			 * went away.
16256 			 *
16257 			 * If the capability negotiation is already done
16258 			 * or is in progress, reset the capabilities and
16259 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16260 			 * so that when the ack comes back, we can start
16261 			 * the renegotiation process.
16262 			 *
16263 			 * Note that if ill_capab_reneg is already B_TRUE
16264 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16265 			 * the capability resetting request has been sent
16266 			 * and the renegotiation has not been started yet;
16267 			 * nothing needs to be done in this case.
16268 			 */
16269 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16270 			ill_capability_reset(ill, B_TRUE);
16271 			ipsq_current_finish(ipsq);
16272 			break;
16273 		default:
16274 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16275 			    "type 0x%x for DL_NOTIFY_IND\n",
16276 			    notify->dl_notification));
16277 			break;
16278 		}
16279 
16280 		/*
16281 		 * As this is an asynchronous operation, we
16282 		 * should not call ill_dlpi_done
16283 		 */
16284 		break;
16285 	}
16286 	case DL_NOTIFY_ACK: {
16287 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16288 
16289 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16290 			ill->ill_note_link = 1;
16291 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16292 		break;
16293 	}
16294 	case DL_PHYS_ADDR_ACK: {
16295 		/*
16296 		 * As part of plumbing the interface via SIOCSLIFNAME,
16297 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16298 		 * whose answers we receive here.  As each answer is received,
16299 		 * we call ill_dlpi_done() to dispatch the next request as
16300 		 * we're processing the current one.  Once all answers have
16301 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16302 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16303 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16304 		 * available, but we know the ioctl is pending on ill_wq.)
16305 		 */
16306 		uint_t	paddrlen, paddroff;
16307 		uint8_t	*addr;
16308 
16309 		paddrreq = ill->ill_phys_addr_pend;
16310 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16311 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16312 		addr = mp->b_rptr + paddroff;
16313 
16314 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16315 		if (paddrreq == DL_IPV6_TOKEN) {
16316 			/*
16317 			 * bcopy to low-order bits of ill_token
16318 			 *
16319 			 * XXX Temporary hack - currently, all known tokens
16320 			 * are 64 bits, so I'll cheat for the moment.
16321 			 */
16322 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
16323 			ill->ill_token_length = paddrlen;
16324 			break;
16325 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16326 			ASSERT(ill->ill_nd_lla_mp == NULL);
16327 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16328 			mp = NULL;
16329 			break;
16330 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
16331 			ASSERT(ill->ill_dest_addr_mp == NULL);
16332 			ill->ill_dest_addr_mp = mp;
16333 			ill->ill_dest_addr = addr;
16334 			mp = NULL;
16335 			if (ill->ill_isv6) {
16336 				ill_setdesttoken(ill);
16337 				ipif_setdestlinklocal(ill->ill_ipif);
16338 			}
16339 			break;
16340 		}
16341 
16342 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16343 		ASSERT(ill->ill_phys_addr_mp == NULL);
16344 		if (!ill->ill_ifname_pending)
16345 			break;
16346 		ill->ill_ifname_pending = 0;
16347 		if (!ioctl_aborted)
16348 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16349 		if (mp1 != NULL) {
16350 			ASSERT(connp == NULL);
16351 			q = ill->ill_wq;
16352 		}
16353 		/*
16354 		 * If any error acks received during the plumbing sequence,
16355 		 * ill_ifname_pending_err will be set. Break out and send up
16356 		 * the error to the pending ioctl.
16357 		 */
16358 		if (ill->ill_ifname_pending_err != 0) {
16359 			err = ill->ill_ifname_pending_err;
16360 			ill->ill_ifname_pending_err = 0;
16361 			break;
16362 		}
16363 
16364 		ill->ill_phys_addr_mp = mp;
16365 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
16366 		mp = NULL;
16367 
16368 		/*
16369 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
16370 		 * provider doesn't support physical addresses.  We check both
16371 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
16372 		 * not have physical addresses, but historically adversises a
16373 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
16374 		 * its DL_PHYS_ADDR_ACK.
16375 		 */
16376 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
16377 			ill->ill_phys_addr = NULL;
16378 		} else if (paddrlen != ill->ill_phys_addr_length) {
16379 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16380 			    paddrlen, ill->ill_phys_addr_length));
16381 			err = EINVAL;
16382 			break;
16383 		}
16384 
16385 		if (ill->ill_nd_lla_mp == NULL) {
16386 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16387 				err = ENOMEM;
16388 				break;
16389 			}
16390 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16391 		}
16392 
16393 		if (ill->ill_isv6) {
16394 			ill_setdefaulttoken(ill);
16395 			ipif_setlinklocal(ill->ill_ipif);
16396 		}
16397 		break;
16398 	}
16399 	case DL_OK_ACK:
16400 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16401 		    dl_primstr((int)dloa->dl_correct_primitive),
16402 		    dloa->dl_correct_primitive));
16403 		switch (dloa->dl_correct_primitive) {
16404 		case DL_ENABMULTI_REQ:
16405 		case DL_DISABMULTI_REQ:
16406 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16407 			break;
16408 		case DL_PROMISCON_REQ:
16409 		case DL_PROMISCOFF_REQ:
16410 		case DL_UNBIND_REQ:
16411 		case DL_ATTACH_REQ:
16412 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16413 			break;
16414 		}
16415 		break;
16416 	default:
16417 		break;
16418 	}
16419 
16420 	freemsg(mp);
16421 	if (mp1 == NULL)
16422 		return;
16423 
16424 	/*
16425 	 * The operation must complete without EINPROGRESS since
16426 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16427 	 * the operation will be stuck forever inside the IPSQ.
16428 	 */
16429 	ASSERT(err != EINPROGRESS);
16430 
16431 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16432 	case 0:
16433 		ipsq_current_finish(ipsq);
16434 		break;
16435 
16436 	case SIOCSLIFNAME:
16437 	case IF_UNITSEL: {
16438 		ill_t *ill_other = ILL_OTHER(ill);
16439 
16440 		/*
16441 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16442 		 * ill has a peer which is in an IPMP group, then place ill
16443 		 * into the same group.  One catch: although ifconfig plumbs
16444 		 * the appropriate IPMP meta-interface prior to plumbing this
16445 		 * ill, it is possible for multiple ifconfig applications to
16446 		 * race (or for another application to adjust plumbing), in
16447 		 * which case the IPMP meta-interface we need will be missing.
16448 		 * If so, kick the phyint out of the group.
16449 		 */
16450 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16451 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16452 			ipmp_illgrp_t	*illg;
16453 
16454 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16455 			if (illg == NULL)
16456 				ipmp_phyint_leave_grp(ill->ill_phyint);
16457 			else
16458 				ipmp_ill_join_illgrp(ill, illg);
16459 		}
16460 
16461 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16462 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16463 		else
16464 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16465 		break;
16466 	}
16467 	case SIOCLIFADDIF:
16468 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16469 		break;
16470 
16471 	default:
16472 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16473 		break;
16474 	}
16475 }
16476 
16477 /*
16478  * ip_rput_other is called by ip_rput to handle messages modifying the global
16479  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
16480  */
16481 /* ARGSUSED */
16482 void
16483 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16484 {
16485 	ill_t		*ill = q->q_ptr;
16486 	struct iocblk	*iocp;
16487 
16488 	ip1dbg(("ip_rput_other "));
16489 	if (ipsq != NULL) {
16490 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16491 		ASSERT(ipsq->ipsq_xop ==
16492 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16493 	}
16494 
16495 	switch (mp->b_datap->db_type) {
16496 	case M_ERROR:
16497 	case M_HANGUP:
16498 		/*
16499 		 * The device has a problem.  We force the ILL down.  It can
16500 		 * be brought up again manually using SIOCSIFFLAGS (via
16501 		 * ifconfig or equivalent).
16502 		 */
16503 		ASSERT(ipsq != NULL);
16504 		if (mp->b_rptr < mp->b_wptr)
16505 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16506 		if (ill->ill_error == 0)
16507 			ill->ill_error = ENXIO;
16508 		if (!ill_down_start(q, mp))
16509 			return;
16510 		ipif_all_down_tail(ipsq, q, mp, NULL);
16511 		break;
16512 	case M_IOCNAK: {
16513 		iocp = (struct iocblk *)mp->b_rptr;
16514 
16515 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
16516 		/*
16517 		 * If this was the first attempt, turn off the fastpath
16518 		 * probing.
16519 		 */
16520 		mutex_enter(&ill->ill_lock);
16521 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16522 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
16523 			mutex_exit(&ill->ill_lock);
16524 			ill_fastpath_nack(ill);
16525 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
16526 			    ill->ill_name));
16527 		} else {
16528 			mutex_exit(&ill->ill_lock);
16529 		}
16530 		freemsg(mp);
16531 		break;
16532 	}
16533 	default:
16534 		ASSERT(0);
16535 		break;
16536 	}
16537 }
16538 
16539 /*
16540  * NOTE : This function does not ire_refrele the ire argument passed in.
16541  *
16542  * IPQoS notes
16543  * IP policy is invoked twice for a forwarded packet, once on the read side
16544  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16545  * enabled. An additional parameter, in_ill, has been added for this purpose.
16546  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16547  * because ip_mroute drops this information.
16548  *
16549  */
16550 void
16551 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16552 {
16553 	uint32_t	old_pkt_len;
16554 	uint32_t	pkt_len;
16555 	queue_t	*q;
16556 	uint32_t	sum;
16557 #define	rptr	((uchar_t *)ipha)
16558 	uint32_t	max_frag;
16559 	uint32_t	ill_index;
16560 	ill_t		*out_ill;
16561 	mib2_ipIfStatsEntry_t *mibptr;
16562 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16563 
16564 	/* Get the ill_index of the incoming ILL */
16565 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16566 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16567 
16568 	/* Initiate Read side IPPF processing */
16569 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16570 		ip_process(IPP_FWD_IN, &mp, ill_index);
16571 		if (mp == NULL) {
16572 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16573 			    "during IPPF processing\n"));
16574 			return;
16575 		}
16576 	}
16577 
16578 	/* Adjust the checksum to reflect the ttl decrement. */
16579 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16580 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16581 
16582 	if (ipha->ipha_ttl-- <= 1) {
16583 		if (ip_csum_hdr(ipha)) {
16584 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16585 			goto drop_pkt;
16586 		}
16587 		/*
16588 		 * Note: ire_stq this will be NULL for multicast
16589 		 * datagrams using the long path through arp (the IRE
16590 		 * is not an IRE_CACHE). This should not cause
16591 		 * problems since we don't generate ICMP errors for
16592 		 * multicast packets.
16593 		 */
16594 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16595 		q = ire->ire_stq;
16596 		if (q != NULL) {
16597 			/* Sent by forwarding path, and router is global zone */
16598 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16599 			    GLOBAL_ZONEID, ipst);
16600 		} else
16601 			freemsg(mp);
16602 		return;
16603 	}
16604 
16605 	/*
16606 	 * Don't forward if the interface is down
16607 	 */
16608 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16609 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16610 		ip2dbg(("ip_rput_forward:interface is down\n"));
16611 		goto drop_pkt;
16612 	}
16613 
16614 	/* Get the ill_index of the outgoing ILL */
16615 	out_ill = ire_to_ill(ire);
16616 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16617 
16618 	DTRACE_PROBE4(ip4__forwarding__start,
16619 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16620 
16621 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16622 	    ipst->ips_ipv4firewall_forwarding,
16623 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16624 
16625 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16626 
16627 	if (mp == NULL)
16628 		return;
16629 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16630 
16631 	if (is_system_labeled()) {
16632 		mblk_t *mp1;
16633 
16634 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16635 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16636 			goto drop_pkt;
16637 		}
16638 		/* Size may have changed */
16639 		mp = mp1;
16640 		ipha = (ipha_t *)mp->b_rptr;
16641 		pkt_len = ntohs(ipha->ipha_length);
16642 	}
16643 
16644 	/* Check if there are options to update */
16645 	if (!IS_SIMPLE_IPH(ipha)) {
16646 		if (ip_csum_hdr(ipha)) {
16647 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16648 			goto drop_pkt;
16649 		}
16650 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16651 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16652 			return;
16653 		}
16654 
16655 		ipha->ipha_hdr_checksum = 0;
16656 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16657 	}
16658 	max_frag = ire->ire_max_frag;
16659 	if (pkt_len > max_frag) {
16660 		/*
16661 		 * It needs fragging on its way out.  We haven't
16662 		 * verified the header checksum yet.  Since we
16663 		 * are going to put a surely good checksum in the
16664 		 * outgoing header, we have to make sure that it
16665 		 * was good coming in.
16666 		 */
16667 		if (ip_csum_hdr(ipha)) {
16668 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16669 			goto drop_pkt;
16670 		}
16671 		/* Initiate Write side IPPF processing */
16672 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16673 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16674 			if (mp == NULL) {
16675 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16676 				    " during IPPF processing\n"));
16677 				return;
16678 			}
16679 		}
16680 		/*
16681 		 * Handle labeled packet resizing.
16682 		 *
16683 		 * If we have added a label, inform ip_wput_frag() of its
16684 		 * effect on the MTU for ICMP messages.
16685 		 */
16686 		if (pkt_len > old_pkt_len) {
16687 			uint32_t secopt_size;
16688 
16689 			secopt_size = pkt_len - old_pkt_len;
16690 			if (secopt_size < max_frag)
16691 				max_frag -= secopt_size;
16692 		}
16693 
16694 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16695 		    GLOBAL_ZONEID, ipst, NULL);
16696 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16697 		return;
16698 	}
16699 
16700 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16701 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16702 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16703 	    ipst->ips_ipv4firewall_physical_out,
16704 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16705 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16706 	if (mp == NULL)
16707 		return;
16708 
16709 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16710 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16711 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16712 	/* ip_xmit_v4 always consumes the packet */
16713 	return;
16714 
16715 drop_pkt:;
16716 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16717 	freemsg(mp);
16718 #undef	rptr
16719 }
16720 
16721 void
16722 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16723 {
16724 	ire_t	*ire;
16725 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16726 
16727 	ASSERT(!ipif->ipif_isv6);
16728 	/*
16729 	 * Find an IRE which matches the destination and the outgoing
16730 	 * queue in the cache table. All we need is an IRE_CACHE which
16731 	 * is pointing at ipif->ipif_ill.
16732 	 */
16733 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16734 		dst = ipif->ipif_pp_dst_addr;
16735 
16736 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16737 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16738 	if (ire == NULL) {
16739 		/*
16740 		 * Mark this packet to make it be delivered to
16741 		 * ip_rput_forward after the new ire has been
16742 		 * created.
16743 		 */
16744 		mp->b_prev = NULL;
16745 		mp->b_next = mp;
16746 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16747 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16748 	} else {
16749 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16750 		IRE_REFRELE(ire);
16751 	}
16752 }
16753 
16754 /* Update any source route, record route or timestamp options */
16755 static int
16756 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16757 {
16758 	ipoptp_t	opts;
16759 	uchar_t		*opt;
16760 	uint8_t		optval;
16761 	uint8_t		optlen;
16762 	ipaddr_t	dst;
16763 	uint32_t	ts;
16764 	ire_t		*dst_ire = NULL;
16765 	ire_t		*tmp_ire = NULL;
16766 	timestruc_t	now;
16767 
16768 	ip2dbg(("ip_rput_forward_options\n"));
16769 	dst = ipha->ipha_dst;
16770 	for (optval = ipoptp_first(&opts, ipha);
16771 	    optval != IPOPT_EOL;
16772 	    optval = ipoptp_next(&opts)) {
16773 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16774 		opt = opts.ipoptp_cur;
16775 		optlen = opts.ipoptp_len;
16776 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16777 		    optval, opts.ipoptp_len));
16778 		switch (optval) {
16779 			uint32_t off;
16780 		case IPOPT_SSRR:
16781 		case IPOPT_LSRR:
16782 			/* Check if adminstratively disabled */
16783 			if (!ipst->ips_ip_forward_src_routed) {
16784 				if (ire->ire_stq != NULL) {
16785 					/*
16786 					 * Sent by forwarding path, and router
16787 					 * is global zone
16788 					 */
16789 					icmp_unreachable(ire->ire_stq, mp,
16790 					    ICMP_SOURCE_ROUTE_FAILED,
16791 					    GLOBAL_ZONEID, ipst);
16792 				} else {
16793 					ip0dbg(("ip_rput_forward_options: "
16794 					    "unable to send unreach\n"));
16795 					freemsg(mp);
16796 				}
16797 				return (-1);
16798 			}
16799 
16800 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16801 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16802 			if (dst_ire == NULL) {
16803 				/*
16804 				 * Must be partial since ip_rput_options
16805 				 * checked for strict.
16806 				 */
16807 				break;
16808 			}
16809 			off = opt[IPOPT_OFFSET];
16810 			off--;
16811 		redo_srr:
16812 			if (optlen < IP_ADDR_LEN ||
16813 			    off > optlen - IP_ADDR_LEN) {
16814 				/* End of source route */
16815 				ip1dbg((
16816 				    "ip_rput_forward_options: end of SR\n"));
16817 				ire_refrele(dst_ire);
16818 				break;
16819 			}
16820 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16821 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16822 			    IP_ADDR_LEN);
16823 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16824 			    ntohl(dst)));
16825 
16826 			/*
16827 			 * Check if our address is present more than
16828 			 * once as consecutive hops in source route.
16829 			 */
16830 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16831 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16832 			if (tmp_ire != NULL) {
16833 				ire_refrele(tmp_ire);
16834 				off += IP_ADDR_LEN;
16835 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16836 				goto redo_srr;
16837 			}
16838 			ipha->ipha_dst = dst;
16839 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16840 			ire_refrele(dst_ire);
16841 			break;
16842 		case IPOPT_RR:
16843 			off = opt[IPOPT_OFFSET];
16844 			off--;
16845 			if (optlen < IP_ADDR_LEN ||
16846 			    off > optlen - IP_ADDR_LEN) {
16847 				/* No more room - ignore */
16848 				ip1dbg((
16849 				    "ip_rput_forward_options: end of RR\n"));
16850 				break;
16851 			}
16852 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16853 			    IP_ADDR_LEN);
16854 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16855 			break;
16856 		case IPOPT_TS:
16857 			/* Insert timestamp if there is room */
16858 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16859 			case IPOPT_TS_TSONLY:
16860 				off = IPOPT_TS_TIMELEN;
16861 				break;
16862 			case IPOPT_TS_PRESPEC:
16863 			case IPOPT_TS_PRESPEC_RFC791:
16864 				/* Verify that the address matched */
16865 				off = opt[IPOPT_OFFSET] - 1;
16866 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16867 				dst_ire = ire_ctable_lookup(dst, 0,
16868 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16869 				    MATCH_IRE_TYPE, ipst);
16870 				if (dst_ire == NULL) {
16871 					/* Not for us */
16872 					break;
16873 				}
16874 				ire_refrele(dst_ire);
16875 				/* FALLTHRU */
16876 			case IPOPT_TS_TSANDADDR:
16877 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16878 				break;
16879 			default:
16880 				/*
16881 				 * ip_*put_options should have already
16882 				 * dropped this packet.
16883 				 */
16884 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16885 				    "unknown IT - bug in ip_rput_options?\n");
16886 				return (0);	/* Keep "lint" happy */
16887 			}
16888 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16889 				/* Increase overflow counter */
16890 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16891 				opt[IPOPT_POS_OV_FLG] =
16892 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16893 				    (off << 4));
16894 				break;
16895 			}
16896 			off = opt[IPOPT_OFFSET] - 1;
16897 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16898 			case IPOPT_TS_PRESPEC:
16899 			case IPOPT_TS_PRESPEC_RFC791:
16900 			case IPOPT_TS_TSANDADDR:
16901 				bcopy(&ire->ire_src_addr,
16902 				    (char *)opt + off, IP_ADDR_LEN);
16903 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16904 				/* FALLTHRU */
16905 			case IPOPT_TS_TSONLY:
16906 				off = opt[IPOPT_OFFSET] - 1;
16907 				/* Compute # of milliseconds since midnight */
16908 				gethrestime(&now);
16909 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16910 				    now.tv_nsec / (NANOSEC / MILLISEC);
16911 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16912 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16913 				break;
16914 			}
16915 			break;
16916 		}
16917 	}
16918 	return (0);
16919 }
16920 
16921 /*
16922  * This is called after processing at least one of AH/ESP headers.
16923  *
16924  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16925  * the actual, physical interface on which the packet was received,
16926  * but, when ip_strict_dst_multihoming is set to 1, could be the
16927  * interface which had the ipha_dst configured when the packet went
16928  * through ip_rput. The ill_index corresponding to the recv_ill
16929  * is saved in ipsec_in_rill_index
16930  *
16931  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16932  * cannot assume "ire" points to valid data for any IPv6 cases.
16933  */
16934 void
16935 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16936 {
16937 	mblk_t *mp;
16938 	ipaddr_t dst;
16939 	in6_addr_t *v6dstp;
16940 	ipha_t *ipha;
16941 	ip6_t *ip6h;
16942 	ipsec_in_t *ii;
16943 	boolean_t ill_need_rele = B_FALSE;
16944 	boolean_t rill_need_rele = B_FALSE;
16945 	boolean_t ire_need_rele = B_FALSE;
16946 	netstack_t	*ns;
16947 	ip_stack_t	*ipst;
16948 
16949 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16950 	ASSERT(ii->ipsec_in_ill_index != 0);
16951 	ns = ii->ipsec_in_ns;
16952 	ASSERT(ii->ipsec_in_ns != NULL);
16953 	ipst = ns->netstack_ip;
16954 
16955 	mp = ipsec_mp->b_cont;
16956 	ASSERT(mp != NULL);
16957 
16958 	if (ill == NULL) {
16959 		ASSERT(recv_ill == NULL);
16960 		/*
16961 		 * We need to get the original queue on which ip_rput_local
16962 		 * or ip_rput_data_v6 was called.
16963 		 */
16964 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16965 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16966 		ill_need_rele = B_TRUE;
16967 
16968 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16969 			recv_ill = ill_lookup_on_ifindex(
16970 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16971 			    NULL, NULL, NULL, NULL, ipst);
16972 			rill_need_rele = B_TRUE;
16973 		} else {
16974 			recv_ill = ill;
16975 		}
16976 
16977 		if ((ill == NULL) || (recv_ill == NULL)) {
16978 			ip0dbg(("ip_fanout_proto_again: interface "
16979 			    "disappeared\n"));
16980 			if (ill != NULL)
16981 				ill_refrele(ill);
16982 			if (recv_ill != NULL)
16983 				ill_refrele(recv_ill);
16984 			freemsg(ipsec_mp);
16985 			return;
16986 		}
16987 	}
16988 
16989 	ASSERT(ill != NULL && recv_ill != NULL);
16990 
16991 	if (mp->b_datap->db_type == M_CTL) {
16992 		/*
16993 		 * AH/ESP is returning the ICMP message after
16994 		 * removing their headers. Fanout again till
16995 		 * it gets to the right protocol.
16996 		 */
16997 		if (ii->ipsec_in_v4) {
16998 			icmph_t *icmph;
16999 			int iph_hdr_length;
17000 			int hdr_length;
17001 
17002 			ipha = (ipha_t *)mp->b_rptr;
17003 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17004 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17005 			ipha = (ipha_t *)&icmph[1];
17006 			hdr_length = IPH_HDR_LENGTH(ipha);
17007 			/*
17008 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17009 			 * Reset the type to M_DATA.
17010 			 */
17011 			mp->b_datap->db_type = M_DATA;
17012 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17013 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17014 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17015 		} else {
17016 			icmp6_t *icmp6;
17017 			int hdr_length;
17018 
17019 			ip6h = (ip6_t *)mp->b_rptr;
17020 			/* Don't call hdr_length_v6() unless you have to. */
17021 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17022 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17023 			else
17024 				hdr_length = IPV6_HDR_LEN;
17025 
17026 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17027 			/*
17028 			 * icmp_inbound_error_fanout_v6 may need to do
17029 			 * pullupmsg.  Reset the type to M_DATA.
17030 			 */
17031 			mp->b_datap->db_type = M_DATA;
17032 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17033 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17034 			    ii->ipsec_in_zoneid);
17035 		}
17036 		if (ill_need_rele)
17037 			ill_refrele(ill);
17038 		if (rill_need_rele)
17039 			ill_refrele(recv_ill);
17040 		return;
17041 	}
17042 
17043 	if (ii->ipsec_in_v4) {
17044 		ipha = (ipha_t *)mp->b_rptr;
17045 		dst = ipha->ipha_dst;
17046 		if (CLASSD(dst)) {
17047 			/*
17048 			 * Multicast has to be delivered to all streams.
17049 			 */
17050 			dst = INADDR_BROADCAST;
17051 		}
17052 
17053 		if (ire == NULL) {
17054 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17055 			    msg_getlabel(mp), ipst);
17056 			if (ire == NULL) {
17057 				if (ill_need_rele)
17058 					ill_refrele(ill);
17059 				if (rill_need_rele)
17060 					ill_refrele(recv_ill);
17061 				ip1dbg(("ip_fanout_proto_again: "
17062 				    "IRE not found"));
17063 				freemsg(ipsec_mp);
17064 				return;
17065 			}
17066 			ire_need_rele = B_TRUE;
17067 		}
17068 
17069 		switch (ipha->ipha_protocol) {
17070 		case IPPROTO_UDP:
17071 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17072 			    recv_ill);
17073 			if (ire_need_rele)
17074 				ire_refrele(ire);
17075 			break;
17076 		case IPPROTO_TCP:
17077 			if (!ire_need_rele)
17078 				IRE_REFHOLD(ire);
17079 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17080 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17081 			IRE_REFRELE(ire);
17082 			if (mp != NULL) {
17083 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17084 				    mp, 1, SQ_PROCESS,
17085 				    SQTAG_IP_PROTO_AGAIN);
17086 			}
17087 			break;
17088 		case IPPROTO_SCTP:
17089 			if (!ire_need_rele)
17090 				IRE_REFHOLD(ire);
17091 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17092 			    ipsec_mp, 0, ill->ill_rq, dst);
17093 			break;
17094 		case IPPROTO_ENCAP:
17095 		case IPPROTO_IPV6:
17096 			if (ip_iptun_input(ipsec_mp, mp, ipha, ill, ire,
17097 			    ill->ill_ipst)) {
17098 				/*
17099 				 * If we made it here, we don't need to worry
17100 				 * about the raw-socket/protocol fanout.
17101 				 */
17102 				if (ire_need_rele)
17103 					ire_refrele(ire);
17104 				break;
17105 			}
17106 			/* else FALLTHRU */
17107 		default:
17108 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17109 			    recv_ill, 0);
17110 			if (ire_need_rele)
17111 				ire_refrele(ire);
17112 			break;
17113 		}
17114 	} else {
17115 		uint32_t rput_flags = 0;
17116 
17117 		ip6h = (ip6_t *)mp->b_rptr;
17118 		v6dstp = &ip6h->ip6_dst;
17119 		/*
17120 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17121 		 * address.
17122 		 *
17123 		 * Currently, we don't store that state in the IPSEC_IN
17124 		 * message, and we may need to.
17125 		 */
17126 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17127 		    IP6_IN_LLMCAST : 0);
17128 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17129 		    NULL, NULL);
17130 	}
17131 	if (ill_need_rele)
17132 		ill_refrele(ill);
17133 	if (rill_need_rele)
17134 		ill_refrele(recv_ill);
17135 }
17136 
17137 /*
17138  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17139  * returns 'true' if there are still fragments left on the queue, in
17140  * which case we restart the timer.
17141  */
17142 void
17143 ill_frag_timer(void *arg)
17144 {
17145 	ill_t	*ill = (ill_t *)arg;
17146 	boolean_t frag_pending;
17147 	ip_stack_t	*ipst = ill->ill_ipst;
17148 	time_t	timeout;
17149 
17150 	mutex_enter(&ill->ill_lock);
17151 	ASSERT(!ill->ill_fragtimer_executing);
17152 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17153 		ill->ill_frag_timer_id = 0;
17154 		mutex_exit(&ill->ill_lock);
17155 		return;
17156 	}
17157 	ill->ill_fragtimer_executing = 1;
17158 	mutex_exit(&ill->ill_lock);
17159 
17160 	if (ill->ill_isv6)
17161 		timeout = ipst->ips_ipv6_frag_timeout;
17162 	else
17163 		timeout = ipst->ips_ip_g_frag_timeout;
17164 
17165 	frag_pending = ill_frag_timeout(ill, timeout);
17166 
17167 	/*
17168 	 * Restart the timer, if we have fragments pending or if someone
17169 	 * wanted us to be scheduled again.
17170 	 */
17171 	mutex_enter(&ill->ill_lock);
17172 	ill->ill_fragtimer_executing = 0;
17173 	ill->ill_frag_timer_id = 0;
17174 	if (frag_pending || ill->ill_fragtimer_needrestart)
17175 		ill_frag_timer_start(ill);
17176 	mutex_exit(&ill->ill_lock);
17177 }
17178 
17179 void
17180 ill_frag_timer_start(ill_t *ill)
17181 {
17182 	ip_stack_t	*ipst = ill->ill_ipst;
17183 	clock_t	timeo_ms;
17184 
17185 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17186 
17187 	/* If the ill is closing or opening don't proceed */
17188 	if (ill->ill_state_flags & ILL_CONDEMNED)
17189 		return;
17190 
17191 	if (ill->ill_fragtimer_executing) {
17192 		/*
17193 		 * ill_frag_timer is currently executing. Just record the
17194 		 * the fact that we want the timer to be restarted.
17195 		 * ill_frag_timer will post a timeout before it returns,
17196 		 * ensuring it will be called again.
17197 		 */
17198 		ill->ill_fragtimer_needrestart = 1;
17199 		return;
17200 	}
17201 
17202 	if (ill->ill_frag_timer_id == 0) {
17203 		if (ill->ill_isv6)
17204 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17205 		else
17206 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17207 		/*
17208 		 * The timer is neither running nor is the timeout handler
17209 		 * executing. Post a timeout so that ill_frag_timer will be
17210 		 * called
17211 		 */
17212 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17213 		    MSEC_TO_TICK(timeo_ms >> 1));
17214 		ill->ill_fragtimer_needrestart = 0;
17215 	}
17216 }
17217 
17218 /*
17219  * This routine is needed for loopback when forwarding multicasts.
17220  *
17221  * IPQoS Notes:
17222  * IPPF processing is done in fanout routines.
17223  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17224  * processing for IPsec packets is done when it comes back in clear.
17225  * NOTE : The callers of this function need to do the ire_refrele for the
17226  *	  ire that is being passed in.
17227  */
17228 void
17229 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17230     ill_t *recv_ill, uint32_t esp_udp_ports)
17231 {
17232 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17233 	ill_t	*ill = (ill_t *)q->q_ptr;
17234 	uint32_t	sum;
17235 	uint32_t	u1;
17236 	uint32_t	u2;
17237 	int		hdr_length;
17238 	boolean_t	mctl_present;
17239 	mblk_t		*first_mp = mp;
17240 	mblk_t		*hada_mp = NULL;
17241 	ipha_t		*inner_ipha;
17242 	ip_stack_t	*ipst;
17243 
17244 	ASSERT(recv_ill != NULL);
17245 	ipst = recv_ill->ill_ipst;
17246 
17247 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17248 	    "ip_rput_locl_start: q %p", q);
17249 
17250 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17251 	ASSERT(ill != NULL);
17252 
17253 #define	rptr	((uchar_t *)ipha)
17254 #define	iphs	((uint16_t *)ipha)
17255 
17256 	/*
17257 	 * no UDP or TCP packet should come here anymore.
17258 	 */
17259 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17260 	    ipha->ipha_protocol != IPPROTO_UDP);
17261 
17262 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17263 	if (mctl_present &&
17264 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17265 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17266 
17267 		/*
17268 		 * It's an IPsec accelerated packet.
17269 		 * Keep a pointer to the data attributes around until
17270 		 * we allocate the ipsec_info_t.
17271 		 */
17272 		IPSECHW_DEBUG(IPSECHW_PKT,
17273 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17274 		hada_mp = first_mp;
17275 		hada_mp->b_cont = NULL;
17276 		/*
17277 		 * Since it is accelerated, it comes directly from
17278 		 * the ill and the data attributes is followed by
17279 		 * the packet data.
17280 		 */
17281 		ASSERT(mp->b_datap->db_type != M_CTL);
17282 		first_mp = mp;
17283 		mctl_present = B_FALSE;
17284 	}
17285 
17286 	/*
17287 	 * IF M_CTL is not present, then ipsec_in_is_secure
17288 	 * should return B_TRUE. There is a case where loopback
17289 	 * packets has an M_CTL in the front with all the
17290 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17291 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17292 	 * packets never comes here, it is safe to ASSERT the
17293 	 * following.
17294 	 */
17295 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17296 
17297 	/*
17298 	 * Also, we should never have an mctl_present if this is an
17299 	 * ESP-in-UDP packet.
17300 	 */
17301 	ASSERT(!mctl_present || !esp_in_udp_packet);
17302 
17303 	/* u1 is # words of IP options */
17304 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17305 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17306 
17307 	/*
17308 	 * Don't verify header checksum if we just removed UDP header or
17309 	 * packet is coming back from AH/ESP.
17310 	 */
17311 	if (!esp_in_udp_packet && !mctl_present) {
17312 		if (u1) {
17313 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17314 				if (hada_mp != NULL)
17315 					freemsg(hada_mp);
17316 				return;
17317 			}
17318 		} else {
17319 			/* Check the IP header checksum.  */
17320 #define	uph	((uint16_t *)ipha)
17321 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17322 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17323 #undef  uph
17324 			/* finish doing IP checksum */
17325 			sum = (sum & 0xFFFF) + (sum >> 16);
17326 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17327 			if (sum && sum != 0xFFFF) {
17328 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17329 				goto drop_pkt;
17330 			}
17331 		}
17332 	}
17333 
17334 	/*
17335 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17336 	 * might be called more than once for secure packets, count only
17337 	 * the first time.
17338 	 */
17339 	if (!mctl_present) {
17340 		UPDATE_IB_PKT_COUNT(ire);
17341 		ire->ire_last_used_time = lbolt;
17342 	}
17343 
17344 	/* Check for fragmentation offset. */
17345 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17346 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17347 	if (u1) {
17348 		/*
17349 		 * We re-assemble fragments before we do the AH/ESP
17350 		 * processing. Thus, M_CTL should not be present
17351 		 * while we are re-assembling.
17352 		 */
17353 		ASSERT(!mctl_present);
17354 		ASSERT(first_mp == mp);
17355 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17356 			return;
17357 
17358 		/*
17359 		 * Make sure that first_mp points back to mp as
17360 		 * the mp we came in with could have changed in
17361 		 * ip_rput_fragment().
17362 		 */
17363 		ipha = (ipha_t *)mp->b_rptr;
17364 		first_mp = mp;
17365 	}
17366 
17367 	/*
17368 	 * Clear hardware checksumming flag as it is currently only
17369 	 * used by TCP and UDP.
17370 	 */
17371 	DB_CKSUMFLAGS(mp) = 0;
17372 
17373 	/* Now we have a complete datagram, destined for this machine. */
17374 	u1 = IPH_HDR_LENGTH(ipha);
17375 	switch (ipha->ipha_protocol) {
17376 	case IPPROTO_ICMP: {
17377 		ire_t		*ire_zone;
17378 		ilm_t		*ilm;
17379 		mblk_t		*mp1;
17380 		zoneid_t	last_zoneid;
17381 		ilm_walker_t	ilw;
17382 
17383 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17384 			ASSERT(ire->ire_type == IRE_BROADCAST);
17385 
17386 			/*
17387 			 * In the multicast case, applications may have joined
17388 			 * the group from different zones, so we need to deliver
17389 			 * the packet to each of them. Loop through the
17390 			 * multicast memberships structures (ilm) on the receive
17391 			 * ill and send a copy of the packet up each matching
17392 			 * one. However, we don't do this for multicasts sent on
17393 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17394 			 * they must stay in the sender's zone.
17395 			 *
17396 			 * ilm_add_v6() ensures that ilms in the same zone are
17397 			 * contiguous in the ill_ilm list. We use this property
17398 			 * to avoid sending duplicates needed when two
17399 			 * applications in the same zone join the same group on
17400 			 * different logical interfaces: we ignore the ilm if
17401 			 * its zoneid is the same as the last matching one.
17402 			 * In addition, the sending of the packet for
17403 			 * ire_zoneid is delayed until all of the other ilms
17404 			 * have been exhausted.
17405 			 */
17406 			last_zoneid = -1;
17407 			ilm = ilm_walker_start(&ilw, recv_ill);
17408 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17409 				if (ipha->ipha_dst != ilm->ilm_addr ||
17410 				    ilm->ilm_zoneid == last_zoneid ||
17411 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17412 				    ilm->ilm_zoneid == ALL_ZONES ||
17413 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17414 					continue;
17415 				mp1 = ip_copymsg(first_mp);
17416 				if (mp1 == NULL)
17417 					continue;
17418 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17419 				    0, sum, mctl_present, B_TRUE,
17420 				    recv_ill, ilm->ilm_zoneid);
17421 				last_zoneid = ilm->ilm_zoneid;
17422 			}
17423 			ilm_walker_finish(&ilw);
17424 		} else if (ire->ire_type == IRE_BROADCAST) {
17425 			/*
17426 			 * In the broadcast case, there may be many zones
17427 			 * which need a copy of the packet delivered to them.
17428 			 * There is one IRE_BROADCAST per broadcast address
17429 			 * and per zone; we walk those using a helper function.
17430 			 * In addition, the sending of the packet for ire is
17431 			 * delayed until all of the other ires have been
17432 			 * processed.
17433 			 */
17434 			IRB_REFHOLD(ire->ire_bucket);
17435 			ire_zone = NULL;
17436 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17437 			    ire)) != NULL) {
17438 				mp1 = ip_copymsg(first_mp);
17439 				if (mp1 == NULL)
17440 					continue;
17441 
17442 				UPDATE_IB_PKT_COUNT(ire_zone);
17443 				ire_zone->ire_last_used_time = lbolt;
17444 				icmp_inbound(q, mp1, B_TRUE, ill,
17445 				    0, sum, mctl_present, B_TRUE,
17446 				    recv_ill, ire_zone->ire_zoneid);
17447 			}
17448 			IRB_REFRELE(ire->ire_bucket);
17449 		}
17450 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17451 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17452 		    ire->ire_zoneid);
17453 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17454 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17455 		return;
17456 	}
17457 	case IPPROTO_IGMP:
17458 		/*
17459 		 * If we are not willing to accept IGMP packets in clear,
17460 		 * then check with global policy.
17461 		 */
17462 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17463 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17464 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17465 			if (first_mp == NULL)
17466 				return;
17467 		}
17468 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17469 			freemsg(first_mp);
17470 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17471 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17472 			return;
17473 		}
17474 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17475 			/* Bad packet - discarded by igmp_input */
17476 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17477 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17478 			if (mctl_present)
17479 				freeb(first_mp);
17480 			return;
17481 		}
17482 		/*
17483 		 * igmp_input() may have returned the pulled up message.
17484 		 * So first_mp and ipha need to be reinitialized.
17485 		 */
17486 		ipha = (ipha_t *)mp->b_rptr;
17487 		if (mctl_present)
17488 			first_mp->b_cont = mp;
17489 		else
17490 			first_mp = mp;
17491 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17492 		    connf_head != NULL) {
17493 			/* No user-level listener for IGMP packets */
17494 			goto drop_pkt;
17495 		}
17496 		/* deliver to local raw users */
17497 		break;
17498 	case IPPROTO_PIM:
17499 		/*
17500 		 * If we are not willing to accept PIM packets in clear,
17501 		 * then check with global policy.
17502 		 */
17503 		if (ipst->ips_pim_accept_clear_messages == 0) {
17504 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17505 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17506 			if (first_mp == NULL)
17507 				return;
17508 		}
17509 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17510 			freemsg(first_mp);
17511 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17512 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17513 			return;
17514 		}
17515 		if (pim_input(q, mp, ill) != 0) {
17516 			/* Bad packet - discarded by pim_input */
17517 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17518 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17519 			if (mctl_present)
17520 				freeb(first_mp);
17521 			return;
17522 		}
17523 
17524 		/*
17525 		 * pim_input() may have pulled up the message so ipha needs to
17526 		 * be reinitialized.
17527 		 */
17528 		ipha = (ipha_t *)mp->b_rptr;
17529 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17530 		    connf_head != NULL) {
17531 			/* No user-level listener for PIM packets */
17532 			goto drop_pkt;
17533 		}
17534 		/* deliver to local raw users */
17535 		break;
17536 	case IPPROTO_ENCAP:
17537 		/*
17538 		 * Handle self-encapsulated packets (IP-in-IP where
17539 		 * the inner addresses == the outer addresses).
17540 		 */
17541 		hdr_length = IPH_HDR_LENGTH(ipha);
17542 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17543 		    mp->b_wptr) {
17544 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17545 			    sizeof (ipha_t) - mp->b_rptr)) {
17546 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17547 				freemsg(first_mp);
17548 				return;
17549 			}
17550 			ipha = (ipha_t *)mp->b_rptr;
17551 		}
17552 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17553 		/*
17554 		 * Check the sanity of the inner IP header.
17555 		 */
17556 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17557 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17558 			freemsg(first_mp);
17559 			return;
17560 		}
17561 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17562 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17563 			freemsg(first_mp);
17564 			return;
17565 		}
17566 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17567 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17568 			ipsec_in_t *ii;
17569 
17570 			/*
17571 			 * Self-encapsulated tunnel packet. Remove
17572 			 * the outer IP header and fanout again.
17573 			 * We also need to make sure that the inner
17574 			 * header is pulled up until options.
17575 			 */
17576 			mp->b_rptr = (uchar_t *)inner_ipha;
17577 			ipha = inner_ipha;
17578 			hdr_length = IPH_HDR_LENGTH(ipha);
17579 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17580 				if (!pullupmsg(mp, (uchar_t *)ipha +
17581 				    + hdr_length - mp->b_rptr)) {
17582 					freemsg(first_mp);
17583 					return;
17584 				}
17585 				ipha = (ipha_t *)mp->b_rptr;
17586 			}
17587 			if (hdr_length > sizeof (ipha_t)) {
17588 				/* We got options on the inner packet. */
17589 				ipaddr_t dst = ipha->ipha_dst;
17590 
17591 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17592 				    -1) {
17593 					/* Bad options! */
17594 					return;
17595 				}
17596 				if (dst != ipha->ipha_dst) {
17597 					/*
17598 					 * Someone put a source-route in
17599 					 * the inside header of a self-
17600 					 * encapsulated packet.  Drop it
17601 					 * with extreme prejudice and let
17602 					 * the sender know.
17603 					 */
17604 					icmp_unreachable(q, first_mp,
17605 					    ICMP_SOURCE_ROUTE_FAILED,
17606 					    recv_ill->ill_zoneid, ipst);
17607 					return;
17608 				}
17609 			}
17610 			if (!mctl_present) {
17611 				ASSERT(first_mp == mp);
17612 				/*
17613 				 * This means that somebody is sending
17614 				 * Self-encapsualted packets without AH/ESP.
17615 				 * If AH/ESP was present, we would have already
17616 				 * allocated the first_mp.
17617 				 *
17618 				 * Send this packet to find a tunnel endpoint.
17619 				 * if I can't find one, an ICMP
17620 				 * PROTOCOL_UNREACHABLE will get sent.
17621 				 */
17622 				goto fanout;
17623 			}
17624 			/*
17625 			 * We generally store the ill_index if we need to
17626 			 * do IPsec processing as we lose the ill queue when
17627 			 * we come back. But in this case, we never should
17628 			 * have to store the ill_index here as it should have
17629 			 * been stored previously when we processed the
17630 			 * AH/ESP header in this routine or for non-ipsec
17631 			 * cases, we still have the queue. But for some bad
17632 			 * packets from the wire, we can get to IPsec after
17633 			 * this and we better store the index for that case.
17634 			 */
17635 			ill = (ill_t *)q->q_ptr;
17636 			ii = (ipsec_in_t *)first_mp->b_rptr;
17637 			ii->ipsec_in_ill_index =
17638 			    ill->ill_phyint->phyint_ifindex;
17639 			ii->ipsec_in_rill_index =
17640 			    recv_ill->ill_phyint->phyint_ifindex;
17641 			if (ii->ipsec_in_decaps) {
17642 				/*
17643 				 * This packet is self-encapsulated multiple
17644 				 * times. We don't want to recurse infinitely.
17645 				 * To keep it simple, drop the packet.
17646 				 */
17647 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17648 				freemsg(first_mp);
17649 				return;
17650 			}
17651 			ii->ipsec_in_decaps = B_TRUE;
17652 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17653 			    ire);
17654 			return;
17655 		}
17656 		break;
17657 	case IPPROTO_AH:
17658 	case IPPROTO_ESP: {
17659 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17660 
17661 		/*
17662 		 * Fast path for AH/ESP. If this is the first time
17663 		 * we are sending a datagram to AH/ESP, allocate
17664 		 * a IPSEC_IN message and prepend it. Otherwise,
17665 		 * just fanout.
17666 		 */
17667 
17668 		int ipsec_rc;
17669 		ipsec_in_t *ii;
17670 		netstack_t *ns = ipst->ips_netstack;
17671 
17672 		IP_STAT(ipst, ipsec_proto_ahesp);
17673 		if (!mctl_present) {
17674 			ASSERT(first_mp == mp);
17675 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17676 			if (first_mp == NULL) {
17677 				ip1dbg(("ip_proto_input: IPSEC_IN "
17678 				    "allocation failure.\n"));
17679 				freemsg(hada_mp); /* okay ifnull */
17680 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17681 				freemsg(mp);
17682 				return;
17683 			}
17684 			/*
17685 			 * Store the ill_index so that when we come back
17686 			 * from IPsec we ride on the same queue.
17687 			 */
17688 			ill = (ill_t *)q->q_ptr;
17689 			ii = (ipsec_in_t *)first_mp->b_rptr;
17690 			ii->ipsec_in_ill_index =
17691 			    ill->ill_phyint->phyint_ifindex;
17692 			ii->ipsec_in_rill_index =
17693 			    recv_ill->ill_phyint->phyint_ifindex;
17694 			first_mp->b_cont = mp;
17695 			/*
17696 			 * Cache hardware acceleration info.
17697 			 */
17698 			if (hada_mp != NULL) {
17699 				IPSECHW_DEBUG(IPSECHW_PKT,
17700 				    ("ip_rput_local: caching data attr.\n"));
17701 				ii->ipsec_in_accelerated = B_TRUE;
17702 				ii->ipsec_in_da = hada_mp;
17703 				hada_mp = NULL;
17704 			}
17705 		} else {
17706 			ii = (ipsec_in_t *)first_mp->b_rptr;
17707 		}
17708 
17709 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17710 
17711 		if (!ipsec_loaded(ipss)) {
17712 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17713 			    ire->ire_zoneid, ipst);
17714 			return;
17715 		}
17716 
17717 		ns = ipst->ips_netstack;
17718 		/* select inbound SA and have IPsec process the pkt */
17719 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17720 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17721 			boolean_t esp_in_udp_sa;
17722 			if (esph == NULL)
17723 				return;
17724 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17725 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17726 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17727 			    IPSA_F_NATT) != 0);
17728 			/*
17729 			 * The following is a fancy, but quick, way of saying:
17730 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17731 			 *    OR
17732 			 * ESP SA and ESP-in-UDP packet --> drop
17733 			 */
17734 			if (esp_in_udp_sa != esp_in_udp_packet) {
17735 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17736 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17737 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17738 				    &ns->netstack_ipsec->ipsec_dropper);
17739 				return;
17740 			}
17741 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17742 			    first_mp, esph);
17743 		} else {
17744 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17745 			if (ah == NULL)
17746 				return;
17747 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17748 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17749 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17750 			    first_mp, ah);
17751 		}
17752 
17753 		switch (ipsec_rc) {
17754 		case IPSEC_STATUS_SUCCESS:
17755 			break;
17756 		case IPSEC_STATUS_FAILED:
17757 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17758 			/* FALLTHRU */
17759 		case IPSEC_STATUS_PENDING:
17760 			return;
17761 		}
17762 		/* we're done with IPsec processing, send it up */
17763 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17764 		return;
17765 	}
17766 	default:
17767 		break;
17768 	}
17769 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17770 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17771 		    ire->ire_zoneid));
17772 		goto drop_pkt;
17773 	}
17774 	/*
17775 	 * Handle protocols with which IP is less intimate.  There
17776 	 * can be more than one stream bound to a particular
17777 	 * protocol.  When this is the case, each one gets a copy
17778 	 * of any incoming packets.
17779 	 */
17780 fanout:
17781 	ip_fanout_proto(q, first_mp, ill, ipha,
17782 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17783 	    B_TRUE, recv_ill, ire->ire_zoneid);
17784 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17785 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17786 	return;
17787 
17788 drop_pkt:
17789 	freemsg(first_mp);
17790 	if (hada_mp != NULL)
17791 		freeb(hada_mp);
17792 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17793 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17794 #undef	rptr
17795 #undef  iphs
17796 
17797 }
17798 
17799 /*
17800  * Update any source route, record route or timestamp options.
17801  * Check that we are at end of strict source route.
17802  * The options have already been checked for sanity in ip_rput_options().
17803  */
17804 static boolean_t
17805 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17806     ip_stack_t *ipst)
17807 {
17808 	ipoptp_t	opts;
17809 	uchar_t		*opt;
17810 	uint8_t		optval;
17811 	uint8_t		optlen;
17812 	ipaddr_t	dst;
17813 	uint32_t	ts;
17814 	ire_t		*dst_ire;
17815 	timestruc_t	now;
17816 	zoneid_t	zoneid;
17817 	ill_t		*ill;
17818 
17819 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17820 
17821 	ip2dbg(("ip_rput_local_options\n"));
17822 
17823 	for (optval = ipoptp_first(&opts, ipha);
17824 	    optval != IPOPT_EOL;
17825 	    optval = ipoptp_next(&opts)) {
17826 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17827 		opt = opts.ipoptp_cur;
17828 		optlen = opts.ipoptp_len;
17829 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17830 		    optval, optlen));
17831 		switch (optval) {
17832 			uint32_t off;
17833 		case IPOPT_SSRR:
17834 		case IPOPT_LSRR:
17835 			off = opt[IPOPT_OFFSET];
17836 			off--;
17837 			if (optlen < IP_ADDR_LEN ||
17838 			    off > optlen - IP_ADDR_LEN) {
17839 				/* End of source route */
17840 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17841 				break;
17842 			}
17843 			/*
17844 			 * This will only happen if two consecutive entries
17845 			 * in the source route contains our address or if
17846 			 * it is a packet with a loose source route which
17847 			 * reaches us before consuming the whole source route
17848 			 */
17849 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17850 			if (optval == IPOPT_SSRR) {
17851 				goto bad_src_route;
17852 			}
17853 			/*
17854 			 * Hack: instead of dropping the packet truncate the
17855 			 * source route to what has been used by filling the
17856 			 * rest with IPOPT_NOP.
17857 			 */
17858 			opt[IPOPT_OLEN] = (uint8_t)off;
17859 			while (off < optlen) {
17860 				opt[off++] = IPOPT_NOP;
17861 			}
17862 			break;
17863 		case IPOPT_RR:
17864 			off = opt[IPOPT_OFFSET];
17865 			off--;
17866 			if (optlen < IP_ADDR_LEN ||
17867 			    off > optlen - IP_ADDR_LEN) {
17868 				/* No more room - ignore */
17869 				ip1dbg((
17870 				    "ip_rput_local_options: end of RR\n"));
17871 				break;
17872 			}
17873 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17874 			    IP_ADDR_LEN);
17875 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17876 			break;
17877 		case IPOPT_TS:
17878 			/* Insert timestamp if there is romm */
17879 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17880 			case IPOPT_TS_TSONLY:
17881 				off = IPOPT_TS_TIMELEN;
17882 				break;
17883 			case IPOPT_TS_PRESPEC:
17884 			case IPOPT_TS_PRESPEC_RFC791:
17885 				/* Verify that the address matched */
17886 				off = opt[IPOPT_OFFSET] - 1;
17887 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17888 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17889 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17890 				    ipst);
17891 				if (dst_ire == NULL) {
17892 					/* Not for us */
17893 					break;
17894 				}
17895 				ire_refrele(dst_ire);
17896 				/* FALLTHRU */
17897 			case IPOPT_TS_TSANDADDR:
17898 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17899 				break;
17900 			default:
17901 				/*
17902 				 * ip_*put_options should have already
17903 				 * dropped this packet.
17904 				 */
17905 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17906 				    "unknown IT - bug in ip_rput_options?\n");
17907 				return (B_TRUE);	/* Keep "lint" happy */
17908 			}
17909 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17910 				/* Increase overflow counter */
17911 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17912 				opt[IPOPT_POS_OV_FLG] =
17913 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17914 				    (off << 4));
17915 				break;
17916 			}
17917 			off = opt[IPOPT_OFFSET] - 1;
17918 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17919 			case IPOPT_TS_PRESPEC:
17920 			case IPOPT_TS_PRESPEC_RFC791:
17921 			case IPOPT_TS_TSANDADDR:
17922 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17923 				    IP_ADDR_LEN);
17924 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17925 				/* FALLTHRU */
17926 			case IPOPT_TS_TSONLY:
17927 				off = opt[IPOPT_OFFSET] - 1;
17928 				/* Compute # of milliseconds since midnight */
17929 				gethrestime(&now);
17930 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17931 				    now.tv_nsec / (NANOSEC / MILLISEC);
17932 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17933 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17934 				break;
17935 			}
17936 			break;
17937 		}
17938 	}
17939 	return (B_TRUE);
17940 
17941 bad_src_route:
17942 	q = WR(q);
17943 	if (q->q_next != NULL)
17944 		ill = q->q_ptr;
17945 	else
17946 		ill = NULL;
17947 
17948 	/* make sure we clear any indication of a hardware checksum */
17949 	DB_CKSUMFLAGS(mp) = 0;
17950 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17951 	if (zoneid == ALL_ZONES)
17952 		freemsg(mp);
17953 	else
17954 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17955 	return (B_FALSE);
17956 
17957 }
17958 
17959 /*
17960  * Process IP options in an inbound packet.  If an option affects the
17961  * effective destination address, return the next hop address via dstp.
17962  * Returns -1 if something fails in which case an ICMP error has been sent
17963  * and mp freed.
17964  */
17965 static int
17966 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17967     ip_stack_t *ipst)
17968 {
17969 	ipoptp_t	opts;
17970 	uchar_t		*opt;
17971 	uint8_t		optval;
17972 	uint8_t		optlen;
17973 	ipaddr_t	dst;
17974 	intptr_t	code = 0;
17975 	ire_t		*ire = NULL;
17976 	zoneid_t	zoneid;
17977 	ill_t		*ill;
17978 
17979 	ip2dbg(("ip_rput_options\n"));
17980 	dst = ipha->ipha_dst;
17981 	for (optval = ipoptp_first(&opts, ipha);
17982 	    optval != IPOPT_EOL;
17983 	    optval = ipoptp_next(&opts)) {
17984 		opt = opts.ipoptp_cur;
17985 		optlen = opts.ipoptp_len;
17986 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17987 		    optval, optlen));
17988 		/*
17989 		 * Note: we need to verify the checksum before we
17990 		 * modify anything thus this routine only extracts the next
17991 		 * hop dst from any source route.
17992 		 */
17993 		switch (optval) {
17994 			uint32_t off;
17995 		case IPOPT_SSRR:
17996 		case IPOPT_LSRR:
17997 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17998 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17999 			if (ire == NULL) {
18000 				if (optval == IPOPT_SSRR) {
18001 					ip1dbg(("ip_rput_options: not next"
18002 					    " strict source route 0x%x\n",
18003 					    ntohl(dst)));
18004 					code = (char *)&ipha->ipha_dst -
18005 					    (char *)ipha;
18006 					goto param_prob; /* RouterReq's */
18007 				}
18008 				ip2dbg(("ip_rput_options: "
18009 				    "not next source route 0x%x\n",
18010 				    ntohl(dst)));
18011 				break;
18012 			}
18013 			ire_refrele(ire);
18014 
18015 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18016 				ip1dbg((
18017 				    "ip_rput_options: bad option offset\n"));
18018 				code = (char *)&opt[IPOPT_OLEN] -
18019 				    (char *)ipha;
18020 				goto param_prob;
18021 			}
18022 			off = opt[IPOPT_OFFSET];
18023 			off--;
18024 		redo_srr:
18025 			if (optlen < IP_ADDR_LEN ||
18026 			    off > optlen - IP_ADDR_LEN) {
18027 				/* End of source route */
18028 				ip1dbg(("ip_rput_options: end of SR\n"));
18029 				break;
18030 			}
18031 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18032 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18033 			    ntohl(dst)));
18034 
18035 			/*
18036 			 * Check if our address is present more than
18037 			 * once as consecutive hops in source route.
18038 			 * XXX verify per-interface ip_forwarding
18039 			 * for source route?
18040 			 */
18041 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18042 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18043 
18044 			if (ire != NULL) {
18045 				ire_refrele(ire);
18046 				off += IP_ADDR_LEN;
18047 				goto redo_srr;
18048 			}
18049 
18050 			if (dst == htonl(INADDR_LOOPBACK)) {
18051 				ip1dbg(("ip_rput_options: loopback addr in "
18052 				    "source route!\n"));
18053 				goto bad_src_route;
18054 			}
18055 			/*
18056 			 * For strict: verify that dst is directly
18057 			 * reachable.
18058 			 */
18059 			if (optval == IPOPT_SSRR) {
18060 				ire = ire_ftable_lookup(dst, 0, 0,
18061 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18062 				    msg_getlabel(mp),
18063 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18064 				if (ire == NULL) {
18065 					ip1dbg(("ip_rput_options: SSRR not "
18066 					    "directly reachable: 0x%x\n",
18067 					    ntohl(dst)));
18068 					goto bad_src_route;
18069 				}
18070 				ire_refrele(ire);
18071 			}
18072 			/*
18073 			 * Defer update of the offset and the record route
18074 			 * until the packet is forwarded.
18075 			 */
18076 			break;
18077 		case IPOPT_RR:
18078 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18079 				ip1dbg((
18080 				    "ip_rput_options: bad option offset\n"));
18081 				code = (char *)&opt[IPOPT_OLEN] -
18082 				    (char *)ipha;
18083 				goto param_prob;
18084 			}
18085 			break;
18086 		case IPOPT_TS:
18087 			/*
18088 			 * Verify that length >= 5 and that there is either
18089 			 * room for another timestamp or that the overflow
18090 			 * counter is not maxed out.
18091 			 */
18092 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18093 			if (optlen < IPOPT_MINLEN_IT) {
18094 				goto param_prob;
18095 			}
18096 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18097 				ip1dbg((
18098 				    "ip_rput_options: bad option offset\n"));
18099 				code = (char *)&opt[IPOPT_OFFSET] -
18100 				    (char *)ipha;
18101 				goto param_prob;
18102 			}
18103 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18104 			case IPOPT_TS_TSONLY:
18105 				off = IPOPT_TS_TIMELEN;
18106 				break;
18107 			case IPOPT_TS_TSANDADDR:
18108 			case IPOPT_TS_PRESPEC:
18109 			case IPOPT_TS_PRESPEC_RFC791:
18110 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18111 				break;
18112 			default:
18113 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18114 				    (char *)ipha;
18115 				goto param_prob;
18116 			}
18117 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18118 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18119 				/*
18120 				 * No room and the overflow counter is 15
18121 				 * already.
18122 				 */
18123 				goto param_prob;
18124 			}
18125 			break;
18126 		}
18127 	}
18128 
18129 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18130 		*dstp = dst;
18131 		return (0);
18132 	}
18133 
18134 	ip1dbg(("ip_rput_options: error processing IP options."));
18135 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18136 
18137 param_prob:
18138 	q = WR(q);
18139 	if (q->q_next != NULL)
18140 		ill = q->q_ptr;
18141 	else
18142 		ill = NULL;
18143 
18144 	/* make sure we clear any indication of a hardware checksum */
18145 	DB_CKSUMFLAGS(mp) = 0;
18146 	/* Don't know whether this is for non-global or global/forwarding */
18147 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18148 	if (zoneid == ALL_ZONES)
18149 		freemsg(mp);
18150 	else
18151 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18152 	return (-1);
18153 
18154 bad_src_route:
18155 	q = WR(q);
18156 	if (q->q_next != NULL)
18157 		ill = q->q_ptr;
18158 	else
18159 		ill = NULL;
18160 
18161 	/* make sure we clear any indication of a hardware checksum */
18162 	DB_CKSUMFLAGS(mp) = 0;
18163 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18164 	if (zoneid == ALL_ZONES)
18165 		freemsg(mp);
18166 	else
18167 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18168 	return (-1);
18169 }
18170 
18171 /*
18172  * IP & ICMP info in >=14 msg's ...
18173  *  - ip fixed part (mib2_ip_t)
18174  *  - icmp fixed part (mib2_icmp_t)
18175  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18176  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18177  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18178  *  - ipRouteAttributeTable (ip 102)	labeled routes
18179  *  - ip multicast membership (ip_member_t)
18180  *  - ip multicast source filtering (ip_grpsrc_t)
18181  *  - igmp fixed part (struct igmpstat)
18182  *  - multicast routing stats (struct mrtstat)
18183  *  - multicast routing vifs (array of struct vifctl)
18184  *  - multicast routing routes (array of struct mfcctl)
18185  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18186  *					One per ill plus one generic
18187  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18188  *					One per ill plus one generic
18189  *  - ipv6RouteEntry			all IPv6 IREs
18190  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18191  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18192  *  - ipv6AddrEntry			all IPv6 ipifs
18193  *  - ipv6 multicast membership (ipv6_member_t)
18194  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18195  *
18196  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18197  *
18198  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18199  * already filled in by the caller.
18200  * Return value of 0 indicates that no messages were sent and caller
18201  * should free mpctl.
18202  */
18203 int
18204 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18205 {
18206 	ip_stack_t *ipst;
18207 	sctp_stack_t *sctps;
18208 
18209 	if (q->q_next != NULL) {
18210 		ipst = ILLQ_TO_IPST(q);
18211 	} else {
18212 		ipst = CONNQ_TO_IPST(q);
18213 	}
18214 	ASSERT(ipst != NULL);
18215 	sctps = ipst->ips_netstack->netstack_sctp;
18216 
18217 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18218 		return (0);
18219 	}
18220 
18221 	/*
18222 	 * For the purposes of the (broken) packet shell use
18223 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18224 	 * to make TCP and UDP appear first in the list of mib items.
18225 	 * TBD: We could expand this and use it in netstat so that
18226 	 * the kernel doesn't have to produce large tables (connections,
18227 	 * routes, etc) when netstat only wants the statistics or a particular
18228 	 * table.
18229 	 */
18230 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18231 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18232 			return (1);
18233 		}
18234 	}
18235 
18236 	if (level != MIB2_TCP) {
18237 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18238 			return (1);
18239 		}
18240 	}
18241 
18242 	if (level != MIB2_UDP) {
18243 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18244 			return (1);
18245 		}
18246 	}
18247 
18248 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18249 	    ipst)) == NULL) {
18250 		return (1);
18251 	}
18252 
18253 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18254 		return (1);
18255 	}
18256 
18257 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18258 		return (1);
18259 	}
18260 
18261 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18262 		return (1);
18263 	}
18264 
18265 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18266 		return (1);
18267 	}
18268 
18269 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18270 		return (1);
18271 	}
18272 
18273 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18274 		return (1);
18275 	}
18276 
18277 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18278 		return (1);
18279 	}
18280 
18281 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18282 		return (1);
18283 	}
18284 
18285 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18286 		return (1);
18287 	}
18288 
18289 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18290 		return (1);
18291 	}
18292 
18293 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18294 		return (1);
18295 	}
18296 
18297 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18298 		return (1);
18299 	}
18300 
18301 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18302 		return (1);
18303 	}
18304 
18305 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18306 	if (mpctl == NULL)
18307 		return (1);
18308 
18309 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18310 	if (mpctl == NULL)
18311 		return (1);
18312 
18313 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18314 		return (1);
18315 	}
18316 	freemsg(mpctl);
18317 	return (1);
18318 }
18319 
18320 /* Get global (legacy) IPv4 statistics */
18321 static mblk_t *
18322 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18323     ip_stack_t *ipst)
18324 {
18325 	mib2_ip_t		old_ip_mib;
18326 	struct opthdr		*optp;
18327 	mblk_t			*mp2ctl;
18328 
18329 	/*
18330 	 * make a copy of the original message
18331 	 */
18332 	mp2ctl = copymsg(mpctl);
18333 
18334 	/* fixed length IP structure... */
18335 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18336 	optp->level = MIB2_IP;
18337 	optp->name = 0;
18338 	SET_MIB(old_ip_mib.ipForwarding,
18339 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18340 	SET_MIB(old_ip_mib.ipDefaultTTL,
18341 	    (uint32_t)ipst->ips_ip_def_ttl);
18342 	SET_MIB(old_ip_mib.ipReasmTimeout,
18343 	    ipst->ips_ip_g_frag_timeout);
18344 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18345 	    sizeof (mib2_ipAddrEntry_t));
18346 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18347 	    sizeof (mib2_ipRouteEntry_t));
18348 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18349 	    sizeof (mib2_ipNetToMediaEntry_t));
18350 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18351 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18352 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18353 	    sizeof (mib2_ipAttributeEntry_t));
18354 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18355 
18356 	/*
18357 	 * Grab the statistics from the new IP MIB
18358 	 */
18359 	SET_MIB(old_ip_mib.ipInReceives,
18360 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18361 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18362 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18363 	SET_MIB(old_ip_mib.ipForwDatagrams,
18364 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18365 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18366 	    ipmib->ipIfStatsInUnknownProtos);
18367 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18368 	SET_MIB(old_ip_mib.ipInDelivers,
18369 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18370 	SET_MIB(old_ip_mib.ipOutRequests,
18371 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18372 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18373 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18374 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18375 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18376 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18377 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18378 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18379 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18380 
18381 	/* ipRoutingDiscards is not being used */
18382 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18383 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18384 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18385 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18386 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18387 	    ipmib->ipIfStatsReasmDuplicates);
18388 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18389 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18390 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18391 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18392 	SET_MIB(old_ip_mib.rawipInOverflows,
18393 	    ipmib->rawipIfStatsInOverflows);
18394 
18395 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18396 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18397 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18398 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18399 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18400 	    ipmib->ipIfStatsOutSwitchIPVersion);
18401 
18402 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18403 	    (int)sizeof (old_ip_mib))) {
18404 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18405 		    (uint_t)sizeof (old_ip_mib)));
18406 	}
18407 
18408 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18409 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18410 	    (int)optp->level, (int)optp->name, (int)optp->len));
18411 	qreply(q, mpctl);
18412 	return (mp2ctl);
18413 }
18414 
18415 /* Per interface IPv4 statistics */
18416 static mblk_t *
18417 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18418 {
18419 	struct opthdr		*optp;
18420 	mblk_t			*mp2ctl;
18421 	ill_t			*ill;
18422 	ill_walk_context_t	ctx;
18423 	mblk_t			*mp_tail = NULL;
18424 	mib2_ipIfStatsEntry_t	global_ip_mib;
18425 
18426 	/*
18427 	 * Make a copy of the original message
18428 	 */
18429 	mp2ctl = copymsg(mpctl);
18430 
18431 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18432 	optp->level = MIB2_IP;
18433 	optp->name = MIB2_IP_TRAFFIC_STATS;
18434 	/* Include "unknown interface" ip_mib */
18435 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18436 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18437 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18438 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18439 	    (ipst->ips_ip_g_forward ? 1 : 2));
18440 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18441 	    (uint32_t)ipst->ips_ip_def_ttl);
18442 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18443 	    sizeof (mib2_ipIfStatsEntry_t));
18444 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18445 	    sizeof (mib2_ipAddrEntry_t));
18446 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18447 	    sizeof (mib2_ipRouteEntry_t));
18448 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18449 	    sizeof (mib2_ipNetToMediaEntry_t));
18450 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18451 	    sizeof (ip_member_t));
18452 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18453 	    sizeof (ip_grpsrc_t));
18454 
18455 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18456 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18457 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18458 		    "failed to allocate %u bytes\n",
18459 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18460 	}
18461 
18462 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18463 
18464 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18465 	ill = ILL_START_WALK_V4(&ctx, ipst);
18466 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18467 		ill->ill_ip_mib->ipIfStatsIfIndex =
18468 		    ill->ill_phyint->phyint_ifindex;
18469 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18470 		    (ipst->ips_ip_g_forward ? 1 : 2));
18471 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18472 		    (uint32_t)ipst->ips_ip_def_ttl);
18473 
18474 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18475 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18476 		    (char *)ill->ill_ip_mib,
18477 		    (int)sizeof (*ill->ill_ip_mib))) {
18478 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18479 			    "failed to allocate %u bytes\n",
18480 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18481 		}
18482 	}
18483 	rw_exit(&ipst->ips_ill_g_lock);
18484 
18485 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18486 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18487 	    "level %d, name %d, len %d\n",
18488 	    (int)optp->level, (int)optp->name, (int)optp->len));
18489 	qreply(q, mpctl);
18490 
18491 	if (mp2ctl == NULL)
18492 		return (NULL);
18493 
18494 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18495 }
18496 
18497 /* Global IPv4 ICMP statistics */
18498 static mblk_t *
18499 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18500 {
18501 	struct opthdr		*optp;
18502 	mblk_t			*mp2ctl;
18503 
18504 	/*
18505 	 * Make a copy of the original message
18506 	 */
18507 	mp2ctl = copymsg(mpctl);
18508 
18509 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18510 	optp->level = MIB2_ICMP;
18511 	optp->name = 0;
18512 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18513 	    (int)sizeof (ipst->ips_icmp_mib))) {
18514 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18515 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18516 	}
18517 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18518 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18519 	    (int)optp->level, (int)optp->name, (int)optp->len));
18520 	qreply(q, mpctl);
18521 	return (mp2ctl);
18522 }
18523 
18524 /* Global IPv4 IGMP statistics */
18525 static mblk_t *
18526 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18527 {
18528 	struct opthdr		*optp;
18529 	mblk_t			*mp2ctl;
18530 
18531 	/*
18532 	 * make a copy of the original message
18533 	 */
18534 	mp2ctl = copymsg(mpctl);
18535 
18536 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18537 	optp->level = EXPER_IGMP;
18538 	optp->name = 0;
18539 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18540 	    (int)sizeof (ipst->ips_igmpstat))) {
18541 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18542 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18543 	}
18544 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18545 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18546 	    (int)optp->level, (int)optp->name, (int)optp->len));
18547 	qreply(q, mpctl);
18548 	return (mp2ctl);
18549 }
18550 
18551 /* Global IPv4 Multicast Routing statistics */
18552 static mblk_t *
18553 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18554 {
18555 	struct opthdr		*optp;
18556 	mblk_t			*mp2ctl;
18557 
18558 	/*
18559 	 * make a copy of the original message
18560 	 */
18561 	mp2ctl = copymsg(mpctl);
18562 
18563 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18564 	optp->level = EXPER_DVMRP;
18565 	optp->name = 0;
18566 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18567 		ip0dbg(("ip_mroute_stats: failed\n"));
18568 	}
18569 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18570 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18571 	    (int)optp->level, (int)optp->name, (int)optp->len));
18572 	qreply(q, mpctl);
18573 	return (mp2ctl);
18574 }
18575 
18576 /* IPv4 address information */
18577 static mblk_t *
18578 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18579 {
18580 	struct opthdr		*optp;
18581 	mblk_t			*mp2ctl;
18582 	mblk_t			*mp_tail = NULL;
18583 	ill_t			*ill;
18584 	ipif_t			*ipif;
18585 	uint_t			bitval;
18586 	mib2_ipAddrEntry_t	mae;
18587 	zoneid_t		zoneid;
18588 	ill_walk_context_t ctx;
18589 
18590 	/*
18591 	 * make a copy of the original message
18592 	 */
18593 	mp2ctl = copymsg(mpctl);
18594 
18595 	/* ipAddrEntryTable */
18596 
18597 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18598 	optp->level = MIB2_IP;
18599 	optp->name = MIB2_IP_ADDR;
18600 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18601 
18602 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18603 	ill = ILL_START_WALK_V4(&ctx, ipst);
18604 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18605 		for (ipif = ill->ill_ipif; ipif != NULL;
18606 		    ipif = ipif->ipif_next) {
18607 			if (ipif->ipif_zoneid != zoneid &&
18608 			    ipif->ipif_zoneid != ALL_ZONES)
18609 				continue;
18610 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18611 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18612 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18613 
18614 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18615 			    OCTET_LENGTH);
18616 			mae.ipAdEntIfIndex.o_length =
18617 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18618 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18619 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18620 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18621 			mae.ipAdEntInfo.ae_subnet_len =
18622 			    ip_mask_to_plen(ipif->ipif_net_mask);
18623 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18624 			for (bitval = 1;
18625 			    bitval &&
18626 			    !(bitval & ipif->ipif_brd_addr);
18627 			    bitval <<= 1)
18628 				noop;
18629 			mae.ipAdEntBcastAddr = bitval;
18630 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18631 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18632 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18633 			mae.ipAdEntInfo.ae_broadcast_addr =
18634 			    ipif->ipif_brd_addr;
18635 			mae.ipAdEntInfo.ae_pp_dst_addr =
18636 			    ipif->ipif_pp_dst_addr;
18637 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18638 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18639 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18640 
18641 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18642 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18643 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18644 				    "allocate %u bytes\n",
18645 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18646 			}
18647 		}
18648 	}
18649 	rw_exit(&ipst->ips_ill_g_lock);
18650 
18651 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18652 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18653 	    (int)optp->level, (int)optp->name, (int)optp->len));
18654 	qreply(q, mpctl);
18655 	return (mp2ctl);
18656 }
18657 
18658 /* IPv6 address information */
18659 static mblk_t *
18660 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18661 {
18662 	struct opthdr		*optp;
18663 	mblk_t			*mp2ctl;
18664 	mblk_t			*mp_tail = NULL;
18665 	ill_t			*ill;
18666 	ipif_t			*ipif;
18667 	mib2_ipv6AddrEntry_t	mae6;
18668 	zoneid_t		zoneid;
18669 	ill_walk_context_t	ctx;
18670 
18671 	/*
18672 	 * make a copy of the original message
18673 	 */
18674 	mp2ctl = copymsg(mpctl);
18675 
18676 	/* ipv6AddrEntryTable */
18677 
18678 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18679 	optp->level = MIB2_IP6;
18680 	optp->name = MIB2_IP6_ADDR;
18681 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18682 
18683 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18684 	ill = ILL_START_WALK_V6(&ctx, ipst);
18685 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18686 		for (ipif = ill->ill_ipif; ipif != NULL;
18687 		    ipif = ipif->ipif_next) {
18688 			if (ipif->ipif_zoneid != zoneid &&
18689 			    ipif->ipif_zoneid != ALL_ZONES)
18690 				continue;
18691 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18692 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18693 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18694 
18695 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18696 			    OCTET_LENGTH);
18697 			mae6.ipv6AddrIfIndex.o_length =
18698 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18699 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18700 			mae6.ipv6AddrPfxLength =
18701 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18702 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18703 			mae6.ipv6AddrInfo.ae_subnet_len =
18704 			    mae6.ipv6AddrPfxLength;
18705 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18706 
18707 			/* Type: stateless(1), stateful(2), unknown(3) */
18708 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18709 				mae6.ipv6AddrType = 1;
18710 			else
18711 				mae6.ipv6AddrType = 2;
18712 			/* Anycast: true(1), false(2) */
18713 			if (ipif->ipif_flags & IPIF_ANYCAST)
18714 				mae6.ipv6AddrAnycastFlag = 1;
18715 			else
18716 				mae6.ipv6AddrAnycastFlag = 2;
18717 
18718 			/*
18719 			 * Address status: preferred(1), deprecated(2),
18720 			 * invalid(3), inaccessible(4), unknown(5)
18721 			 */
18722 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18723 				mae6.ipv6AddrStatus = 3;
18724 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18725 				mae6.ipv6AddrStatus = 2;
18726 			else
18727 				mae6.ipv6AddrStatus = 1;
18728 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18729 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18730 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18731 			    ipif->ipif_v6pp_dst_addr;
18732 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18733 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18734 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18735 			mae6.ipv6AddrIdentifier = ill->ill_token;
18736 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18737 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18738 			mae6.ipv6AddrRetransmitTime =
18739 			    ill->ill_reachable_retrans_time;
18740 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18741 			    (char *)&mae6,
18742 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18743 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18744 				    "allocate %u bytes\n",
18745 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18746 			}
18747 		}
18748 	}
18749 	rw_exit(&ipst->ips_ill_g_lock);
18750 
18751 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18752 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18753 	    (int)optp->level, (int)optp->name, (int)optp->len));
18754 	qreply(q, mpctl);
18755 	return (mp2ctl);
18756 }
18757 
18758 /* IPv4 multicast group membership. */
18759 static mblk_t *
18760 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18761 {
18762 	struct opthdr		*optp;
18763 	mblk_t			*mp2ctl;
18764 	ill_t			*ill;
18765 	ipif_t			*ipif;
18766 	ilm_t			*ilm;
18767 	ip_member_t		ipm;
18768 	mblk_t			*mp_tail = NULL;
18769 	ill_walk_context_t	ctx;
18770 	zoneid_t		zoneid;
18771 	ilm_walker_t		ilw;
18772 
18773 	/*
18774 	 * make a copy of the original message
18775 	 */
18776 	mp2ctl = copymsg(mpctl);
18777 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18778 
18779 	/* ipGroupMember table */
18780 	optp = (struct opthdr *)&mpctl->b_rptr[
18781 	    sizeof (struct T_optmgmt_ack)];
18782 	optp->level = MIB2_IP;
18783 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18784 
18785 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18786 	ill = ILL_START_WALK_V4(&ctx, ipst);
18787 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18788 		if (IS_UNDER_IPMP(ill))
18789 			continue;
18790 
18791 		ilm = ilm_walker_start(&ilw, ill);
18792 		for (ipif = ill->ill_ipif; ipif != NULL;
18793 		    ipif = ipif->ipif_next) {
18794 			if (ipif->ipif_zoneid != zoneid &&
18795 			    ipif->ipif_zoneid != ALL_ZONES)
18796 				continue;	/* not this zone */
18797 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18798 			    OCTET_LENGTH);
18799 			ipm.ipGroupMemberIfIndex.o_length =
18800 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18801 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18802 				ASSERT(ilm->ilm_ipif != NULL);
18803 				ASSERT(ilm->ilm_ill == NULL);
18804 				if (ilm->ilm_ipif != ipif)
18805 					continue;
18806 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18807 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18808 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18809 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18810 				    (char *)&ipm, (int)sizeof (ipm))) {
18811 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18812 					    "failed to allocate %u bytes\n",
18813 					    (uint_t)sizeof (ipm)));
18814 				}
18815 			}
18816 		}
18817 		ilm_walker_finish(&ilw);
18818 	}
18819 	rw_exit(&ipst->ips_ill_g_lock);
18820 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18821 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18822 	    (int)optp->level, (int)optp->name, (int)optp->len));
18823 	qreply(q, mpctl);
18824 	return (mp2ctl);
18825 }
18826 
18827 /* IPv6 multicast group membership. */
18828 static mblk_t *
18829 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18830 {
18831 	struct opthdr		*optp;
18832 	mblk_t			*mp2ctl;
18833 	ill_t			*ill;
18834 	ilm_t			*ilm;
18835 	ipv6_member_t		ipm6;
18836 	mblk_t			*mp_tail = NULL;
18837 	ill_walk_context_t	ctx;
18838 	zoneid_t		zoneid;
18839 	ilm_walker_t		ilw;
18840 
18841 	/*
18842 	 * make a copy of the original message
18843 	 */
18844 	mp2ctl = copymsg(mpctl);
18845 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18846 
18847 	/* ip6GroupMember table */
18848 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18849 	optp->level = MIB2_IP6;
18850 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18851 
18852 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18853 	ill = ILL_START_WALK_V6(&ctx, ipst);
18854 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18855 		if (IS_UNDER_IPMP(ill))
18856 			continue;
18857 
18858 		ilm = ilm_walker_start(&ilw, ill);
18859 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18860 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18861 			ASSERT(ilm->ilm_ipif == NULL);
18862 			ASSERT(ilm->ilm_ill != NULL);
18863 			if (ilm->ilm_zoneid != zoneid)
18864 				continue;	/* not this zone */
18865 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18866 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18867 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18868 			if (!snmp_append_data2(mpctl->b_cont,
18869 			    &mp_tail,
18870 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18871 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18872 				    "failed to allocate %u bytes\n",
18873 				    (uint_t)sizeof (ipm6)));
18874 			}
18875 		}
18876 		ilm_walker_finish(&ilw);
18877 	}
18878 	rw_exit(&ipst->ips_ill_g_lock);
18879 
18880 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18881 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18882 	    (int)optp->level, (int)optp->name, (int)optp->len));
18883 	qreply(q, mpctl);
18884 	return (mp2ctl);
18885 }
18886 
18887 /* IP multicast filtered sources */
18888 static mblk_t *
18889 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18890 {
18891 	struct opthdr		*optp;
18892 	mblk_t			*mp2ctl;
18893 	ill_t			*ill;
18894 	ipif_t			*ipif;
18895 	ilm_t			*ilm;
18896 	ip_grpsrc_t		ips;
18897 	mblk_t			*mp_tail = NULL;
18898 	ill_walk_context_t	ctx;
18899 	zoneid_t		zoneid;
18900 	int			i;
18901 	slist_t			*sl;
18902 	ilm_walker_t		ilw;
18903 
18904 	/*
18905 	 * make a copy of the original message
18906 	 */
18907 	mp2ctl = copymsg(mpctl);
18908 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18909 
18910 	/* ipGroupSource table */
18911 	optp = (struct opthdr *)&mpctl->b_rptr[
18912 	    sizeof (struct T_optmgmt_ack)];
18913 	optp->level = MIB2_IP;
18914 	optp->name = EXPER_IP_GROUP_SOURCES;
18915 
18916 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18917 	ill = ILL_START_WALK_V4(&ctx, ipst);
18918 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18919 		if (IS_UNDER_IPMP(ill))
18920 			continue;
18921 
18922 		ilm = ilm_walker_start(&ilw, ill);
18923 		for (ipif = ill->ill_ipif; ipif != NULL;
18924 		    ipif = ipif->ipif_next) {
18925 			if (ipif->ipif_zoneid != zoneid)
18926 				continue;	/* not this zone */
18927 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18928 			    OCTET_LENGTH);
18929 			ips.ipGroupSourceIfIndex.o_length =
18930 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18931 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18932 				ASSERT(ilm->ilm_ipif != NULL);
18933 				ASSERT(ilm->ilm_ill == NULL);
18934 				sl = ilm->ilm_filter;
18935 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18936 					continue;
18937 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18938 				for (i = 0; i < sl->sl_numsrc; i++) {
18939 					if (!IN6_IS_ADDR_V4MAPPED(
18940 					    &sl->sl_addr[i]))
18941 						continue;
18942 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18943 					    ips.ipGroupSourceAddress);
18944 					if (snmp_append_data2(mpctl->b_cont,
18945 					    &mp_tail, (char *)&ips,
18946 					    (int)sizeof (ips)) == 0) {
18947 						ip1dbg(("ip_snmp_get_mib2_"
18948 						    "ip_group_src: failed to "
18949 						    "allocate %u bytes\n",
18950 						    (uint_t)sizeof (ips)));
18951 					}
18952 				}
18953 			}
18954 		}
18955 		ilm_walker_finish(&ilw);
18956 	}
18957 	rw_exit(&ipst->ips_ill_g_lock);
18958 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18959 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18960 	    (int)optp->level, (int)optp->name, (int)optp->len));
18961 	qreply(q, mpctl);
18962 	return (mp2ctl);
18963 }
18964 
18965 /* IPv6 multicast filtered sources. */
18966 static mblk_t *
18967 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18968 {
18969 	struct opthdr		*optp;
18970 	mblk_t			*mp2ctl;
18971 	ill_t			*ill;
18972 	ilm_t			*ilm;
18973 	ipv6_grpsrc_t		ips6;
18974 	mblk_t			*mp_tail = NULL;
18975 	ill_walk_context_t	ctx;
18976 	zoneid_t		zoneid;
18977 	int			i;
18978 	slist_t			*sl;
18979 	ilm_walker_t		ilw;
18980 
18981 	/*
18982 	 * make a copy of the original message
18983 	 */
18984 	mp2ctl = copymsg(mpctl);
18985 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18986 
18987 	/* ip6GroupMember table */
18988 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18989 	optp->level = MIB2_IP6;
18990 	optp->name = EXPER_IP6_GROUP_SOURCES;
18991 
18992 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18993 	ill = ILL_START_WALK_V6(&ctx, ipst);
18994 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18995 		if (IS_UNDER_IPMP(ill))
18996 			continue;
18997 
18998 		ilm = ilm_walker_start(&ilw, ill);
18999 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19000 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19001 			ASSERT(ilm->ilm_ipif == NULL);
19002 			ASSERT(ilm->ilm_ill != NULL);
19003 			sl = ilm->ilm_filter;
19004 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19005 				continue;
19006 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19007 			for (i = 0; i < sl->sl_numsrc; i++) {
19008 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19009 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19010 				    (char *)&ips6, (int)sizeof (ips6))) {
19011 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19012 					    "group_src: failed to allocate "
19013 					    "%u bytes\n",
19014 					    (uint_t)sizeof (ips6)));
19015 				}
19016 			}
19017 		}
19018 		ilm_walker_finish(&ilw);
19019 	}
19020 	rw_exit(&ipst->ips_ill_g_lock);
19021 
19022 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19023 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19024 	    (int)optp->level, (int)optp->name, (int)optp->len));
19025 	qreply(q, mpctl);
19026 	return (mp2ctl);
19027 }
19028 
19029 /* Multicast routing virtual interface table. */
19030 static mblk_t *
19031 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19032 {
19033 	struct opthdr		*optp;
19034 	mblk_t			*mp2ctl;
19035 
19036 	/*
19037 	 * make a copy of the original message
19038 	 */
19039 	mp2ctl = copymsg(mpctl);
19040 
19041 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19042 	optp->level = EXPER_DVMRP;
19043 	optp->name = EXPER_DVMRP_VIF;
19044 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19045 		ip0dbg(("ip_mroute_vif: failed\n"));
19046 	}
19047 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19048 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19049 	    (int)optp->level, (int)optp->name, (int)optp->len));
19050 	qreply(q, mpctl);
19051 	return (mp2ctl);
19052 }
19053 
19054 /* Multicast routing table. */
19055 static mblk_t *
19056 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19057 {
19058 	struct opthdr		*optp;
19059 	mblk_t			*mp2ctl;
19060 
19061 	/*
19062 	 * make a copy of the original message
19063 	 */
19064 	mp2ctl = copymsg(mpctl);
19065 
19066 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19067 	optp->level = EXPER_DVMRP;
19068 	optp->name = EXPER_DVMRP_MRT;
19069 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19070 		ip0dbg(("ip_mroute_mrt: failed\n"));
19071 	}
19072 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19073 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19074 	    (int)optp->level, (int)optp->name, (int)optp->len));
19075 	qreply(q, mpctl);
19076 	return (mp2ctl);
19077 }
19078 
19079 /*
19080  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19081  * in one IRE walk.
19082  */
19083 static mblk_t *
19084 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19085     ip_stack_t *ipst)
19086 {
19087 	struct opthdr	*optp;
19088 	mblk_t		*mp2ctl;	/* Returned */
19089 	mblk_t		*mp3ctl;	/* nettomedia */
19090 	mblk_t		*mp4ctl;	/* routeattrs */
19091 	iproutedata_t	ird;
19092 	zoneid_t	zoneid;
19093 
19094 	/*
19095 	 * make copies of the original message
19096 	 *	- mp2ctl is returned unchanged to the caller for his use
19097 	 *	- mpctl is sent upstream as ipRouteEntryTable
19098 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19099 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19100 	 */
19101 	mp2ctl = copymsg(mpctl);
19102 	mp3ctl = copymsg(mpctl);
19103 	mp4ctl = copymsg(mpctl);
19104 	if (mp3ctl == NULL || mp4ctl == NULL) {
19105 		freemsg(mp4ctl);
19106 		freemsg(mp3ctl);
19107 		freemsg(mp2ctl);
19108 		freemsg(mpctl);
19109 		return (NULL);
19110 	}
19111 
19112 	bzero(&ird, sizeof (ird));
19113 
19114 	ird.ird_route.lp_head = mpctl->b_cont;
19115 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19116 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19117 	/*
19118 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19119 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19120 	 * intended a temporary solution until a proper MIB API is provided
19121 	 * that provides complete filtering/caller-opt-in.
19122 	 */
19123 	if (level == EXPER_IP_AND_TESTHIDDEN)
19124 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19125 
19126 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19127 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19128 
19129 	/* ipRouteEntryTable in mpctl */
19130 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19131 	optp->level = MIB2_IP;
19132 	optp->name = MIB2_IP_ROUTE;
19133 	optp->len = msgdsize(ird.ird_route.lp_head);
19134 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19135 	    (int)optp->level, (int)optp->name, (int)optp->len));
19136 	qreply(q, mpctl);
19137 
19138 	/* ipNetToMediaEntryTable in mp3ctl */
19139 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19140 	optp->level = MIB2_IP;
19141 	optp->name = MIB2_IP_MEDIA;
19142 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19143 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19144 	    (int)optp->level, (int)optp->name, (int)optp->len));
19145 	qreply(q, mp3ctl);
19146 
19147 	/* ipRouteAttributeTable in mp4ctl */
19148 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19149 	optp->level = MIB2_IP;
19150 	optp->name = EXPER_IP_RTATTR;
19151 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19152 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19153 	    (int)optp->level, (int)optp->name, (int)optp->len));
19154 	if (optp->len == 0)
19155 		freemsg(mp4ctl);
19156 	else
19157 		qreply(q, mp4ctl);
19158 
19159 	return (mp2ctl);
19160 }
19161 
19162 /*
19163  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19164  * ipv6NetToMediaEntryTable in an NDP walk.
19165  */
19166 static mblk_t *
19167 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19168     ip_stack_t *ipst)
19169 {
19170 	struct opthdr	*optp;
19171 	mblk_t		*mp2ctl;	/* Returned */
19172 	mblk_t		*mp3ctl;	/* nettomedia */
19173 	mblk_t		*mp4ctl;	/* routeattrs */
19174 	iproutedata_t	ird;
19175 	zoneid_t	zoneid;
19176 
19177 	/*
19178 	 * make copies of the original message
19179 	 *	- mp2ctl is returned unchanged to the caller for his use
19180 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19181 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19182 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19183 	 */
19184 	mp2ctl = copymsg(mpctl);
19185 	mp3ctl = copymsg(mpctl);
19186 	mp4ctl = copymsg(mpctl);
19187 	if (mp3ctl == NULL || mp4ctl == NULL) {
19188 		freemsg(mp4ctl);
19189 		freemsg(mp3ctl);
19190 		freemsg(mp2ctl);
19191 		freemsg(mpctl);
19192 		return (NULL);
19193 	}
19194 
19195 	bzero(&ird, sizeof (ird));
19196 
19197 	ird.ird_route.lp_head = mpctl->b_cont;
19198 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19199 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19200 	/*
19201 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19202 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19203 	 * intended a temporary solution until a proper MIB API is provided
19204 	 * that provides complete filtering/caller-opt-in.
19205 	 */
19206 	if (level == EXPER_IP_AND_TESTHIDDEN)
19207 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19208 
19209 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19210 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19211 
19212 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19213 	optp->level = MIB2_IP6;
19214 	optp->name = MIB2_IP6_ROUTE;
19215 	optp->len = msgdsize(ird.ird_route.lp_head);
19216 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19217 	    (int)optp->level, (int)optp->name, (int)optp->len));
19218 	qreply(q, mpctl);
19219 
19220 	/* ipv6NetToMediaEntryTable in mp3ctl */
19221 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19222 
19223 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19224 	optp->level = MIB2_IP6;
19225 	optp->name = MIB2_IP6_MEDIA;
19226 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19227 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19228 	    (int)optp->level, (int)optp->name, (int)optp->len));
19229 	qreply(q, mp3ctl);
19230 
19231 	/* ipv6RouteAttributeTable in mp4ctl */
19232 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19233 	optp->level = MIB2_IP6;
19234 	optp->name = EXPER_IP_RTATTR;
19235 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19236 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19237 	    (int)optp->level, (int)optp->name, (int)optp->len));
19238 	if (optp->len == 0)
19239 		freemsg(mp4ctl);
19240 	else
19241 		qreply(q, mp4ctl);
19242 
19243 	return (mp2ctl);
19244 }
19245 
19246 /*
19247  * IPv6 mib: One per ill
19248  */
19249 static mblk_t *
19250 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19251 {
19252 	struct opthdr		*optp;
19253 	mblk_t			*mp2ctl;
19254 	ill_t			*ill;
19255 	ill_walk_context_t	ctx;
19256 	mblk_t			*mp_tail = NULL;
19257 
19258 	/*
19259 	 * Make a copy of the original message
19260 	 */
19261 	mp2ctl = copymsg(mpctl);
19262 
19263 	/* fixed length IPv6 structure ... */
19264 
19265 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19266 	optp->level = MIB2_IP6;
19267 	optp->name = 0;
19268 	/* Include "unknown interface" ip6_mib */
19269 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19270 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19271 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19272 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19273 	    ipst->ips_ipv6_forward ? 1 : 2);
19274 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19275 	    ipst->ips_ipv6_def_hops);
19276 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19277 	    sizeof (mib2_ipIfStatsEntry_t));
19278 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19279 	    sizeof (mib2_ipv6AddrEntry_t));
19280 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19281 	    sizeof (mib2_ipv6RouteEntry_t));
19282 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19283 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19284 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19285 	    sizeof (ipv6_member_t));
19286 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19287 	    sizeof (ipv6_grpsrc_t));
19288 
19289 	/*
19290 	 * Synchronize 64- and 32-bit counters
19291 	 */
19292 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19293 	    ipIfStatsHCInReceives);
19294 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19295 	    ipIfStatsHCInDelivers);
19296 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19297 	    ipIfStatsHCOutRequests);
19298 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19299 	    ipIfStatsHCOutForwDatagrams);
19300 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19301 	    ipIfStatsHCOutMcastPkts);
19302 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19303 	    ipIfStatsHCInMcastPkts);
19304 
19305 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19306 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19307 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19308 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19309 	}
19310 
19311 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19312 	ill = ILL_START_WALK_V6(&ctx, ipst);
19313 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19314 		ill->ill_ip_mib->ipIfStatsIfIndex =
19315 		    ill->ill_phyint->phyint_ifindex;
19316 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19317 		    ipst->ips_ipv6_forward ? 1 : 2);
19318 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19319 		    ill->ill_max_hops);
19320 
19321 		/*
19322 		 * Synchronize 64- and 32-bit counters
19323 		 */
19324 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19325 		    ipIfStatsHCInReceives);
19326 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19327 		    ipIfStatsHCInDelivers);
19328 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19329 		    ipIfStatsHCOutRequests);
19330 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19331 		    ipIfStatsHCOutForwDatagrams);
19332 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19333 		    ipIfStatsHCOutMcastPkts);
19334 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19335 		    ipIfStatsHCInMcastPkts);
19336 
19337 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19338 		    (char *)ill->ill_ip_mib,
19339 		    (int)sizeof (*ill->ill_ip_mib))) {
19340 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19341 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19342 		}
19343 	}
19344 	rw_exit(&ipst->ips_ill_g_lock);
19345 
19346 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19347 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19348 	    (int)optp->level, (int)optp->name, (int)optp->len));
19349 	qreply(q, mpctl);
19350 	return (mp2ctl);
19351 }
19352 
19353 /*
19354  * ICMPv6 mib: One per ill
19355  */
19356 static mblk_t *
19357 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19358 {
19359 	struct opthdr		*optp;
19360 	mblk_t			*mp2ctl;
19361 	ill_t			*ill;
19362 	ill_walk_context_t	ctx;
19363 	mblk_t			*mp_tail = NULL;
19364 	/*
19365 	 * Make a copy of the original message
19366 	 */
19367 	mp2ctl = copymsg(mpctl);
19368 
19369 	/* fixed length ICMPv6 structure ... */
19370 
19371 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19372 	optp->level = MIB2_ICMP6;
19373 	optp->name = 0;
19374 	/* Include "unknown interface" icmp6_mib */
19375 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19376 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19377 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19378 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19379 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19380 	    (char *)&ipst->ips_icmp6_mib,
19381 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19382 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19383 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19384 	}
19385 
19386 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19387 	ill = ILL_START_WALK_V6(&ctx, ipst);
19388 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19389 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19390 		    ill->ill_phyint->phyint_ifindex;
19391 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19392 		    (char *)ill->ill_icmp6_mib,
19393 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19394 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19395 			    "%u bytes\n",
19396 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19397 		}
19398 	}
19399 	rw_exit(&ipst->ips_ill_g_lock);
19400 
19401 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19402 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19403 	    (int)optp->level, (int)optp->name, (int)optp->len));
19404 	qreply(q, mpctl);
19405 	return (mp2ctl);
19406 }
19407 
19408 /*
19409  * ire_walk routine to create both ipRouteEntryTable and
19410  * ipRouteAttributeTable in one IRE walk
19411  */
19412 static void
19413 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19414 {
19415 	ill_t				*ill;
19416 	ipif_t				*ipif;
19417 	mib2_ipRouteEntry_t		*re;
19418 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19419 	ipaddr_t			gw_addr;
19420 	tsol_ire_gw_secattr_t		*attrp;
19421 	tsol_gc_t			*gc = NULL;
19422 	tsol_gcgrp_t			*gcgrp = NULL;
19423 	uint_t				sacnt = 0;
19424 	int				i;
19425 
19426 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19427 
19428 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19429 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19430 		return;
19431 	}
19432 
19433 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19434 		return;
19435 
19436 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19437 		mutex_enter(&attrp->igsa_lock);
19438 		if ((gc = attrp->igsa_gc) != NULL) {
19439 			gcgrp = gc->gc_grp;
19440 			ASSERT(gcgrp != NULL);
19441 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19442 			sacnt = 1;
19443 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19444 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19445 			gc = gcgrp->gcgrp_head;
19446 			sacnt = gcgrp->gcgrp_count;
19447 		}
19448 		mutex_exit(&attrp->igsa_lock);
19449 
19450 		/* do nothing if there's no gc to report */
19451 		if (gc == NULL) {
19452 			ASSERT(sacnt == 0);
19453 			if (gcgrp != NULL) {
19454 				/* we might as well drop the lock now */
19455 				rw_exit(&gcgrp->gcgrp_rwlock);
19456 				gcgrp = NULL;
19457 			}
19458 			attrp = NULL;
19459 		}
19460 
19461 		ASSERT(gc == NULL || (gcgrp != NULL &&
19462 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19463 	}
19464 	ASSERT(sacnt == 0 || gc != NULL);
19465 
19466 	if (sacnt != 0 &&
19467 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19468 		kmem_free(re, sizeof (*re));
19469 		rw_exit(&gcgrp->gcgrp_rwlock);
19470 		return;
19471 	}
19472 
19473 	/*
19474 	 * Return all IRE types for route table... let caller pick and choose
19475 	 */
19476 	re->ipRouteDest = ire->ire_addr;
19477 	ipif = ire->ire_ipif;
19478 	re->ipRouteIfIndex.o_length = 0;
19479 	if (ire->ire_type == IRE_CACHE) {
19480 		ill = (ill_t *)ire->ire_stq->q_ptr;
19481 		re->ipRouteIfIndex.o_length =
19482 		    ill->ill_name_length == 0 ? 0 :
19483 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19484 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19485 		    re->ipRouteIfIndex.o_length);
19486 	} else if (ipif != NULL) {
19487 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19488 		re->ipRouteIfIndex.o_length =
19489 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19490 	}
19491 	re->ipRouteMetric1 = -1;
19492 	re->ipRouteMetric2 = -1;
19493 	re->ipRouteMetric3 = -1;
19494 	re->ipRouteMetric4 = -1;
19495 
19496 	gw_addr = ire->ire_gateway_addr;
19497 
19498 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19499 		re->ipRouteNextHop = ire->ire_src_addr;
19500 	else
19501 		re->ipRouteNextHop = gw_addr;
19502 	/* indirect(4), direct(3), or invalid(2) */
19503 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19504 		re->ipRouteType = 2;
19505 	else
19506 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19507 	re->ipRouteProto = -1;
19508 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19509 	re->ipRouteMask = ire->ire_mask;
19510 	re->ipRouteMetric5 = -1;
19511 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19512 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19513 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19514 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19515 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19516 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19517 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19518 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19519 
19520 	if (ire->ire_flags & RTF_DYNAMIC) {
19521 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19522 	} else {
19523 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19524 	}
19525 
19526 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19527 	    (char *)re, (int)sizeof (*re))) {
19528 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19529 		    (uint_t)sizeof (*re)));
19530 	}
19531 
19532 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19533 		iaeptr->iae_routeidx = ird->ird_idx;
19534 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19535 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19536 	}
19537 
19538 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19539 	    (char *)iae, sacnt * sizeof (*iae))) {
19540 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19541 		    (unsigned)(sacnt * sizeof (*iae))));
19542 	}
19543 
19544 	/* bump route index for next pass */
19545 	ird->ird_idx++;
19546 
19547 	kmem_free(re, sizeof (*re));
19548 	if (sacnt != 0)
19549 		kmem_free(iae, sacnt * sizeof (*iae));
19550 
19551 	if (gcgrp != NULL)
19552 		rw_exit(&gcgrp->gcgrp_rwlock);
19553 }
19554 
19555 /*
19556  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19557  */
19558 static void
19559 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19560 {
19561 	ill_t				*ill;
19562 	ipif_t				*ipif;
19563 	mib2_ipv6RouteEntry_t		*re;
19564 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19565 	in6_addr_t			gw_addr_v6;
19566 	tsol_ire_gw_secattr_t		*attrp;
19567 	tsol_gc_t			*gc = NULL;
19568 	tsol_gcgrp_t			*gcgrp = NULL;
19569 	uint_t				sacnt = 0;
19570 	int				i;
19571 
19572 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19573 
19574 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19575 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19576 		return;
19577 	}
19578 
19579 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19580 		return;
19581 
19582 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19583 		mutex_enter(&attrp->igsa_lock);
19584 		if ((gc = attrp->igsa_gc) != NULL) {
19585 			gcgrp = gc->gc_grp;
19586 			ASSERT(gcgrp != NULL);
19587 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19588 			sacnt = 1;
19589 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19590 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19591 			gc = gcgrp->gcgrp_head;
19592 			sacnt = gcgrp->gcgrp_count;
19593 		}
19594 		mutex_exit(&attrp->igsa_lock);
19595 
19596 		/* do nothing if there's no gc to report */
19597 		if (gc == NULL) {
19598 			ASSERT(sacnt == 0);
19599 			if (gcgrp != NULL) {
19600 				/* we might as well drop the lock now */
19601 				rw_exit(&gcgrp->gcgrp_rwlock);
19602 				gcgrp = NULL;
19603 			}
19604 			attrp = NULL;
19605 		}
19606 
19607 		ASSERT(gc == NULL || (gcgrp != NULL &&
19608 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19609 	}
19610 	ASSERT(sacnt == 0 || gc != NULL);
19611 
19612 	if (sacnt != 0 &&
19613 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19614 		kmem_free(re, sizeof (*re));
19615 		rw_exit(&gcgrp->gcgrp_rwlock);
19616 		return;
19617 	}
19618 
19619 	/*
19620 	 * Return all IRE types for route table... let caller pick and choose
19621 	 */
19622 	re->ipv6RouteDest = ire->ire_addr_v6;
19623 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19624 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19625 	re->ipv6RouteIfIndex.o_length = 0;
19626 	ipif = ire->ire_ipif;
19627 	if (ire->ire_type == IRE_CACHE) {
19628 		ill = (ill_t *)ire->ire_stq->q_ptr;
19629 		re->ipv6RouteIfIndex.o_length =
19630 		    ill->ill_name_length == 0 ? 0 :
19631 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19632 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19633 		    re->ipv6RouteIfIndex.o_length);
19634 	} else if (ipif != NULL) {
19635 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19636 		re->ipv6RouteIfIndex.o_length =
19637 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19638 	}
19639 
19640 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19641 
19642 	mutex_enter(&ire->ire_lock);
19643 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19644 	mutex_exit(&ire->ire_lock);
19645 
19646 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19647 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19648 	else
19649 		re->ipv6RouteNextHop = gw_addr_v6;
19650 
19651 	/* remote(4), local(3), or discard(2) */
19652 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19653 		re->ipv6RouteType = 2;
19654 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19655 		re->ipv6RouteType = 3;
19656 	else
19657 		re->ipv6RouteType = 4;
19658 
19659 	re->ipv6RouteProtocol	= -1;
19660 	re->ipv6RoutePolicy	= 0;
19661 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19662 	re->ipv6RouteNextHopRDI	= 0;
19663 	re->ipv6RouteWeight	= 0;
19664 	re->ipv6RouteMetric	= 0;
19665 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19666 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19667 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19668 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19669 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19670 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19671 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19672 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19673 
19674 	if (ire->ire_flags & RTF_DYNAMIC) {
19675 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19676 	} else {
19677 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19678 	}
19679 
19680 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19681 	    (char *)re, (int)sizeof (*re))) {
19682 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19683 		    (uint_t)sizeof (*re)));
19684 	}
19685 
19686 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19687 		iaeptr->iae_routeidx = ird->ird_idx;
19688 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19689 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19690 	}
19691 
19692 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19693 	    (char *)iae, sacnt * sizeof (*iae))) {
19694 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19695 		    (unsigned)(sacnt * sizeof (*iae))));
19696 	}
19697 
19698 	/* bump route index for next pass */
19699 	ird->ird_idx++;
19700 
19701 	kmem_free(re, sizeof (*re));
19702 	if (sacnt != 0)
19703 		kmem_free(iae, sacnt * sizeof (*iae));
19704 
19705 	if (gcgrp != NULL)
19706 		rw_exit(&gcgrp->gcgrp_rwlock);
19707 }
19708 
19709 /*
19710  * ndp_walk routine to create ipv6NetToMediaEntryTable
19711  */
19712 static int
19713 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19714 {
19715 	ill_t				*ill;
19716 	mib2_ipv6NetToMediaEntry_t	ntme;
19717 	dl_unitdata_req_t		*dl;
19718 
19719 	ill = nce->nce_ill;
19720 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19721 		return (0);
19722 
19723 	/*
19724 	 * Neighbor cache entry attached to IRE with on-link
19725 	 * destination.
19726 	 */
19727 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19728 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19729 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19730 	    (nce->nce_res_mp != NULL)) {
19731 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19732 		ntme.ipv6NetToMediaPhysAddress.o_length =
19733 		    dl->dl_dest_addr_length;
19734 	} else {
19735 		ntme.ipv6NetToMediaPhysAddress.o_length =
19736 		    ill->ill_phys_addr_length;
19737 	}
19738 	if (nce->nce_res_mp != NULL) {
19739 		bcopy((char *)nce->nce_res_mp->b_rptr +
19740 		    NCE_LL_ADDR_OFFSET(ill),
19741 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19742 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19743 	} else {
19744 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19745 		    ill->ill_phys_addr_length);
19746 	}
19747 	/*
19748 	 * Note: Returns ND_* states. Should be:
19749 	 * reachable(1), stale(2), delay(3), probe(4),
19750 	 * invalid(5), unknown(6)
19751 	 */
19752 	ntme.ipv6NetToMediaState = nce->nce_state;
19753 	ntme.ipv6NetToMediaLastUpdated = 0;
19754 
19755 	/* other(1), dynamic(2), static(3), local(4) */
19756 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19757 		ntme.ipv6NetToMediaType = 4;
19758 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19759 		ntme.ipv6NetToMediaType = 1;
19760 	} else {
19761 		ntme.ipv6NetToMediaType = 2;
19762 	}
19763 
19764 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19765 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19766 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19767 		    (uint_t)sizeof (ntme)));
19768 	}
19769 	return (0);
19770 }
19771 
19772 /*
19773  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19774  */
19775 /* ARGSUSED */
19776 int
19777 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19778 {
19779 	switch (level) {
19780 	case MIB2_IP:
19781 	case MIB2_ICMP:
19782 		switch (name) {
19783 		default:
19784 			break;
19785 		}
19786 		return (1);
19787 	default:
19788 		return (1);
19789 	}
19790 }
19791 
19792 /*
19793  * When there exists both a 64- and 32-bit counter of a particular type
19794  * (i.e., InReceives), only the 64-bit counters are added.
19795  */
19796 void
19797 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19798 {
19799 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19800 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19801 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19802 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19803 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19804 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19805 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19806 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19807 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19808 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19809 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19810 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19811 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19812 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19813 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19814 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19815 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19816 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19817 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19818 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19819 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19820 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19821 	    o2->ipIfStatsInWrongIPVersion);
19822 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19823 	    o2->ipIfStatsInWrongIPVersion);
19824 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19825 	    o2->ipIfStatsOutSwitchIPVersion);
19826 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19827 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19828 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19829 	    o2->ipIfStatsHCInForwDatagrams);
19830 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19831 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19832 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19833 	    o2->ipIfStatsHCOutForwDatagrams);
19834 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19835 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19836 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19837 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19838 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19839 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19840 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19841 	    o2->ipIfStatsHCOutMcastOctets);
19842 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19843 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19844 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19845 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19846 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19847 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19848 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19849 }
19850 
19851 void
19852 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19853 {
19854 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19855 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19856 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19857 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19859 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19861 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19862 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19863 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19864 	    o2->ipv6IfIcmpInRouterSolicits);
19865 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19866 	    o2->ipv6IfIcmpInRouterAdvertisements);
19867 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19868 	    o2->ipv6IfIcmpInNeighborSolicits);
19869 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19870 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19871 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19872 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19873 	    o2->ipv6IfIcmpInGroupMembQueries);
19874 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19875 	    o2->ipv6IfIcmpInGroupMembResponses);
19876 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19877 	    o2->ipv6IfIcmpInGroupMembReductions);
19878 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19879 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19880 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19881 	    o2->ipv6IfIcmpOutDestUnreachs);
19882 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19883 	    o2->ipv6IfIcmpOutAdminProhibs);
19884 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19885 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19886 	    o2->ipv6IfIcmpOutParmProblems);
19887 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19888 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19889 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19890 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19891 	    o2->ipv6IfIcmpOutRouterSolicits);
19892 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19893 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19894 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19895 	    o2->ipv6IfIcmpOutNeighborSolicits);
19896 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19897 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19898 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19899 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19900 	    o2->ipv6IfIcmpOutGroupMembQueries);
19901 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19902 	    o2->ipv6IfIcmpOutGroupMembResponses);
19903 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19904 	    o2->ipv6IfIcmpOutGroupMembReductions);
19905 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19906 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19907 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19908 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19909 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19910 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19911 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19912 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19913 	    o2->ipv6IfIcmpInGroupMembTotal);
19914 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19915 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19916 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19917 	    o2->ipv6IfIcmpInGroupMembBadReports);
19918 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19919 	    o2->ipv6IfIcmpInGroupMembOurReports);
19920 }
19921 
19922 /*
19923  * Called before the options are updated to check if this packet will
19924  * be source routed from here.
19925  * This routine assumes that the options are well formed i.e. that they
19926  * have already been checked.
19927  */
19928 static boolean_t
19929 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19930 {
19931 	ipoptp_t	opts;
19932 	uchar_t		*opt;
19933 	uint8_t		optval;
19934 	uint8_t		optlen;
19935 	ipaddr_t	dst;
19936 	ire_t		*ire;
19937 
19938 	if (IS_SIMPLE_IPH(ipha)) {
19939 		ip2dbg(("not source routed\n"));
19940 		return (B_FALSE);
19941 	}
19942 	dst = ipha->ipha_dst;
19943 	for (optval = ipoptp_first(&opts, ipha);
19944 	    optval != IPOPT_EOL;
19945 	    optval = ipoptp_next(&opts)) {
19946 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19947 		opt = opts.ipoptp_cur;
19948 		optlen = opts.ipoptp_len;
19949 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19950 		    optval, optlen));
19951 		switch (optval) {
19952 			uint32_t off;
19953 		case IPOPT_SSRR:
19954 		case IPOPT_LSRR:
19955 			/*
19956 			 * If dst is one of our addresses and there are some
19957 			 * entries left in the source route return (true).
19958 			 */
19959 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19960 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19961 			if (ire == NULL) {
19962 				ip2dbg(("ip_source_routed: not next"
19963 				    " source route 0x%x\n",
19964 				    ntohl(dst)));
19965 				return (B_FALSE);
19966 			}
19967 			ire_refrele(ire);
19968 			off = opt[IPOPT_OFFSET];
19969 			off--;
19970 			if (optlen < IP_ADDR_LEN ||
19971 			    off > optlen - IP_ADDR_LEN) {
19972 				/* End of source route */
19973 				ip1dbg(("ip_source_routed: end of SR\n"));
19974 				return (B_FALSE);
19975 			}
19976 			return (B_TRUE);
19977 		}
19978 	}
19979 	ip2dbg(("not source routed\n"));
19980 	return (B_FALSE);
19981 }
19982 
19983 /*
19984  * Check if the packet contains any source route.
19985  */
19986 static boolean_t
19987 ip_source_route_included(ipha_t *ipha)
19988 {
19989 	ipoptp_t	opts;
19990 	uint8_t		optval;
19991 
19992 	if (IS_SIMPLE_IPH(ipha))
19993 		return (B_FALSE);
19994 	for (optval = ipoptp_first(&opts, ipha);
19995 	    optval != IPOPT_EOL;
19996 	    optval = ipoptp_next(&opts)) {
19997 		switch (optval) {
19998 		case IPOPT_SSRR:
19999 		case IPOPT_LSRR:
20000 			return (B_TRUE);
20001 		}
20002 	}
20003 	return (B_FALSE);
20004 }
20005 
20006 /*
20007  * Called when the IRE expiration timer fires.
20008  */
20009 void
20010 ip_trash_timer_expire(void *args)
20011 {
20012 	int			flush_flag = 0;
20013 	ire_expire_arg_t	iea;
20014 	ip_stack_t		*ipst = (ip_stack_t *)args;
20015 
20016 	iea.iea_ipst = ipst;	/* No netstack_hold */
20017 
20018 	/*
20019 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20020 	 * This lock makes sure that a new invocation of this function
20021 	 * that occurs due to an almost immediate timer firing will not
20022 	 * progress beyond this point until the current invocation is done
20023 	 */
20024 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20025 	ipst->ips_ip_ire_expire_id = 0;
20026 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20027 
20028 	/* Periodic timer */
20029 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20030 	    ipst->ips_ip_ire_arp_interval) {
20031 		/*
20032 		 * Remove all IRE_CACHE entries since they might
20033 		 * contain arp information.
20034 		 */
20035 		flush_flag |= FLUSH_ARP_TIME;
20036 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20037 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20038 	}
20039 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20040 	    ipst->ips_ip_ire_redir_interval) {
20041 		/* Remove all redirects */
20042 		flush_flag |= FLUSH_REDIRECT_TIME;
20043 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20044 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20045 	}
20046 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20047 	    ipst->ips_ip_ire_pathmtu_interval) {
20048 		/* Increase path mtu */
20049 		flush_flag |= FLUSH_MTU_TIME;
20050 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20051 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20052 	}
20053 
20054 	/*
20055 	 * Optimize for the case when there are no redirects in the
20056 	 * ftable, that is, no need to walk the ftable in that case.
20057 	 */
20058 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20059 		iea.iea_flush_flag = flush_flag;
20060 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20061 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20062 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20063 		    NULL, ALL_ZONES, ipst);
20064 	}
20065 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20066 	    ipst->ips_ip_redirect_cnt > 0) {
20067 		iea.iea_flush_flag = flush_flag;
20068 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20069 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20070 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20071 	}
20072 	if (flush_flag & FLUSH_MTU_TIME) {
20073 		/*
20074 		 * Walk all IPv6 IRE's and update them
20075 		 * Note that ARP and redirect timers are not
20076 		 * needed since NUD handles stale entries.
20077 		 */
20078 		flush_flag = FLUSH_MTU_TIME;
20079 		iea.iea_flush_flag = flush_flag;
20080 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20081 		    ALL_ZONES, ipst);
20082 	}
20083 
20084 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20085 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20086 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20087 
20088 	/*
20089 	 * Hold the lock to serialize timeout calls and prevent
20090 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20091 	 * for the timer to fire and a new invocation of this function
20092 	 * to start before the return value of timeout has been stored
20093 	 * in ip_ire_expire_id by the current invocation.
20094 	 */
20095 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20096 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20097 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20098 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20099 }
20100 
20101 /*
20102  * Called by the memory allocator subsystem directly, when the system
20103  * is running low on memory.
20104  */
20105 /* ARGSUSED */
20106 void
20107 ip_trash_ire_reclaim(void *args)
20108 {
20109 	netstack_handle_t nh;
20110 	netstack_t *ns;
20111 
20112 	netstack_next_init(&nh);
20113 	while ((ns = netstack_next(&nh)) != NULL) {
20114 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20115 		netstack_rele(ns);
20116 	}
20117 	netstack_next_fini(&nh);
20118 }
20119 
20120 static void
20121 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20122 {
20123 	ire_cache_count_t icc;
20124 	ire_cache_reclaim_t icr;
20125 	ncc_cache_count_t ncc;
20126 	nce_cache_reclaim_t ncr;
20127 	uint_t delete_cnt;
20128 	/*
20129 	 * Memory reclaim call back.
20130 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20131 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20132 	 * entries, determine what fraction to free for
20133 	 * each category of IRE_CACHE entries giving absolute priority
20134 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20135 	 * entry will be freed unless all offlink entries are freed).
20136 	 */
20137 	icc.icc_total = 0;
20138 	icc.icc_unused = 0;
20139 	icc.icc_offlink = 0;
20140 	icc.icc_pmtu = 0;
20141 	icc.icc_onlink = 0;
20142 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20143 
20144 	/*
20145 	 * Free NCEs for IPv6 like the onlink ires.
20146 	 */
20147 	ncc.ncc_total = 0;
20148 	ncc.ncc_host = 0;
20149 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20150 
20151 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20152 	    icc.icc_pmtu + icc.icc_onlink);
20153 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20154 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20155 	if (delete_cnt == 0)
20156 		return;
20157 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20158 	/* Always delete all unused offlink entries */
20159 	icr.icr_ipst = ipst;
20160 	icr.icr_unused = 1;
20161 	if (delete_cnt <= icc.icc_unused) {
20162 		/*
20163 		 * Only need to free unused entries.  In other words,
20164 		 * there are enough unused entries to free to meet our
20165 		 * target number of freed ire cache entries.
20166 		 */
20167 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20168 		ncr.ncr_host = 0;
20169 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20170 		/*
20171 		 * Only need to free unused entries, plus a fraction of offlink
20172 		 * entries.  It follows from the first if statement that
20173 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20174 		 */
20175 		delete_cnt -= icc.icc_unused;
20176 		/* Round up # deleted by truncating fraction */
20177 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20178 		icr.icr_pmtu = icr.icr_onlink = 0;
20179 		ncr.ncr_host = 0;
20180 	} else if (delete_cnt <=
20181 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20182 		/*
20183 		 * Free all unused and offlink entries, plus a fraction of
20184 		 * pmtu entries.  It follows from the previous if statement
20185 		 * that icc_pmtu is non-zero, and that
20186 		 * delete_cnt != icc_unused + icc_offlink.
20187 		 */
20188 		icr.icr_offlink = 1;
20189 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20190 		/* Round up # deleted by truncating fraction */
20191 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20192 		icr.icr_onlink = 0;
20193 		ncr.ncr_host = 0;
20194 	} else {
20195 		/*
20196 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20197 		 * of onlink entries.  If we're here, then we know that
20198 		 * icc_onlink is non-zero, and that
20199 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20200 		 */
20201 		icr.icr_offlink = icr.icr_pmtu = 1;
20202 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20203 		    icc.icc_pmtu;
20204 		/* Round up # deleted by truncating fraction */
20205 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20206 		/* Using the same delete fraction as for onlink IREs */
20207 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20208 	}
20209 #ifdef DEBUG
20210 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20211 	    "fractions %d/%d/%d/%d\n",
20212 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20213 	    icc.icc_unused, icc.icc_offlink,
20214 	    icc.icc_pmtu, icc.icc_onlink,
20215 	    icr.icr_unused, icr.icr_offlink,
20216 	    icr.icr_pmtu, icr.icr_onlink));
20217 #endif
20218 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20219 	if (ncr.ncr_host != 0)
20220 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20221 		    (uchar_t *)&ncr, ipst);
20222 #ifdef DEBUG
20223 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20224 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20225 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20226 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20227 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20228 	    icc.icc_pmtu, icc.icc_onlink));
20229 #endif
20230 }
20231 
20232 /*
20233  * ip_unbind is called when a copy of an unbind request is received from the
20234  * upper level protocol.  We remove this conn from any fanout hash list it is
20235  * on, and zero out the bind information.  No reply is expected up above.
20236  */
20237 void
20238 ip_unbind(conn_t *connp)
20239 {
20240 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20241 
20242 	if (is_system_labeled() && connp->conn_anon_port) {
20243 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20244 		    connp->conn_mlp_type, connp->conn_ulp,
20245 		    ntohs(connp->conn_lport), B_FALSE);
20246 		connp->conn_anon_port = 0;
20247 	}
20248 	connp->conn_mlp_type = mlptSingle;
20249 
20250 	ipcl_hash_remove(connp);
20251 }
20252 
20253 /*
20254  * Write side put procedure.  Outbound data, IOCTLs, responses from
20255  * resolvers, etc, come down through here.
20256  *
20257  * arg2 is always a queue_t *.
20258  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20259  * the zoneid.
20260  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20261  */
20262 void
20263 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20264 {
20265 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20266 }
20267 
20268 void
20269 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20270     ip_opt_info_t *infop)
20271 {
20272 	conn_t		*connp = NULL;
20273 	queue_t		*q = (queue_t *)arg2;
20274 	ipha_t		*ipha;
20275 #define	rptr	((uchar_t *)ipha)
20276 	ire_t		*ire = NULL;
20277 	ire_t		*sctp_ire = NULL;
20278 	uint32_t	v_hlen_tos_len;
20279 	ipaddr_t	dst;
20280 	mblk_t		*first_mp = NULL;
20281 	boolean_t	mctl_present;
20282 	ipsec_out_t	*io;
20283 	int		match_flags;
20284 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20285 	ipif_t		*dst_ipif;
20286 	boolean_t	multirt_need_resolve = B_FALSE;
20287 	mblk_t		*copy_mp = NULL;
20288 	int		err = 0;
20289 	zoneid_t	zoneid;
20290 	boolean_t	need_decref = B_FALSE;
20291 	boolean_t	ignore_dontroute = B_FALSE;
20292 	boolean_t	ignore_nexthop = B_FALSE;
20293 	boolean_t	ip_nexthop = B_FALSE;
20294 	ipaddr_t	nexthop_addr;
20295 	ip_stack_t	*ipst;
20296 
20297 #ifdef	_BIG_ENDIAN
20298 #define	V_HLEN	(v_hlen_tos_len >> 24)
20299 #else
20300 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20301 #endif
20302 
20303 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20304 	    "ip_wput_start: q %p", q);
20305 
20306 	/*
20307 	 * ip_wput fast path
20308 	 */
20309 
20310 	/* is packet from ARP ? */
20311 	if (q->q_next != NULL) {
20312 		zoneid = (zoneid_t)(uintptr_t)arg;
20313 		goto qnext;
20314 	}
20315 
20316 	connp = (conn_t *)arg;
20317 	ASSERT(connp != NULL);
20318 	zoneid = connp->conn_zoneid;
20319 	ipst = connp->conn_netstack->netstack_ip;
20320 	ASSERT(ipst != NULL);
20321 
20322 	/* is queue flow controlled? */
20323 	if ((q->q_first != NULL || connp->conn_draining) &&
20324 	    (caller == IP_WPUT)) {
20325 		ASSERT(!need_decref);
20326 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20327 		(void) putq(q, mp);
20328 		return;
20329 	}
20330 
20331 	/* Multidata transmit? */
20332 	if (DB_TYPE(mp) == M_MULTIDATA) {
20333 		/*
20334 		 * We should never get here, since all Multidata messages
20335 		 * originating from tcp should have been directed over to
20336 		 * tcp_multisend() in the first place.
20337 		 */
20338 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20339 		freemsg(mp);
20340 		return;
20341 	} else if (DB_TYPE(mp) != M_DATA)
20342 		goto notdata;
20343 
20344 	if (mp->b_flag & MSGHASREF) {
20345 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20346 		mp->b_flag &= ~MSGHASREF;
20347 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20348 		need_decref = B_TRUE;
20349 	}
20350 	ipha = (ipha_t *)mp->b_rptr;
20351 
20352 	/* is IP header non-aligned or mblk smaller than basic IP header */
20353 #ifndef SAFETY_BEFORE_SPEED
20354 	if (!OK_32PTR(rptr) ||
20355 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20356 		goto hdrtoosmall;
20357 #endif
20358 
20359 	ASSERT(OK_32PTR(ipha));
20360 
20361 	/*
20362 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20363 	 * wrong version, we'll catch it again in ip_output_v6.
20364 	 *
20365 	 * Note that this is *only* locally-generated output here, and never
20366 	 * forwarded data, and that we need to deal only with transports that
20367 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20368 	 * label.)
20369 	 */
20370 	if (is_system_labeled() &&
20371 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20372 	    !connp->conn_ulp_labeled) {
20373 		cred_t	*credp;
20374 		pid_t	pid;
20375 
20376 		credp = BEST_CRED(mp, connp, &pid);
20377 		err = tsol_check_label(credp, &mp,
20378 		    connp->conn_mac_mode, ipst, pid);
20379 		ipha = (ipha_t *)mp->b_rptr;
20380 		if (err != 0) {
20381 			first_mp = mp;
20382 			if (err == EINVAL)
20383 				goto icmp_parameter_problem;
20384 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20385 			goto discard_pkt;
20386 		}
20387 	}
20388 
20389 	ASSERT(infop != NULL);
20390 
20391 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20392 		/*
20393 		 * IP_PKTINFO ancillary option is present.
20394 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20395 		 * allows using address of any zone as the source address.
20396 		 */
20397 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20398 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20399 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20400 		if (ire == NULL)
20401 			goto drop_pkt;
20402 		ire_refrele(ire);
20403 		ire = NULL;
20404 	}
20405 
20406 	/*
20407 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20408 	 */
20409 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20410 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20411 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20412 
20413 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20414 			goto drop_pkt;
20415 		/*
20416 		 * check that there is an ipif belonging
20417 		 * to our zone. IPCL_ZONEID is not used because
20418 		 * IP_ALLZONES option is valid only when the ill is
20419 		 * accessible from all zones i.e has a valid ipif in
20420 		 * all zones.
20421 		 */
20422 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20423 			goto drop_pkt;
20424 		}
20425 	}
20426 
20427 	/*
20428 	 * If there is a policy, try to attach an ipsec_out in
20429 	 * the front. At the end, first_mp either points to a
20430 	 * M_DATA message or IPSEC_OUT message linked to a
20431 	 * M_DATA message. We have to do it now as we might
20432 	 * lose the "conn" if we go through ip_newroute.
20433 	 */
20434 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20435 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20436 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20437 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20438 			if (need_decref)
20439 				CONN_DEC_REF(connp);
20440 			return;
20441 		}
20442 		ASSERT(mp->b_datap->db_type == M_CTL);
20443 		first_mp = mp;
20444 		mp = mp->b_cont;
20445 		mctl_present = B_TRUE;
20446 	} else {
20447 		first_mp = mp;
20448 		mctl_present = B_FALSE;
20449 	}
20450 
20451 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20452 
20453 	/* is wrong version or IP options present */
20454 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20455 		goto version_hdrlen_check;
20456 	dst = ipha->ipha_dst;
20457 
20458 	/* If IP_BOUND_IF has been set, use that ill. */
20459 	if (connp->conn_outgoing_ill != NULL) {
20460 		xmit_ill = conn_get_held_ill(connp,
20461 		    &connp->conn_outgoing_ill, &err);
20462 		if (err == ILL_LOOKUP_FAILED)
20463 			goto drop_pkt;
20464 
20465 		goto send_from_ill;
20466 	}
20467 
20468 	/* is packet multicast? */
20469 	if (CLASSD(dst))
20470 		goto multicast;
20471 
20472 	/*
20473 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20474 	 * takes precedence over conn_dontroute and conn_nexthop_set
20475 	 */
20476 	if (xmit_ill != NULL)
20477 		goto send_from_ill;
20478 
20479 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20480 		/*
20481 		 * If the destination is a broadcast, local, or loopback
20482 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20483 		 * standard path.
20484 		 */
20485 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20486 		if ((ire == NULL) || (ire->ire_type &
20487 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20488 			if (ire != NULL) {
20489 				ire_refrele(ire);
20490 				/* No more access to ire */
20491 				ire = NULL;
20492 			}
20493 			/*
20494 			 * bypass routing checks and go directly to interface.
20495 			 */
20496 			if (connp->conn_dontroute)
20497 				goto dontroute;
20498 
20499 			ASSERT(connp->conn_nexthop_set);
20500 			ip_nexthop = B_TRUE;
20501 			nexthop_addr = connp->conn_nexthop_v4;
20502 			goto send_from_ill;
20503 		}
20504 
20505 		/* Must be a broadcast, a loopback or a local ire */
20506 		ire_refrele(ire);
20507 		/* No more access to ire */
20508 		ire = NULL;
20509 	}
20510 
20511 	/*
20512 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20513 	 * this for the tcp global queue and listen end point
20514 	 * as it does not really have a real destination to
20515 	 * talk to.  This is also true for SCTP.
20516 	 */
20517 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20518 	    !connp->conn_fully_bound) {
20519 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20520 		if (ire == NULL)
20521 			goto noirefound;
20522 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20523 		    "ip_wput_end: q %p (%S)", q, "end");
20524 
20525 		/*
20526 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20527 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20528 		 */
20529 		if (ire->ire_flags & RTF_MULTIRT) {
20530 
20531 			/*
20532 			 * Force the TTL of multirouted packets if required.
20533 			 * The TTL of such packets is bounded by the
20534 			 * ip_multirt_ttl ndd variable.
20535 			 */
20536 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20537 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20538 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20539 				    "(was %d), dst 0x%08x\n",
20540 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20541 				    ntohl(ire->ire_addr)));
20542 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20543 			}
20544 			/*
20545 			 * We look at this point if there are pending
20546 			 * unresolved routes. ire_multirt_resolvable()
20547 			 * checks in O(n) that all IRE_OFFSUBNET ire
20548 			 * entries for the packet's destination and
20549 			 * flagged RTF_MULTIRT are currently resolved.
20550 			 * If some remain unresolved, we make a copy
20551 			 * of the current message. It will be used
20552 			 * to initiate additional route resolutions.
20553 			 */
20554 			multirt_need_resolve =
20555 			    ire_multirt_need_resolve(ire->ire_addr,
20556 			    msg_getlabel(first_mp), ipst);
20557 			ip2dbg(("ip_wput[TCP]: ire %p, "
20558 			    "multirt_need_resolve %d, first_mp %p\n",
20559 			    (void *)ire, multirt_need_resolve,
20560 			    (void *)first_mp));
20561 			if (multirt_need_resolve) {
20562 				copy_mp = copymsg(first_mp);
20563 				if (copy_mp != NULL) {
20564 					MULTIRT_DEBUG_TAG(copy_mp);
20565 				}
20566 			}
20567 		}
20568 
20569 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20570 
20571 		/*
20572 		 * Try to resolve another multiroute if
20573 		 * ire_multirt_need_resolve() deemed it necessary.
20574 		 */
20575 		if (copy_mp != NULL)
20576 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20577 		if (need_decref)
20578 			CONN_DEC_REF(connp);
20579 		return;
20580 	}
20581 
20582 	/*
20583 	 * Access to conn_ire_cache. (protected by conn_lock)
20584 	 *
20585 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20586 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20587 	 * send a packet or two with the IRE_CACHE that is going away.
20588 	 * Access to the ire requires an ire refhold on the ire prior to
20589 	 * its use since an interface unplumb thread may delete the cached
20590 	 * ire and release the refhold at any time.
20591 	 *
20592 	 * Caching an ire in the conn_ire_cache
20593 	 *
20594 	 * o Caching an ire pointer in the conn requires a strict check for
20595 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20596 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20597 	 * in the conn is done after making sure under the bucket lock that the
20598 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20599 	 * caching an ire after the unplumb thread has cleaned up the conn.
20600 	 * If the conn does not send a packet subsequently the unplumb thread
20601 	 * will be hanging waiting for the ire count to drop to zero.
20602 	 *
20603 	 * o We also need to atomically test for a null conn_ire_cache and
20604 	 * set the conn_ire_cache under the the protection of the conn_lock
20605 	 * to avoid races among concurrent threads trying to simultaneously
20606 	 * cache an ire in the conn_ire_cache.
20607 	 */
20608 	mutex_enter(&connp->conn_lock);
20609 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20610 
20611 	if (ire != NULL && ire->ire_addr == dst &&
20612 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20613 
20614 		IRE_REFHOLD(ire);
20615 		mutex_exit(&connp->conn_lock);
20616 
20617 	} else {
20618 		boolean_t cached = B_FALSE;
20619 		connp->conn_ire_cache = NULL;
20620 		mutex_exit(&connp->conn_lock);
20621 		/* Release the old ire */
20622 		if (ire != NULL && sctp_ire == NULL)
20623 			IRE_REFRELE_NOTR(ire);
20624 
20625 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20626 		if (ire == NULL)
20627 			goto noirefound;
20628 		IRE_REFHOLD_NOTR(ire);
20629 
20630 		mutex_enter(&connp->conn_lock);
20631 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20632 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20633 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20634 				if (connp->conn_ulp == IPPROTO_TCP)
20635 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20636 				connp->conn_ire_cache = ire;
20637 				cached = B_TRUE;
20638 			}
20639 			rw_exit(&ire->ire_bucket->irb_lock);
20640 		}
20641 		mutex_exit(&connp->conn_lock);
20642 
20643 		/*
20644 		 * We can continue to use the ire but since it was
20645 		 * not cached, we should drop the extra reference.
20646 		 */
20647 		if (!cached)
20648 			IRE_REFRELE_NOTR(ire);
20649 	}
20650 
20651 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20652 	    "ip_wput_end: q %p (%S)", q, "end");
20653 
20654 	/*
20655 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20656 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20657 	 */
20658 	if (ire->ire_flags & RTF_MULTIRT) {
20659 		/*
20660 		 * Force the TTL of multirouted packets if required.
20661 		 * The TTL of such packets is bounded by the
20662 		 * ip_multirt_ttl ndd variable.
20663 		 */
20664 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20665 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20666 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20667 			    "(was %d), dst 0x%08x\n",
20668 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20669 			    ntohl(ire->ire_addr)));
20670 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20671 		}
20672 
20673 		/*
20674 		 * At this point, we check to see if there are any pending
20675 		 * unresolved routes. ire_multirt_resolvable()
20676 		 * checks in O(n) that all IRE_OFFSUBNET ire
20677 		 * entries for the packet's destination and
20678 		 * flagged RTF_MULTIRT are currently resolved.
20679 		 * If some remain unresolved, we make a copy
20680 		 * of the current message. It will be used
20681 		 * to initiate additional route resolutions.
20682 		 */
20683 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20684 		    msg_getlabel(first_mp), ipst);
20685 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20686 		    "multirt_need_resolve %d, first_mp %p\n",
20687 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20688 		if (multirt_need_resolve) {
20689 			copy_mp = copymsg(first_mp);
20690 			if (copy_mp != NULL) {
20691 				MULTIRT_DEBUG_TAG(copy_mp);
20692 			}
20693 		}
20694 	}
20695 
20696 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20697 
20698 	/*
20699 	 * Try to resolve another multiroute if
20700 	 * ire_multirt_resolvable() deemed it necessary
20701 	 */
20702 	if (copy_mp != NULL)
20703 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20704 	if (need_decref)
20705 		CONN_DEC_REF(connp);
20706 	return;
20707 
20708 qnext:
20709 	/*
20710 	 * Upper Level Protocols pass down complete IP datagrams
20711 	 * as M_DATA messages.	Everything else is a sideshow.
20712 	 *
20713 	 * 1) We could be re-entering ip_wput because of ip_neworute
20714 	 *    in which case we could have a IPSEC_OUT message. We
20715 	 *    need to pass through ip_wput like other datagrams and
20716 	 *    hence cannot branch to ip_wput_nondata.
20717 	 *
20718 	 * 2) ARP, AH, ESP, and other clients who are on the module
20719 	 *    instance of IP stream, give us something to deal with.
20720 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20721 	 *
20722 	 * 3) ICMP replies also could come here.
20723 	 */
20724 	ipst = ILLQ_TO_IPST(q);
20725 
20726 	if (DB_TYPE(mp) != M_DATA) {
20727 notdata:
20728 		if (DB_TYPE(mp) == M_CTL) {
20729 			/*
20730 			 * M_CTL messages are used by ARP, AH and ESP to
20731 			 * communicate with IP. We deal with IPSEC_IN and
20732 			 * IPSEC_OUT here. ip_wput_nondata handles other
20733 			 * cases.
20734 			 */
20735 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20736 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20737 				first_mp = mp->b_cont;
20738 				first_mp->b_flag &= ~MSGHASREF;
20739 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20740 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20741 				CONN_DEC_REF(connp);
20742 				connp = NULL;
20743 			}
20744 			if (ii->ipsec_info_type == IPSEC_IN) {
20745 				/*
20746 				 * Either this message goes back to
20747 				 * IPsec for further processing or to
20748 				 * ULP after policy checks.
20749 				 */
20750 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20751 				return;
20752 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20753 				io = (ipsec_out_t *)ii;
20754 				if (io->ipsec_out_proc_begin) {
20755 					/*
20756 					 * IPsec processing has already started.
20757 					 * Complete it.
20758 					 * IPQoS notes: We don't care what is
20759 					 * in ipsec_out_ill_index since this
20760 					 * won't be processed for IPQoS policies
20761 					 * in ipsec_out_process.
20762 					 */
20763 					ipsec_out_process(q, mp, NULL,
20764 					    io->ipsec_out_ill_index);
20765 					return;
20766 				} else {
20767 					connp = (q->q_next != NULL) ?
20768 					    NULL : Q_TO_CONN(q);
20769 					first_mp = mp;
20770 					mp = mp->b_cont;
20771 					mctl_present = B_TRUE;
20772 				}
20773 				zoneid = io->ipsec_out_zoneid;
20774 				ASSERT(zoneid != ALL_ZONES);
20775 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20776 				/*
20777 				 * It's an IPsec control message requesting
20778 				 * an SADB update to be sent to the IPsec
20779 				 * hardware acceleration capable ills.
20780 				 */
20781 				ipsec_ctl_t *ipsec_ctl =
20782 				    (ipsec_ctl_t *)mp->b_rptr;
20783 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20784 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20785 				mblk_t *cmp = mp->b_cont;
20786 
20787 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20788 				ASSERT(cmp != NULL);
20789 
20790 				freeb(mp);
20791 				ill_ipsec_capab_send_all(satype, cmp, sa,
20792 				    ipst->ips_netstack);
20793 				return;
20794 			} else {
20795 				/*
20796 				 * This must be ARP or special TSOL signaling.
20797 				 */
20798 				ip_wput_nondata(NULL, q, mp, NULL);
20799 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20800 				    "ip_wput_end: q %p (%S)", q, "nondata");
20801 				return;
20802 			}
20803 		} else {
20804 			/*
20805 			 * This must be non-(ARP/AH/ESP) messages.
20806 			 */
20807 			ASSERT(!need_decref);
20808 			ip_wput_nondata(NULL, q, mp, NULL);
20809 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20810 			    "ip_wput_end: q %p (%S)", q, "nondata");
20811 			return;
20812 		}
20813 	} else {
20814 		first_mp = mp;
20815 		mctl_present = B_FALSE;
20816 	}
20817 
20818 	ASSERT(first_mp != NULL);
20819 
20820 	if (mctl_present) {
20821 		io = (ipsec_out_t *)first_mp->b_rptr;
20822 		if (io->ipsec_out_ip_nexthop) {
20823 			/*
20824 			 * We may have lost the conn context if we are
20825 			 * coming here from ip_newroute(). Copy the
20826 			 * nexthop information.
20827 			 */
20828 			ip_nexthop = B_TRUE;
20829 			nexthop_addr = io->ipsec_out_nexthop_addr;
20830 
20831 			ipha = (ipha_t *)mp->b_rptr;
20832 			dst = ipha->ipha_dst;
20833 			goto send_from_ill;
20834 		}
20835 	}
20836 
20837 	ASSERT(xmit_ill == NULL);
20838 
20839 	/* We have a complete IP datagram heading outbound. */
20840 	ipha = (ipha_t *)mp->b_rptr;
20841 
20842 #ifndef SPEED_BEFORE_SAFETY
20843 	/*
20844 	 * Make sure we have a full-word aligned message and that at least
20845 	 * a simple IP header is accessible in the first message.  If not,
20846 	 * try a pullup.  For labeled systems we need to always take this
20847 	 * path as M_CTLs are "notdata" but have trailing data to process.
20848 	 */
20849 	if (!OK_32PTR(rptr) ||
20850 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20851 hdrtoosmall:
20852 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20853 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20854 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20855 			if (first_mp == NULL)
20856 				first_mp = mp;
20857 			goto discard_pkt;
20858 		}
20859 
20860 		/* This function assumes that mp points to an IPv4 packet. */
20861 		if (is_system_labeled() &&
20862 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20863 		    (connp == NULL || !connp->conn_ulp_labeled)) {
20864 			cred_t	*credp;
20865 			pid_t	pid;
20866 
20867 			if (connp != NULL) {
20868 				credp = BEST_CRED(mp, connp, &pid);
20869 				err = tsol_check_label(credp, &mp,
20870 				    connp->conn_mac_mode, ipst, pid);
20871 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
20872 				err = tsol_check_label(credp, &mp,
20873 				    CONN_MAC_DEFAULT, ipst, pid);
20874 			}
20875 			ipha = (ipha_t *)mp->b_rptr;
20876 			if (mctl_present)
20877 				first_mp->b_cont = mp;
20878 			else
20879 				first_mp = mp;
20880 			if (err != 0) {
20881 				if (err == EINVAL)
20882 					goto icmp_parameter_problem;
20883 				ip2dbg(("ip_wput: label check failed (%d)\n",
20884 				    err));
20885 				goto discard_pkt;
20886 			}
20887 		}
20888 
20889 		ipha = (ipha_t *)mp->b_rptr;
20890 		if (first_mp == NULL) {
20891 			ASSERT(xmit_ill == NULL);
20892 			/*
20893 			 * If we got here because of "goto hdrtoosmall"
20894 			 * We need to attach a IPSEC_OUT.
20895 			 */
20896 			if (connp->conn_out_enforce_policy) {
20897 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20898 				    NULL, ipha->ipha_protocol,
20899 				    ipst->ips_netstack)) == NULL)) {
20900 					BUMP_MIB(&ipst->ips_ip_mib,
20901 					    ipIfStatsOutDiscards);
20902 					if (need_decref)
20903 						CONN_DEC_REF(connp);
20904 					return;
20905 				} else {
20906 					ASSERT(mp->b_datap->db_type == M_CTL);
20907 					first_mp = mp;
20908 					mp = mp->b_cont;
20909 					mctl_present = B_TRUE;
20910 				}
20911 			} else {
20912 				first_mp = mp;
20913 				mctl_present = B_FALSE;
20914 			}
20915 		}
20916 	}
20917 #endif
20918 
20919 	/* Most of the code below is written for speed, not readability */
20920 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20921 
20922 	/*
20923 	 * If ip_newroute() fails, we're going to need a full
20924 	 * header for the icmp wraparound.
20925 	 */
20926 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20927 		uint_t	v_hlen;
20928 version_hdrlen_check:
20929 		ASSERT(first_mp != NULL);
20930 		v_hlen = V_HLEN;
20931 		/*
20932 		 * siphon off IPv6 packets coming down from transport
20933 		 * layer modules here.
20934 		 * Note: high-order bit carries NUD reachability confirmation
20935 		 */
20936 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20937 			/*
20938 			 * FIXME: assume that callers of ip_output* call
20939 			 * the right version?
20940 			 */
20941 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20942 			ASSERT(xmit_ill == NULL);
20943 			if (need_decref)
20944 				mp->b_flag |= MSGHASREF;
20945 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20946 			return;
20947 		}
20948 
20949 		if ((v_hlen >> 4) != IP_VERSION) {
20950 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20951 			    "ip_wput_end: q %p (%S)", q, "badvers");
20952 			goto discard_pkt;
20953 		}
20954 		/*
20955 		 * Is the header length at least 20 bytes?
20956 		 *
20957 		 * Are there enough bytes accessible in the header?  If
20958 		 * not, try a pullup.
20959 		 */
20960 		v_hlen &= 0xF;
20961 		v_hlen <<= 2;
20962 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20963 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20964 			    "ip_wput_end: q %p (%S)", q, "badlen");
20965 			goto discard_pkt;
20966 		}
20967 		if (v_hlen > (mp->b_wptr - rptr)) {
20968 			if (!pullupmsg(mp, v_hlen)) {
20969 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20970 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20971 				goto discard_pkt;
20972 			}
20973 			ipha = (ipha_t *)mp->b_rptr;
20974 		}
20975 		/*
20976 		 * Move first entry from any source route into ipha_dst and
20977 		 * verify the options
20978 		 */
20979 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20980 		    zoneid, ipst)) {
20981 			ASSERT(xmit_ill == NULL);
20982 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20983 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20984 			    "ip_wput_end: q %p (%S)", q, "badopts");
20985 			if (need_decref)
20986 				CONN_DEC_REF(connp);
20987 			return;
20988 		}
20989 	}
20990 	dst = ipha->ipha_dst;
20991 
20992 	/*
20993 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20994 	 * we have to run the packet through ip_newroute which will take
20995 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20996 	 * a resolver, or assigning a default gateway, etc.
20997 	 */
20998 	if (CLASSD(dst)) {
20999 		ipif_t	*ipif;
21000 		uint32_t setsrc = 0;
21001 
21002 multicast:
21003 		ASSERT(first_mp != NULL);
21004 		ip2dbg(("ip_wput: CLASSD\n"));
21005 		if (connp == NULL) {
21006 			/*
21007 			 * Use the first good ipif on the ill.
21008 			 * XXX Should this ever happen? (Appears
21009 			 * to show up with just ppp and no ethernet due
21010 			 * to in.rdisc.)
21011 			 * However, ire_send should be able to
21012 			 * call ip_wput_ire directly.
21013 			 *
21014 			 * XXX Also, this can happen for ICMP and other packets
21015 			 * with multicast source addresses.  Perhaps we should
21016 			 * fix things so that we drop the packet in question,
21017 			 * but for now, just run with it.
21018 			 */
21019 			ill_t *ill = (ill_t *)q->q_ptr;
21020 
21021 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21022 			if (ipif == NULL) {
21023 				if (need_decref)
21024 					CONN_DEC_REF(connp);
21025 				freemsg(first_mp);
21026 				return;
21027 			}
21028 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21029 			    ntohl(dst), ill->ill_name));
21030 		} else {
21031 			/*
21032 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21033 			 * and IP_MULTICAST_IF.  The block comment above this
21034 			 * function explains the locking mechanism used here.
21035 			 */
21036 			if (xmit_ill == NULL) {
21037 				xmit_ill = conn_get_held_ill(connp,
21038 				    &connp->conn_outgoing_ill, &err);
21039 				if (err == ILL_LOOKUP_FAILED) {
21040 					ip1dbg(("ip_wput: No ill for "
21041 					    "IP_BOUND_IF\n"));
21042 					BUMP_MIB(&ipst->ips_ip_mib,
21043 					    ipIfStatsOutNoRoutes);
21044 					goto drop_pkt;
21045 				}
21046 			}
21047 
21048 			if (xmit_ill == NULL) {
21049 				ipif = conn_get_held_ipif(connp,
21050 				    &connp->conn_multicast_ipif, &err);
21051 				if (err == IPIF_LOOKUP_FAILED) {
21052 					ip1dbg(("ip_wput: No ipif for "
21053 					    "multicast\n"));
21054 					BUMP_MIB(&ipst->ips_ip_mib,
21055 					    ipIfStatsOutNoRoutes);
21056 					goto drop_pkt;
21057 				}
21058 			}
21059 			if (xmit_ill != NULL) {
21060 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21061 				if (ipif == NULL) {
21062 					ip1dbg(("ip_wput: No ipif for "
21063 					    "xmit_ill\n"));
21064 					BUMP_MIB(&ipst->ips_ip_mib,
21065 					    ipIfStatsOutNoRoutes);
21066 					goto drop_pkt;
21067 				}
21068 			} else if (ipif == NULL || ipif->ipif_isv6) {
21069 				/*
21070 				 * We must do this ipif determination here
21071 				 * else we could pass through ip_newroute
21072 				 * and come back here without the conn context.
21073 				 *
21074 				 * Note: we do late binding i.e. we bind to
21075 				 * the interface when the first packet is sent.
21076 				 * For performance reasons we do not rebind on
21077 				 * each packet but keep the binding until the
21078 				 * next IP_MULTICAST_IF option.
21079 				 *
21080 				 * conn_multicast_{ipif,ill} are shared between
21081 				 * IPv4 and IPv6 and AF_INET6 sockets can
21082 				 * send both IPv4 and IPv6 packets. Hence
21083 				 * we have to check that "isv6" matches above.
21084 				 */
21085 				if (ipif != NULL)
21086 					ipif_refrele(ipif);
21087 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21088 				if (ipif == NULL) {
21089 					ip1dbg(("ip_wput: No ipif for "
21090 					    "multicast\n"));
21091 					BUMP_MIB(&ipst->ips_ip_mib,
21092 					    ipIfStatsOutNoRoutes);
21093 					goto drop_pkt;
21094 				}
21095 				err = conn_set_held_ipif(connp,
21096 				    &connp->conn_multicast_ipif, ipif);
21097 				if (err == IPIF_LOOKUP_FAILED) {
21098 					ipif_refrele(ipif);
21099 					ip1dbg(("ip_wput: No ipif for "
21100 					    "multicast\n"));
21101 					BUMP_MIB(&ipst->ips_ip_mib,
21102 					    ipIfStatsOutNoRoutes);
21103 					goto drop_pkt;
21104 				}
21105 			}
21106 		}
21107 		ASSERT(!ipif->ipif_isv6);
21108 		/*
21109 		 * As we may lose the conn by the time we reach ip_wput_ire,
21110 		 * we copy conn_multicast_loop and conn_dontroute on to an
21111 		 * ipsec_out. In case if this datagram goes out secure,
21112 		 * we need the ill_index also. Copy that also into the
21113 		 * ipsec_out.
21114 		 */
21115 		if (mctl_present) {
21116 			io = (ipsec_out_t *)first_mp->b_rptr;
21117 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21118 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21119 		} else {
21120 			ASSERT(mp == first_mp);
21121 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21122 			    BPRI_HI)) == NULL) {
21123 				ipif_refrele(ipif);
21124 				first_mp = mp;
21125 				goto discard_pkt;
21126 			}
21127 			first_mp->b_datap->db_type = M_CTL;
21128 			first_mp->b_wptr += sizeof (ipsec_info_t);
21129 			/* ipsec_out_secure is B_FALSE now */
21130 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21131 			io = (ipsec_out_t *)first_mp->b_rptr;
21132 			io->ipsec_out_type = IPSEC_OUT;
21133 			io->ipsec_out_len = sizeof (ipsec_out_t);
21134 			io->ipsec_out_use_global_policy = B_TRUE;
21135 			io->ipsec_out_ns = ipst->ips_netstack;
21136 			first_mp->b_cont = mp;
21137 			mctl_present = B_TRUE;
21138 		}
21139 
21140 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21141 		io->ipsec_out_ill_index =
21142 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21143 
21144 		if (connp != NULL) {
21145 			io->ipsec_out_multicast_loop =
21146 			    connp->conn_multicast_loop;
21147 			io->ipsec_out_dontroute = connp->conn_dontroute;
21148 			io->ipsec_out_zoneid = connp->conn_zoneid;
21149 		}
21150 		/*
21151 		 * If the application uses IP_MULTICAST_IF with
21152 		 * different logical addresses of the same ILL, we
21153 		 * need to make sure that the soruce address of
21154 		 * the packet matches the logical IP address used
21155 		 * in the option. We do it by initializing ipha_src
21156 		 * here. This should keep IPsec also happy as
21157 		 * when we return from IPsec processing, we don't
21158 		 * have to worry about getting the right address on
21159 		 * the packet. Thus it is sufficient to look for
21160 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21161 		 * MATCH_IRE_IPIF.
21162 		 *
21163 		 * NOTE : We need to do it for non-secure case also as
21164 		 * this might go out secure if there is a global policy
21165 		 * match in ip_wput_ire.
21166 		 *
21167 		 * As we do not have the ire yet, it is possible that
21168 		 * we set the source address here and then later discover
21169 		 * that the ire implies the source address to be assigned
21170 		 * through the RTF_SETSRC flag.
21171 		 * In that case, the setsrc variable will remind us
21172 		 * that overwritting the source address by the one
21173 		 * of the RTF_SETSRC-flagged ire is allowed.
21174 		 */
21175 		if (ipha->ipha_src == INADDR_ANY &&
21176 		    (connp == NULL || !connp->conn_unspec_src)) {
21177 			ipha->ipha_src = ipif->ipif_src_addr;
21178 			setsrc = RTF_SETSRC;
21179 		}
21180 		/*
21181 		 * Find an IRE which matches the destination and the outgoing
21182 		 * queue (i.e. the outgoing interface.)
21183 		 * For loopback use a unicast IP address for
21184 		 * the ire lookup.
21185 		 */
21186 		if (IS_LOOPBACK(ipif->ipif_ill))
21187 			dst = ipif->ipif_lcl_addr;
21188 
21189 		/*
21190 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21191 		 * We don't need to lookup ire in ctable as the packet
21192 		 * needs to be sent to the destination through the specified
21193 		 * ill irrespective of ires in the cache table.
21194 		 */
21195 		ire = NULL;
21196 		if (xmit_ill == NULL) {
21197 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21198 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21199 		}
21200 
21201 		if (ire == NULL) {
21202 			/*
21203 			 * Multicast loopback and multicast forwarding is
21204 			 * done in ip_wput_ire.
21205 			 *
21206 			 * Mark this packet to make it be delivered to
21207 			 * ip_wput_ire after the new ire has been
21208 			 * created.
21209 			 *
21210 			 * The call to ip_newroute_ipif takes into account
21211 			 * the setsrc reminder. In any case, we take care
21212 			 * of the RTF_MULTIRT flag.
21213 			 */
21214 			mp->b_prev = mp->b_next = NULL;
21215 			if (xmit_ill == NULL ||
21216 			    xmit_ill->ill_ipif_up_count > 0) {
21217 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21218 				    setsrc | RTF_MULTIRT, zoneid, infop);
21219 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21220 				    "ip_wput_end: q %p (%S)", q, "noire");
21221 			} else {
21222 				freemsg(first_mp);
21223 			}
21224 			ipif_refrele(ipif);
21225 			if (xmit_ill != NULL)
21226 				ill_refrele(xmit_ill);
21227 			if (need_decref)
21228 				CONN_DEC_REF(connp);
21229 			return;
21230 		}
21231 
21232 		ipif_refrele(ipif);
21233 		ipif = NULL;
21234 		ASSERT(xmit_ill == NULL);
21235 
21236 		/*
21237 		 * Honor the RTF_SETSRC flag for multicast packets,
21238 		 * if allowed by the setsrc reminder.
21239 		 */
21240 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21241 			ipha->ipha_src = ire->ire_src_addr;
21242 		}
21243 
21244 		/*
21245 		 * Unconditionally force the TTL to 1 for
21246 		 * multirouted multicast packets:
21247 		 * multirouted multicast should not cross
21248 		 * multicast routers.
21249 		 */
21250 		if (ire->ire_flags & RTF_MULTIRT) {
21251 			if (ipha->ipha_ttl > 1) {
21252 				ip2dbg(("ip_wput: forcing multicast "
21253 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21254 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21255 				ipha->ipha_ttl = 1;
21256 			}
21257 		}
21258 	} else {
21259 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21260 		if ((ire != NULL) && (ire->ire_type &
21261 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21262 			ignore_dontroute = B_TRUE;
21263 			ignore_nexthop = B_TRUE;
21264 		}
21265 		if (ire != NULL) {
21266 			ire_refrele(ire);
21267 			ire = NULL;
21268 		}
21269 		/*
21270 		 * Guard against coming in from arp in which case conn is NULL.
21271 		 * Also guard against non M_DATA with dontroute set but
21272 		 * destined to local, loopback or broadcast addresses.
21273 		 */
21274 		if (connp != NULL && connp->conn_dontroute &&
21275 		    !ignore_dontroute) {
21276 dontroute:
21277 			/*
21278 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21279 			 * routing protocols from seeing false direct
21280 			 * connectivity.
21281 			 */
21282 			ipha->ipha_ttl = 1;
21283 			/* If suitable ipif not found, drop packet */
21284 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21285 			if (dst_ipif == NULL) {
21286 noroute:
21287 				ip1dbg(("ip_wput: no route for dst using"
21288 				    " SO_DONTROUTE\n"));
21289 				BUMP_MIB(&ipst->ips_ip_mib,
21290 				    ipIfStatsOutNoRoutes);
21291 				mp->b_prev = mp->b_next = NULL;
21292 				if (first_mp == NULL)
21293 					first_mp = mp;
21294 				goto drop_pkt;
21295 			} else {
21296 				/*
21297 				 * If suitable ipif has been found, set
21298 				 * xmit_ill to the corresponding
21299 				 * ipif_ill because we'll be using the
21300 				 * send_from_ill logic below.
21301 				 */
21302 				ASSERT(xmit_ill == NULL);
21303 				xmit_ill = dst_ipif->ipif_ill;
21304 				mutex_enter(&xmit_ill->ill_lock);
21305 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21306 					mutex_exit(&xmit_ill->ill_lock);
21307 					xmit_ill = NULL;
21308 					ipif_refrele(dst_ipif);
21309 					goto noroute;
21310 				}
21311 				ill_refhold_locked(xmit_ill);
21312 				mutex_exit(&xmit_ill->ill_lock);
21313 				ipif_refrele(dst_ipif);
21314 			}
21315 		}
21316 
21317 send_from_ill:
21318 		if (xmit_ill != NULL) {
21319 			ipif_t *ipif;
21320 
21321 			/*
21322 			 * Mark this packet as originated locally
21323 			 */
21324 			mp->b_prev = mp->b_next = NULL;
21325 
21326 			/*
21327 			 * Could be SO_DONTROUTE case also.
21328 			 * Verify that at least one ipif is up on the ill.
21329 			 */
21330 			if (xmit_ill->ill_ipif_up_count == 0) {
21331 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21332 				    xmit_ill->ill_name));
21333 				goto drop_pkt;
21334 			}
21335 
21336 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21337 			if (ipif == NULL) {
21338 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21339 				    xmit_ill->ill_name));
21340 				goto drop_pkt;
21341 			}
21342 
21343 			match_flags = 0;
21344 			if (IS_UNDER_IPMP(xmit_ill))
21345 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21346 
21347 			/*
21348 			 * Look for a ire that is part of the group,
21349 			 * if found use it else call ip_newroute_ipif.
21350 			 * IPCL_ZONEID is not used for matching because
21351 			 * IP_ALLZONES option is valid only when the
21352 			 * ill is accessible from all zones i.e has a
21353 			 * valid ipif in all zones.
21354 			 */
21355 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21356 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21357 			    msg_getlabel(mp), match_flags, ipst);
21358 			/*
21359 			 * If an ire exists use it or else create
21360 			 * an ire but don't add it to the cache.
21361 			 * Adding an ire may cause issues with
21362 			 * asymmetric routing.
21363 			 * In case of multiroute always act as if
21364 			 * ire does not exist.
21365 			 */
21366 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21367 				if (ire != NULL)
21368 					ire_refrele(ire);
21369 				ip_newroute_ipif(q, first_mp, ipif,
21370 				    dst, connp, 0, zoneid, infop);
21371 				ipif_refrele(ipif);
21372 				ip1dbg(("ip_output: xmit_ill via %s\n",
21373 				    xmit_ill->ill_name));
21374 				ill_refrele(xmit_ill);
21375 				if (need_decref)
21376 					CONN_DEC_REF(connp);
21377 				return;
21378 			}
21379 			ipif_refrele(ipif);
21380 		} else if (ip_nexthop || (connp != NULL &&
21381 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21382 			if (!ip_nexthop) {
21383 				ip_nexthop = B_TRUE;
21384 				nexthop_addr = connp->conn_nexthop_v4;
21385 			}
21386 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21387 			    MATCH_IRE_GW;
21388 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21389 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21390 		} else {
21391 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21392 			    ipst);
21393 		}
21394 		if (!ire) {
21395 			if (ip_nexthop && !ignore_nexthop) {
21396 				if (mctl_present) {
21397 					io = (ipsec_out_t *)first_mp->b_rptr;
21398 					ASSERT(first_mp->b_datap->db_type ==
21399 					    M_CTL);
21400 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21401 				} else {
21402 					ASSERT(mp == first_mp);
21403 					first_mp = allocb(
21404 					    sizeof (ipsec_info_t), BPRI_HI);
21405 					if (first_mp == NULL) {
21406 						first_mp = mp;
21407 						goto discard_pkt;
21408 					}
21409 					first_mp->b_datap->db_type = M_CTL;
21410 					first_mp->b_wptr +=
21411 					    sizeof (ipsec_info_t);
21412 					/* ipsec_out_secure is B_FALSE now */
21413 					bzero(first_mp->b_rptr,
21414 					    sizeof (ipsec_info_t));
21415 					io = (ipsec_out_t *)first_mp->b_rptr;
21416 					io->ipsec_out_type = IPSEC_OUT;
21417 					io->ipsec_out_len =
21418 					    sizeof (ipsec_out_t);
21419 					io->ipsec_out_use_global_policy =
21420 					    B_TRUE;
21421 					io->ipsec_out_ns = ipst->ips_netstack;
21422 					first_mp->b_cont = mp;
21423 					mctl_present = B_TRUE;
21424 				}
21425 				io->ipsec_out_ip_nexthop = ip_nexthop;
21426 				io->ipsec_out_nexthop_addr = nexthop_addr;
21427 			}
21428 noirefound:
21429 			/*
21430 			 * Mark this packet as having originated on
21431 			 * this machine.  This will be noted in
21432 			 * ire_add_then_send, which needs to know
21433 			 * whether to run it back through ip_wput or
21434 			 * ip_rput following successful resolution.
21435 			 */
21436 			mp->b_prev = NULL;
21437 			mp->b_next = NULL;
21438 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21439 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21440 			    "ip_wput_end: q %p (%S)", q, "newroute");
21441 			if (xmit_ill != NULL)
21442 				ill_refrele(xmit_ill);
21443 			if (need_decref)
21444 				CONN_DEC_REF(connp);
21445 			return;
21446 		}
21447 	}
21448 
21449 	/* We now know where we are going with it. */
21450 
21451 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21452 	    "ip_wput_end: q %p (%S)", q, "end");
21453 
21454 	/*
21455 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21456 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21457 	 */
21458 	if (ire->ire_flags & RTF_MULTIRT) {
21459 		/*
21460 		 * Force the TTL of multirouted packets if required.
21461 		 * The TTL of such packets is bounded by the
21462 		 * ip_multirt_ttl ndd variable.
21463 		 */
21464 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21465 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21466 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21467 			    "(was %d), dst 0x%08x\n",
21468 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21469 			    ntohl(ire->ire_addr)));
21470 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21471 		}
21472 		/*
21473 		 * At this point, we check to see if there are any pending
21474 		 * unresolved routes. ire_multirt_resolvable()
21475 		 * checks in O(n) that all IRE_OFFSUBNET ire
21476 		 * entries for the packet's destination and
21477 		 * flagged RTF_MULTIRT are currently resolved.
21478 		 * If some remain unresolved, we make a copy
21479 		 * of the current message. It will be used
21480 		 * to initiate additional route resolutions.
21481 		 */
21482 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21483 		    msg_getlabel(first_mp), ipst);
21484 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21485 		    "multirt_need_resolve %d, first_mp %p\n",
21486 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21487 		if (multirt_need_resolve) {
21488 			copy_mp = copymsg(first_mp);
21489 			if (copy_mp != NULL) {
21490 				MULTIRT_DEBUG_TAG(copy_mp);
21491 			}
21492 		}
21493 	}
21494 
21495 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21496 	/*
21497 	 * Try to resolve another multiroute if
21498 	 * ire_multirt_resolvable() deemed it necessary.
21499 	 * At this point, we need to distinguish
21500 	 * multicasts from other packets. For multicasts,
21501 	 * we call ip_newroute_ipif() and request that both
21502 	 * multirouting and setsrc flags are checked.
21503 	 */
21504 	if (copy_mp != NULL) {
21505 		if (CLASSD(dst)) {
21506 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21507 			if (ipif) {
21508 				ASSERT(infop->ip_opt_ill_index == 0);
21509 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21510 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21511 				ipif_refrele(ipif);
21512 			} else {
21513 				MULTIRT_DEBUG_UNTAG(copy_mp);
21514 				freemsg(copy_mp);
21515 				copy_mp = NULL;
21516 			}
21517 		} else {
21518 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21519 		}
21520 	}
21521 	if (xmit_ill != NULL)
21522 		ill_refrele(xmit_ill);
21523 	if (need_decref)
21524 		CONN_DEC_REF(connp);
21525 	return;
21526 
21527 icmp_parameter_problem:
21528 	/* could not have originated externally */
21529 	ASSERT(mp->b_prev == NULL);
21530 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21531 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21532 		/* it's the IP header length that's in trouble */
21533 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21534 		first_mp = NULL;
21535 	}
21536 
21537 discard_pkt:
21538 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21539 drop_pkt:
21540 	ip1dbg(("ip_wput: dropped packet\n"));
21541 	if (ire != NULL)
21542 		ire_refrele(ire);
21543 	if (need_decref)
21544 		CONN_DEC_REF(connp);
21545 	freemsg(first_mp);
21546 	if (xmit_ill != NULL)
21547 		ill_refrele(xmit_ill);
21548 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21549 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21550 }
21551 
21552 /*
21553  * If this is a conn_t queue, then we pass in the conn. This includes the
21554  * zoneid.
21555  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21556  * in which case we use the global zoneid since those are all part of
21557  * the global zone.
21558  */
21559 void
21560 ip_wput(queue_t *q, mblk_t *mp)
21561 {
21562 	if (CONN_Q(q))
21563 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21564 	else
21565 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21566 }
21567 
21568 /*
21569  *
21570  * The following rules must be observed when accessing any ipif or ill
21571  * that has been cached in the conn. Typically conn_outgoing_ill,
21572  * conn_multicast_ipif and conn_multicast_ill.
21573  *
21574  * Access: The ipif or ill pointed to from the conn can be accessed under
21575  * the protection of the conn_lock or after it has been refheld under the
21576  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21577  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21578  * The reason for this is that a concurrent unplumb could actually be
21579  * cleaning up these cached pointers by walking the conns and might have
21580  * finished cleaning up the conn in question. The macros check that an
21581  * unplumb has not yet started on the ipif or ill.
21582  *
21583  * Caching: An ipif or ill pointer may be cached in the conn only after
21584  * making sure that an unplumb has not started. So the caching is done
21585  * while holding both the conn_lock and the ill_lock and after using the
21586  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21587  * flag before starting the cleanup of conns.
21588  *
21589  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21590  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21591  * or a reference to the ipif or a reference to an ire that references the
21592  * ipif. An ipif only changes its ill when migrating from an underlying ill
21593  * to an IPMP ill in ipif_up().
21594  */
21595 ipif_t *
21596 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21597 {
21598 	ipif_t	*ipif;
21599 	ill_t	*ill;
21600 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21601 
21602 	*err = 0;
21603 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21604 	mutex_enter(&connp->conn_lock);
21605 	ipif = *ipifp;
21606 	if (ipif != NULL) {
21607 		ill = ipif->ipif_ill;
21608 		mutex_enter(&ill->ill_lock);
21609 		if (IPIF_CAN_LOOKUP(ipif)) {
21610 			ipif_refhold_locked(ipif);
21611 			mutex_exit(&ill->ill_lock);
21612 			mutex_exit(&connp->conn_lock);
21613 			rw_exit(&ipst->ips_ill_g_lock);
21614 			return (ipif);
21615 		} else {
21616 			*err = IPIF_LOOKUP_FAILED;
21617 		}
21618 		mutex_exit(&ill->ill_lock);
21619 	}
21620 	mutex_exit(&connp->conn_lock);
21621 	rw_exit(&ipst->ips_ill_g_lock);
21622 	return (NULL);
21623 }
21624 
21625 ill_t *
21626 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21627 {
21628 	ill_t	*ill;
21629 
21630 	*err = 0;
21631 	mutex_enter(&connp->conn_lock);
21632 	ill = *illp;
21633 	if (ill != NULL) {
21634 		mutex_enter(&ill->ill_lock);
21635 		if (ILL_CAN_LOOKUP(ill)) {
21636 			ill_refhold_locked(ill);
21637 			mutex_exit(&ill->ill_lock);
21638 			mutex_exit(&connp->conn_lock);
21639 			return (ill);
21640 		} else {
21641 			*err = ILL_LOOKUP_FAILED;
21642 		}
21643 		mutex_exit(&ill->ill_lock);
21644 	}
21645 	mutex_exit(&connp->conn_lock);
21646 	return (NULL);
21647 }
21648 
21649 static int
21650 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21651 {
21652 	ill_t	*ill;
21653 
21654 	ill = ipif->ipif_ill;
21655 	mutex_enter(&connp->conn_lock);
21656 	mutex_enter(&ill->ill_lock);
21657 	if (IPIF_CAN_LOOKUP(ipif)) {
21658 		*ipifp = ipif;
21659 		mutex_exit(&ill->ill_lock);
21660 		mutex_exit(&connp->conn_lock);
21661 		return (0);
21662 	}
21663 	mutex_exit(&ill->ill_lock);
21664 	mutex_exit(&connp->conn_lock);
21665 	return (IPIF_LOOKUP_FAILED);
21666 }
21667 
21668 /*
21669  * This is called if the outbound datagram needs fragmentation.
21670  *
21671  * NOTE : This function does not ire_refrele the ire argument passed in.
21672  */
21673 static void
21674 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21675     ip_stack_t *ipst, conn_t *connp)
21676 {
21677 	ipha_t		*ipha;
21678 	mblk_t		*mp;
21679 	uint32_t	v_hlen_tos_len;
21680 	uint32_t	max_frag;
21681 	uint32_t	frag_flag;
21682 	boolean_t	dont_use;
21683 
21684 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21685 		mp = ipsec_mp->b_cont;
21686 	} else {
21687 		mp = ipsec_mp;
21688 	}
21689 
21690 	ipha = (ipha_t *)mp->b_rptr;
21691 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21692 
21693 #ifdef	_BIG_ENDIAN
21694 #define	V_HLEN	(v_hlen_tos_len >> 24)
21695 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21696 #else
21697 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21698 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21699 #endif
21700 
21701 #ifndef SPEED_BEFORE_SAFETY
21702 	/*
21703 	 * Check that ipha_length is consistent with
21704 	 * the mblk length
21705 	 */
21706 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21707 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21708 		    LENGTH, msgdsize(mp)));
21709 		freemsg(ipsec_mp);
21710 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21711 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21712 		    "packet length mismatch");
21713 		return;
21714 	}
21715 #endif
21716 	/*
21717 	 * Don't use frag_flag if pre-built packet or source
21718 	 * routed or if multicast (since multicast packets do not solicit
21719 	 * ICMP "packet too big" messages). Get the values of
21720 	 * max_frag and frag_flag atomically by acquiring the
21721 	 * ire_lock.
21722 	 */
21723 	mutex_enter(&ire->ire_lock);
21724 	max_frag = ire->ire_max_frag;
21725 	frag_flag = ire->ire_frag_flag;
21726 	mutex_exit(&ire->ire_lock);
21727 
21728 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21729 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21730 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21731 
21732 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21733 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21734 }
21735 
21736 /*
21737  * Used for deciding the MSS size for the upper layer. Thus
21738  * we need to check the outbound policy values in the conn.
21739  */
21740 int
21741 conn_ipsec_length(conn_t *connp)
21742 {
21743 	ipsec_latch_t *ipl;
21744 
21745 	ipl = connp->conn_latch;
21746 	if (ipl == NULL)
21747 		return (0);
21748 
21749 	if (ipl->ipl_out_policy == NULL)
21750 		return (0);
21751 
21752 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21753 }
21754 
21755 /*
21756  * Returns an estimate of the IPsec headers size. This is used if
21757  * we don't want to call into IPsec to get the exact size.
21758  */
21759 int
21760 ipsec_out_extra_length(mblk_t *ipsec_mp)
21761 {
21762 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21763 	ipsec_action_t *a;
21764 
21765 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21766 	if (!io->ipsec_out_secure)
21767 		return (0);
21768 
21769 	a = io->ipsec_out_act;
21770 
21771 	if (a == NULL) {
21772 		ASSERT(io->ipsec_out_policy != NULL);
21773 		a = io->ipsec_out_policy->ipsp_act;
21774 	}
21775 	ASSERT(a != NULL);
21776 
21777 	return (a->ipa_ovhd);
21778 }
21779 
21780 /*
21781  * Returns an estimate of the IPsec headers size. This is used if
21782  * we don't want to call into IPsec to get the exact size.
21783  */
21784 int
21785 ipsec_in_extra_length(mblk_t *ipsec_mp)
21786 {
21787 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21788 	ipsec_action_t *a;
21789 
21790 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21791 
21792 	a = ii->ipsec_in_action;
21793 	return (a == NULL ? 0 : a->ipa_ovhd);
21794 }
21795 
21796 /*
21797  * If there are any source route options, return the true final
21798  * destination. Otherwise, return the destination.
21799  */
21800 ipaddr_t
21801 ip_get_dst(ipha_t *ipha)
21802 {
21803 	ipoptp_t	opts;
21804 	uchar_t		*opt;
21805 	uint8_t		optval;
21806 	uint8_t		optlen;
21807 	ipaddr_t	dst;
21808 	uint32_t off;
21809 
21810 	dst = ipha->ipha_dst;
21811 
21812 	if (IS_SIMPLE_IPH(ipha))
21813 		return (dst);
21814 
21815 	for (optval = ipoptp_first(&opts, ipha);
21816 	    optval != IPOPT_EOL;
21817 	    optval = ipoptp_next(&opts)) {
21818 		opt = opts.ipoptp_cur;
21819 		optlen = opts.ipoptp_len;
21820 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21821 		switch (optval) {
21822 		case IPOPT_SSRR:
21823 		case IPOPT_LSRR:
21824 			off = opt[IPOPT_OFFSET];
21825 			/*
21826 			 * If one of the conditions is true, it means
21827 			 * end of options and dst already has the right
21828 			 * value.
21829 			 */
21830 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21831 				off = optlen - IP_ADDR_LEN;
21832 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21833 			}
21834 			return (dst);
21835 		default:
21836 			break;
21837 		}
21838 	}
21839 
21840 	return (dst);
21841 }
21842 
21843 mblk_t *
21844 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21845     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21846 {
21847 	ipsec_out_t	*io;
21848 	mblk_t		*first_mp;
21849 	boolean_t policy_present;
21850 	ip_stack_t	*ipst;
21851 	ipsec_stack_t	*ipss;
21852 
21853 	ASSERT(ire != NULL);
21854 	ipst = ire->ire_ipst;
21855 	ipss = ipst->ips_netstack->netstack_ipsec;
21856 
21857 	first_mp = mp;
21858 	if (mp->b_datap->db_type == M_CTL) {
21859 		io = (ipsec_out_t *)first_mp->b_rptr;
21860 		/*
21861 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21862 		 *
21863 		 * 1) There is per-socket policy (including cached global
21864 		 *    policy) or a policy on the IP-in-IP tunnel.
21865 		 * 2) There is no per-socket policy, but it is
21866 		 *    a multicast packet that needs to go out
21867 		 *    on a specific interface. This is the case
21868 		 *    where (ip_wput and ip_wput_multicast) attaches
21869 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21870 		 *
21871 		 * In case (2) we check with global policy to
21872 		 * see if there is a match and set the ill_index
21873 		 * appropriately so that we can lookup the ire
21874 		 * properly in ip_wput_ipsec_out.
21875 		 */
21876 
21877 		/*
21878 		 * ipsec_out_use_global_policy is set to B_FALSE
21879 		 * in ipsec_in_to_out(). Refer to that function for
21880 		 * details.
21881 		 */
21882 		if ((io->ipsec_out_latch == NULL) &&
21883 		    (io->ipsec_out_use_global_policy)) {
21884 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21885 			    ire, connp, unspec_src, zoneid));
21886 		}
21887 		if (!io->ipsec_out_secure) {
21888 			/*
21889 			 * If this is not a secure packet, drop
21890 			 * the IPSEC_OUT mp and treat it as a clear
21891 			 * packet. This happens when we are sending
21892 			 * a ICMP reply back to a clear packet. See
21893 			 * ipsec_in_to_out() for details.
21894 			 */
21895 			mp = first_mp->b_cont;
21896 			freeb(first_mp);
21897 		}
21898 		return (mp);
21899 	}
21900 	/*
21901 	 * See whether we need to attach a global policy here. We
21902 	 * don't depend on the conn (as it could be null) for deciding
21903 	 * what policy this datagram should go through because it
21904 	 * should have happened in ip_wput if there was some
21905 	 * policy. This normally happens for connections which are not
21906 	 * fully bound preventing us from caching policies in
21907 	 * ip_bind. Packets coming from the TCP listener/global queue
21908 	 * - which are non-hard_bound - could also be affected by
21909 	 * applying policy here.
21910 	 *
21911 	 * If this packet is coming from tcp global queue or listener,
21912 	 * we will be applying policy here.  This may not be *right*
21913 	 * if these packets are coming from the detached connection as
21914 	 * it could have gone in clear before. This happens only if a
21915 	 * TCP connection started when there is no policy and somebody
21916 	 * added policy before it became detached. Thus packets of the
21917 	 * detached connection could go out secure and the other end
21918 	 * would drop it because it will be expecting in clear. The
21919 	 * converse is not true i.e if somebody starts a TCP
21920 	 * connection and deletes the policy, all the packets will
21921 	 * still go out with the policy that existed before deleting
21922 	 * because ip_unbind sends up policy information which is used
21923 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21924 	 * TCP to attach a dummy IPSEC_OUT and set
21925 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21926 	 * affect performance for normal cases, we are not doing it.
21927 	 * Thus, set policy before starting any TCP connections.
21928 	 *
21929 	 * NOTE - We might apply policy even for a hard bound connection
21930 	 * - for which we cached policy in ip_bind - if somebody added
21931 	 * global policy after we inherited the policy in ip_bind.
21932 	 * This means that the packets that were going out in clear
21933 	 * previously would start going secure and hence get dropped
21934 	 * on the other side. To fix this, TCP attaches a dummy
21935 	 * ipsec_out and make sure that we don't apply global policy.
21936 	 */
21937 	if (ipha != NULL)
21938 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21939 	else
21940 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21941 	if (!policy_present)
21942 		return (mp);
21943 
21944 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21945 	    zoneid));
21946 }
21947 
21948 /*
21949  * This function does the ire_refrele of the ire passed in as the
21950  * argument. As this function looks up more ires i.e broadcast ires,
21951  * it needs to REFRELE them. Currently, for simplicity we don't
21952  * differentiate the one passed in and looked up here. We always
21953  * REFRELE.
21954  * IPQoS Notes:
21955  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21956  * IPsec packets are done in ipsec_out_process.
21957  */
21958 void
21959 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21960     zoneid_t zoneid)
21961 {
21962 	ipha_t		*ipha;
21963 #define	rptr	((uchar_t *)ipha)
21964 	queue_t		*stq;
21965 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21966 	uint32_t	v_hlen_tos_len;
21967 	uint32_t	ttl_protocol;
21968 	ipaddr_t	src;
21969 	ipaddr_t	dst;
21970 	uint32_t	cksum;
21971 	ipaddr_t	orig_src;
21972 	ire_t		*ire1;
21973 	mblk_t		*next_mp;
21974 	uint_t		hlen;
21975 	uint16_t	*up;
21976 	uint32_t	max_frag = ire->ire_max_frag;
21977 	ill_t		*ill = ire_to_ill(ire);
21978 	int		clusterwide;
21979 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21980 	int		ipsec_len;
21981 	mblk_t		*first_mp;
21982 	ipsec_out_t	*io;
21983 	boolean_t	conn_dontroute;		/* conn value for multicast */
21984 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21985 	boolean_t	multicast_forward;	/* Should we forward ? */
21986 	boolean_t	unspec_src;
21987 	ill_t		*conn_outgoing_ill = NULL;
21988 	ill_t		*ire_ill;
21989 	ill_t		*ire1_ill;
21990 	ill_t		*out_ill;
21991 	uint32_t 	ill_index = 0;
21992 	boolean_t	multirt_send = B_FALSE;
21993 	int		err;
21994 	ipxmit_state_t	pktxmit_state;
21995 	ip_stack_t	*ipst = ire->ire_ipst;
21996 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21997 
21998 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21999 	    "ip_wput_ire_start: q %p", q);
22000 
22001 	multicast_forward = B_FALSE;
22002 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22003 
22004 	if (ire->ire_flags & RTF_MULTIRT) {
22005 		/*
22006 		 * Multirouting case. The bucket where ire is stored
22007 		 * probably holds other RTF_MULTIRT flagged ire
22008 		 * to the destination. In this call to ip_wput_ire,
22009 		 * we attempt to send the packet through all
22010 		 * those ires. Thus, we first ensure that ire is the
22011 		 * first RTF_MULTIRT ire in the bucket,
22012 		 * before walking the ire list.
22013 		 */
22014 		ire_t *first_ire;
22015 		irb_t *irb = ire->ire_bucket;
22016 		ASSERT(irb != NULL);
22017 
22018 		/* Make sure we do not omit any multiroute ire. */
22019 		IRB_REFHOLD(irb);
22020 		for (first_ire = irb->irb_ire;
22021 		    first_ire != NULL;
22022 		    first_ire = first_ire->ire_next) {
22023 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22024 			    (first_ire->ire_addr == ire->ire_addr) &&
22025 			    !(first_ire->ire_marks &
22026 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22027 				break;
22028 		}
22029 
22030 		if ((first_ire != NULL) && (first_ire != ire)) {
22031 			IRE_REFHOLD(first_ire);
22032 			ire_refrele(ire);
22033 			ire = first_ire;
22034 			ill = ire_to_ill(ire);
22035 		}
22036 		IRB_REFRELE(irb);
22037 	}
22038 
22039 	/*
22040 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22041 	 * for performance we don't grab the mutexs in the fastpath
22042 	 */
22043 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22044 	    connp->conn_outgoing_ill != NULL) {
22045 		conn_outgoing_ill = conn_get_held_ill(connp,
22046 		    &connp->conn_outgoing_ill, &err);
22047 		if (err == ILL_LOOKUP_FAILED) {
22048 			ire_refrele(ire);
22049 			freemsg(mp);
22050 			return;
22051 		}
22052 	}
22053 
22054 	if (mp->b_datap->db_type != M_CTL) {
22055 		ipha = (ipha_t *)mp->b_rptr;
22056 	} else {
22057 		io = (ipsec_out_t *)mp->b_rptr;
22058 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22059 		ASSERT(zoneid == io->ipsec_out_zoneid);
22060 		ASSERT(zoneid != ALL_ZONES);
22061 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22062 		dst = ipha->ipha_dst;
22063 		/*
22064 		 * For the multicast case, ipsec_out carries conn_dontroute and
22065 		 * conn_multicast_loop as conn may not be available here. We
22066 		 * need this for multicast loopback and forwarding which is done
22067 		 * later in the code.
22068 		 */
22069 		if (CLASSD(dst)) {
22070 			conn_dontroute = io->ipsec_out_dontroute;
22071 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22072 			/*
22073 			 * If conn_dontroute is not set or conn_multicast_loop
22074 			 * is set, we need to do forwarding/loopback. For
22075 			 * datagrams from ip_wput_multicast, conn_dontroute is
22076 			 * set to B_TRUE and conn_multicast_loop is set to
22077 			 * B_FALSE so that we neither do forwarding nor
22078 			 * loopback.
22079 			 */
22080 			if (!conn_dontroute || conn_multicast_loop)
22081 				multicast_forward = B_TRUE;
22082 		}
22083 	}
22084 
22085 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22086 	    ire->ire_zoneid != ALL_ZONES) {
22087 		/*
22088 		 * When a zone sends a packet to another zone, we try to deliver
22089 		 * the packet under the same conditions as if the destination
22090 		 * was a real node on the network. To do so, we look for a
22091 		 * matching route in the forwarding table.
22092 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22093 		 * ip_newroute() does.
22094 		 * Note that IRE_LOCAL are special, since they are used
22095 		 * when the zoneid doesn't match in some cases. This means that
22096 		 * we need to handle ipha_src differently since ire_src_addr
22097 		 * belongs to the receiving zone instead of the sending zone.
22098 		 * When ip_restrict_interzone_loopback is set, then
22099 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22100 		 * for loopback between zones when the logical "Ethernet" would
22101 		 * have looped them back.
22102 		 */
22103 		ire_t *src_ire;
22104 
22105 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22106 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22107 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22108 		if (src_ire != NULL &&
22109 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22110 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22111 		    ire_local_same_lan(ire, src_ire))) {
22112 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22113 				ipha->ipha_src = src_ire->ire_src_addr;
22114 			ire_refrele(src_ire);
22115 		} else {
22116 			ire_refrele(ire);
22117 			if (conn_outgoing_ill != NULL)
22118 				ill_refrele(conn_outgoing_ill);
22119 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22120 			if (src_ire != NULL) {
22121 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22122 					ire_refrele(src_ire);
22123 					freemsg(mp);
22124 					return;
22125 				}
22126 				ire_refrele(src_ire);
22127 			}
22128 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22129 				/* Failed */
22130 				freemsg(mp);
22131 				return;
22132 			}
22133 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22134 			    ipst);
22135 			return;
22136 		}
22137 	}
22138 
22139 	if (mp->b_datap->db_type == M_CTL ||
22140 	    ipss->ipsec_outbound_v4_policy_present) {
22141 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22142 		    unspec_src, zoneid);
22143 		if (mp == NULL) {
22144 			ire_refrele(ire);
22145 			if (conn_outgoing_ill != NULL)
22146 				ill_refrele(conn_outgoing_ill);
22147 			return;
22148 		}
22149 		/*
22150 		 * Trusted Extensions supports all-zones interfaces, so
22151 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22152 		 * the global zone.
22153 		 */
22154 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22155 			io = (ipsec_out_t *)mp->b_rptr;
22156 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22157 			zoneid = io->ipsec_out_zoneid;
22158 		}
22159 	}
22160 
22161 	first_mp = mp;
22162 	ipsec_len = 0;
22163 
22164 	if (first_mp->b_datap->db_type == M_CTL) {
22165 		io = (ipsec_out_t *)first_mp->b_rptr;
22166 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22167 		mp = first_mp->b_cont;
22168 		ipsec_len = ipsec_out_extra_length(first_mp);
22169 		ASSERT(ipsec_len >= 0);
22170 		if (zoneid == ALL_ZONES)
22171 			zoneid = GLOBAL_ZONEID;
22172 		/* We already picked up the zoneid from the M_CTL above */
22173 		ASSERT(zoneid == io->ipsec_out_zoneid);
22174 
22175 		/*
22176 		 * Drop M_CTL here if IPsec processing is not needed.
22177 		 * (Non-IPsec use of M_CTL extracted any information it
22178 		 * needed above).
22179 		 */
22180 		if (ipsec_len == 0) {
22181 			freeb(first_mp);
22182 			first_mp = mp;
22183 		}
22184 	}
22185 
22186 	/*
22187 	 * Fast path for ip_wput_ire
22188 	 */
22189 
22190 	ipha = (ipha_t *)mp->b_rptr;
22191 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22192 	dst = ipha->ipha_dst;
22193 
22194 	/*
22195 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22196 	 * if the socket is a SOCK_RAW type. The transport checksum should
22197 	 * be provided in the pre-built packet, so we don't need to compute it.
22198 	 * Also, other application set flags, like DF, should not be altered.
22199 	 * Other transport MUST pass down zero.
22200 	 */
22201 	ip_hdr_included = ipha->ipha_ident;
22202 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22203 
22204 	if (CLASSD(dst)) {
22205 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22206 		    ntohl(dst),
22207 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22208 		    ntohl(ire->ire_addr)));
22209 	}
22210 
22211 /* Macros to extract header fields from data already in registers */
22212 #ifdef	_BIG_ENDIAN
22213 #define	V_HLEN	(v_hlen_tos_len >> 24)
22214 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22215 #define	PROTO	(ttl_protocol & 0xFF)
22216 #else
22217 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22218 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22219 #define	PROTO	(ttl_protocol >> 8)
22220 #endif
22221 
22222 	orig_src = src = ipha->ipha_src;
22223 	/* (The loop back to "another" is explained down below.) */
22224 another:;
22225 	/*
22226 	 * Assign an ident value for this packet.  We assign idents on
22227 	 * a per destination basis out of the IRE.  There could be
22228 	 * other threads targeting the same destination, so we have to
22229 	 * arrange for a atomic increment.  Note that we use a 32-bit
22230 	 * atomic add because it has better performance than its
22231 	 * 16-bit sibling.
22232 	 *
22233 	 * If running in cluster mode and if the source address
22234 	 * belongs to a replicated service then vector through
22235 	 * cl_inet_ipident vector to allocate ip identifier
22236 	 * NOTE: This is a contract private interface with the
22237 	 * clustering group.
22238 	 */
22239 	clusterwide = 0;
22240 	if (cl_inet_ipident) {
22241 		ASSERT(cl_inet_isclusterwide);
22242 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22243 
22244 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22245 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22246 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22247 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22248 			    (uint8_t *)(uintptr_t)dst, NULL);
22249 			clusterwide = 1;
22250 		}
22251 	}
22252 	if (!clusterwide) {
22253 		ipha->ipha_ident =
22254 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22255 	}
22256 
22257 #ifndef _BIG_ENDIAN
22258 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22259 #endif
22260 
22261 	/*
22262 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22263 	 * This is needed to obey conn_unspec_src when packets go through
22264 	 * ip_newroute + arp.
22265 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22266 	 */
22267 	if (src == INADDR_ANY && !unspec_src) {
22268 		/*
22269 		 * Assign the appropriate source address from the IRE if none
22270 		 * was specified.
22271 		 */
22272 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22273 
22274 		src = ire->ire_src_addr;
22275 		if (connp == NULL) {
22276 			ip1dbg(("ip_wput_ire: no connp and no src "
22277 			    "address for dst 0x%x, using src 0x%x\n",
22278 			    ntohl(dst),
22279 			    ntohl(src)));
22280 		}
22281 		ipha->ipha_src = src;
22282 	}
22283 	stq = ire->ire_stq;
22284 
22285 	/*
22286 	 * We only allow ire chains for broadcasts since there will
22287 	 * be multiple IRE_CACHE entries for the same multicast
22288 	 * address (one per ipif).
22289 	 */
22290 	next_mp = NULL;
22291 
22292 	/* broadcast packet */
22293 	if (ire->ire_type == IRE_BROADCAST)
22294 		goto broadcast;
22295 
22296 	/* loopback ? */
22297 	if (stq == NULL)
22298 		goto nullstq;
22299 
22300 	/* The ill_index for outbound ILL */
22301 	ill_index = Q_TO_INDEX(stq);
22302 
22303 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22304 	ttl_protocol = ((uint16_t *)ipha)[4];
22305 
22306 	/* pseudo checksum (do it in parts for IP header checksum) */
22307 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22308 
22309 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22310 		queue_t *dev_q = stq->q_next;
22311 
22312 		/*
22313 		 * For DIRECT_CAPABLE, we do flow control at
22314 		 * the time of sending the packet. See
22315 		 * ILL_SEND_TX().
22316 		 */
22317 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22318 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22319 			goto blocked;
22320 
22321 		if ((PROTO == IPPROTO_UDP) &&
22322 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22323 			hlen = (V_HLEN & 0xF) << 2;
22324 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22325 			if (*up != 0) {
22326 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22327 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22328 				/* Software checksum? */
22329 				if (DB_CKSUMFLAGS(mp) == 0) {
22330 					IP_STAT(ipst, ip_out_sw_cksum);
22331 					IP_STAT_UPDATE(ipst,
22332 					    ip_udp_out_sw_cksum_bytes,
22333 					    LENGTH - hlen);
22334 				}
22335 			}
22336 		}
22337 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22338 		hlen = (V_HLEN & 0xF) << 2;
22339 		if (PROTO == IPPROTO_TCP) {
22340 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22341 			/*
22342 			 * The packet header is processed once and for all, even
22343 			 * in the multirouting case. We disable hardware
22344 			 * checksum if the packet is multirouted, as it will be
22345 			 * replicated via several interfaces, and not all of
22346 			 * them may have this capability.
22347 			 */
22348 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22349 			    LENGTH, max_frag, ipsec_len, cksum);
22350 			/* Software checksum? */
22351 			if (DB_CKSUMFLAGS(mp) == 0) {
22352 				IP_STAT(ipst, ip_out_sw_cksum);
22353 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22354 				    LENGTH - hlen);
22355 			}
22356 		} else {
22357 			sctp_hdr_t	*sctph;
22358 
22359 			ASSERT(PROTO == IPPROTO_SCTP);
22360 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22361 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22362 			/*
22363 			 * Zero out the checksum field to ensure proper
22364 			 * checksum calculation.
22365 			 */
22366 			sctph->sh_chksum = 0;
22367 #ifdef	DEBUG
22368 			if (!skip_sctp_cksum)
22369 #endif
22370 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22371 		}
22372 	}
22373 
22374 	/*
22375 	 * If this is a multicast packet and originated from ip_wput
22376 	 * we need to do loopback and forwarding checks. If it comes
22377 	 * from ip_wput_multicast, we SHOULD not do this.
22378 	 */
22379 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22380 
22381 	/* checksum */
22382 	cksum += ttl_protocol;
22383 
22384 	/* fragment the packet */
22385 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22386 		goto fragmentit;
22387 	/*
22388 	 * Don't use frag_flag if packet is pre-built or source
22389 	 * routed or if multicast (since multicast packets do
22390 	 * not solicit ICMP "packet too big" messages).
22391 	 */
22392 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22393 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22394 	    !ip_source_route_included(ipha)) &&
22395 	    !CLASSD(ipha->ipha_dst))
22396 		ipha->ipha_fragment_offset_and_flags |=
22397 		    htons(ire->ire_frag_flag);
22398 
22399 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22400 		/* calculate IP header checksum */
22401 		cksum += ipha->ipha_ident;
22402 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22403 		cksum += ipha->ipha_fragment_offset_and_flags;
22404 
22405 		/* IP options present */
22406 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22407 		if (hlen)
22408 			goto checksumoptions;
22409 
22410 		/* calculate hdr checksum */
22411 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22412 		cksum = ~(cksum + (cksum >> 16));
22413 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22414 	}
22415 	if (ipsec_len != 0) {
22416 		/*
22417 		 * We will do the rest of the processing after
22418 		 * we come back from IPsec in ip_wput_ipsec_out().
22419 		 */
22420 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22421 
22422 		io = (ipsec_out_t *)first_mp->b_rptr;
22423 		io->ipsec_out_ill_index =
22424 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22425 		ipsec_out_process(q, first_mp, ire, 0);
22426 		ire_refrele(ire);
22427 		if (conn_outgoing_ill != NULL)
22428 			ill_refrele(conn_outgoing_ill);
22429 		return;
22430 	}
22431 
22432 	/*
22433 	 * In most cases, the emission loop below is entered only
22434 	 * once. Only in the case where the ire holds the
22435 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22436 	 * flagged ires in the bucket, and send the packet
22437 	 * through all crossed RTF_MULTIRT routes.
22438 	 */
22439 	if (ire->ire_flags & RTF_MULTIRT) {
22440 		multirt_send = B_TRUE;
22441 	}
22442 	do {
22443 		if (multirt_send) {
22444 			irb_t *irb;
22445 			/*
22446 			 * We are in a multiple send case, need to get
22447 			 * the next ire and make a duplicate of the packet.
22448 			 * ire1 holds here the next ire to process in the
22449 			 * bucket. If multirouting is expected,
22450 			 * any non-RTF_MULTIRT ire that has the
22451 			 * right destination address is ignored.
22452 			 */
22453 			irb = ire->ire_bucket;
22454 			ASSERT(irb != NULL);
22455 
22456 			IRB_REFHOLD(irb);
22457 			for (ire1 = ire->ire_next;
22458 			    ire1 != NULL;
22459 			    ire1 = ire1->ire_next) {
22460 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22461 					continue;
22462 				if (ire1->ire_addr != ire->ire_addr)
22463 					continue;
22464 				if (ire1->ire_marks &
22465 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22466 					continue;
22467 
22468 				/* Got one */
22469 				IRE_REFHOLD(ire1);
22470 				break;
22471 			}
22472 			IRB_REFRELE(irb);
22473 
22474 			if (ire1 != NULL) {
22475 				next_mp = copyb(mp);
22476 				if ((next_mp == NULL) ||
22477 				    ((mp->b_cont != NULL) &&
22478 				    ((next_mp->b_cont =
22479 				    dupmsg(mp->b_cont)) == NULL))) {
22480 					freemsg(next_mp);
22481 					next_mp = NULL;
22482 					ire_refrele(ire1);
22483 					ire1 = NULL;
22484 				}
22485 			}
22486 
22487 			/* Last multiroute ire; don't loop anymore. */
22488 			if (ire1 == NULL) {
22489 				multirt_send = B_FALSE;
22490 			}
22491 		}
22492 
22493 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22494 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22495 		    mblk_t *, mp);
22496 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22497 		    ipst->ips_ipv4firewall_physical_out,
22498 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22499 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22500 
22501 		if (mp == NULL)
22502 			goto release_ire_and_ill;
22503 
22504 		if (ipst->ips_ip4_observe.he_interested) {
22505 			zoneid_t szone;
22506 
22507 			/*
22508 			 * On the outbound path the destination zone will be
22509 			 * unknown as we're sending this packet out on the
22510 			 * wire.
22511 			 */
22512 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22513 			    ALL_ZONES);
22514 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22515 			    ire->ire_ipif->ipif_ill, ipst);
22516 		}
22517 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22518 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22519 
22520 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22521 
22522 		if ((pktxmit_state == SEND_FAILED) ||
22523 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22524 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22525 			    "- packet dropped\n"));
22526 release_ire_and_ill:
22527 			ire_refrele(ire);
22528 			if (next_mp != NULL) {
22529 				freemsg(next_mp);
22530 				ire_refrele(ire1);
22531 			}
22532 			if (conn_outgoing_ill != NULL)
22533 				ill_refrele(conn_outgoing_ill);
22534 			return;
22535 		}
22536 
22537 		if (CLASSD(dst)) {
22538 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22539 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22540 			    LENGTH);
22541 		}
22542 
22543 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22544 		    "ip_wput_ire_end: q %p (%S)",
22545 		    q, "last copy out");
22546 		IRE_REFRELE(ire);
22547 
22548 		if (multirt_send) {
22549 			ASSERT(ire1);
22550 			/*
22551 			 * Proceed with the next RTF_MULTIRT ire,
22552 			 * Also set up the send-to queue accordingly.
22553 			 */
22554 			ire = ire1;
22555 			ire1 = NULL;
22556 			stq = ire->ire_stq;
22557 			mp = next_mp;
22558 			next_mp = NULL;
22559 			ipha = (ipha_t *)mp->b_rptr;
22560 			ill_index = Q_TO_INDEX(stq);
22561 			ill = (ill_t *)stq->q_ptr;
22562 		}
22563 	} while (multirt_send);
22564 	if (conn_outgoing_ill != NULL)
22565 		ill_refrele(conn_outgoing_ill);
22566 	return;
22567 
22568 	/*
22569 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22570 	 */
22571 broadcast:
22572 	{
22573 		/*
22574 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22575 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22576 		 * can be overridden stack-wide through the ip_broadcast_ttl
22577 		 * ndd tunable, or on a per-connection basis through the
22578 		 * IP_BROADCAST_TTL socket option.
22579 		 *
22580 		 * In the event that we are replying to incoming ICMP packets,
22581 		 * connp could be NULL.
22582 		 */
22583 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22584 		if (connp != NULL) {
22585 			if (connp->conn_dontroute)
22586 				ipha->ipha_ttl = 1;
22587 			else if (connp->conn_broadcast_ttl != 0)
22588 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22589 		}
22590 
22591 		/*
22592 		 * Note that we are not doing a IRB_REFHOLD here.
22593 		 * Actually we don't care if the list changes i.e
22594 		 * if somebody deletes an IRE from the list while
22595 		 * we drop the lock, the next time we come around
22596 		 * ire_next will be NULL and hence we won't send
22597 		 * out multiple copies which is fine.
22598 		 */
22599 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22600 		ire1 = ire->ire_next;
22601 		if (conn_outgoing_ill != NULL) {
22602 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22603 				ASSERT(ire1 == ire->ire_next);
22604 				if (ire1 != NULL && ire1->ire_addr == dst) {
22605 					ire_refrele(ire);
22606 					ire = ire1;
22607 					IRE_REFHOLD(ire);
22608 					ire1 = ire->ire_next;
22609 					continue;
22610 				}
22611 				rw_exit(&ire->ire_bucket->irb_lock);
22612 				/* Did not find a matching ill */
22613 				ip1dbg(("ip_wput_ire: broadcast with no "
22614 				    "matching IP_BOUND_IF ill %s dst %x\n",
22615 				    conn_outgoing_ill->ill_name, dst));
22616 				freemsg(first_mp);
22617 				if (ire != NULL)
22618 					ire_refrele(ire);
22619 				ill_refrele(conn_outgoing_ill);
22620 				return;
22621 			}
22622 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22623 			/*
22624 			 * If the next IRE has the same address and is not one
22625 			 * of the two copies that we need to send, try to see
22626 			 * whether this copy should be sent at all. This
22627 			 * assumes that we insert loopbacks first and then
22628 			 * non-loopbacks. This is acheived by inserting the
22629 			 * loopback always before non-loopback.
22630 			 * This is used to send a single copy of a broadcast
22631 			 * packet out all physical interfaces that have an
22632 			 * matching IRE_BROADCAST while also looping
22633 			 * back one copy (to ip_wput_local) for each
22634 			 * matching physical interface. However, we avoid
22635 			 * sending packets out different logical that match by
22636 			 * having ipif_up/ipif_down supress duplicate
22637 			 * IRE_BROADCASTS.
22638 			 *
22639 			 * This feature is currently used to get broadcasts
22640 			 * sent to multiple interfaces, when the broadcast
22641 			 * address being used applies to multiple interfaces.
22642 			 * For example, a whole net broadcast will be
22643 			 * replicated on every connected subnet of
22644 			 * the target net.
22645 			 *
22646 			 * Each zone has its own set of IRE_BROADCASTs, so that
22647 			 * we're able to distribute inbound packets to multiple
22648 			 * zones who share a broadcast address. We avoid looping
22649 			 * back outbound packets in different zones but on the
22650 			 * same ill, as the application would see duplicates.
22651 			 *
22652 			 * This logic assumes that ire_add_v4() groups the
22653 			 * IRE_BROADCAST entries so that those with the same
22654 			 * ire_addr are kept together.
22655 			 */
22656 			ire_ill = ire->ire_ipif->ipif_ill;
22657 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22658 				while (ire1 != NULL && ire1->ire_addr == dst) {
22659 					ire1_ill = ire1->ire_ipif->ipif_ill;
22660 					if (ire1_ill != ire_ill)
22661 						break;
22662 					ire1 = ire1->ire_next;
22663 				}
22664 			}
22665 		}
22666 		ASSERT(multirt_send == B_FALSE);
22667 		if (ire1 != NULL && ire1->ire_addr == dst) {
22668 			if ((ire->ire_flags & RTF_MULTIRT) &&
22669 			    (ire1->ire_flags & RTF_MULTIRT)) {
22670 				/*
22671 				 * We are in the multirouting case.
22672 				 * The message must be sent at least
22673 				 * on both ires. These ires have been
22674 				 * inserted AFTER the standard ones
22675 				 * in ip_rt_add(). There are thus no
22676 				 * other ire entries for the destination
22677 				 * address in the rest of the bucket
22678 				 * that do not have the RTF_MULTIRT
22679 				 * flag. We don't process a copy
22680 				 * of the message here. This will be
22681 				 * done in the final sending loop.
22682 				 */
22683 				multirt_send = B_TRUE;
22684 			} else {
22685 				next_mp = ip_copymsg(first_mp);
22686 				if (next_mp != NULL)
22687 					IRE_REFHOLD(ire1);
22688 			}
22689 		}
22690 		rw_exit(&ire->ire_bucket->irb_lock);
22691 	}
22692 
22693 	if (stq) {
22694 		/*
22695 		 * A non-NULL send-to queue means this packet is going
22696 		 * out of this machine.
22697 		 */
22698 		out_ill = (ill_t *)stq->q_ptr;
22699 
22700 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22701 		ttl_protocol = ((uint16_t *)ipha)[4];
22702 		/*
22703 		 * We accumulate the pseudo header checksum in cksum.
22704 		 * This is pretty hairy code, so watch close.  One
22705 		 * thing to keep in mind is that UDP and TCP have
22706 		 * stored their respective datagram lengths in their
22707 		 * checksum fields.  This lines things up real nice.
22708 		 */
22709 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22710 		    (src >> 16) + (src & 0xFFFF);
22711 		/*
22712 		 * We assume the udp checksum field contains the
22713 		 * length, so to compute the pseudo header checksum,
22714 		 * all we need is the protocol number and src/dst.
22715 		 */
22716 		/* Provide the checksums for UDP and TCP. */
22717 		if ((PROTO == IPPROTO_TCP) &&
22718 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22719 			/* hlen gets the number of uchar_ts in the IP header */
22720 			hlen = (V_HLEN & 0xF) << 2;
22721 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22722 			IP_STAT(ipst, ip_out_sw_cksum);
22723 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22724 			    LENGTH - hlen);
22725 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22726 		} else if (PROTO == IPPROTO_SCTP &&
22727 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22728 			sctp_hdr_t	*sctph;
22729 
22730 			hlen = (V_HLEN & 0xF) << 2;
22731 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22732 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22733 			sctph->sh_chksum = 0;
22734 #ifdef	DEBUG
22735 			if (!skip_sctp_cksum)
22736 #endif
22737 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22738 		} else {
22739 			queue_t	*dev_q = stq->q_next;
22740 
22741 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22742 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22743 blocked:
22744 				ipha->ipha_ident = ip_hdr_included;
22745 				/*
22746 				 * If we don't have a conn to apply
22747 				 * backpressure, free the message.
22748 				 * In the ire_send path, we don't know
22749 				 * the position to requeue the packet. Rather
22750 				 * than reorder packets, we just drop this
22751 				 * packet.
22752 				 */
22753 				if (ipst->ips_ip_output_queue &&
22754 				    connp != NULL &&
22755 				    caller != IRE_SEND) {
22756 					if (caller == IP_WSRV) {
22757 						idl_tx_list_t *idl_txl;
22758 
22759 						idl_txl =
22760 						    &ipst->ips_idl_tx_list[0];
22761 						connp->conn_did_putbq = 1;
22762 						(void) putbq(connp->conn_wq,
22763 						    first_mp);
22764 						conn_drain_insert(connp,
22765 						    idl_txl);
22766 						/*
22767 						 * This is the service thread,
22768 						 * and the queue is already
22769 						 * noenabled. The check for
22770 						 * canput and the putbq is not
22771 						 * atomic. So we need to check
22772 						 * again.
22773 						 */
22774 						if (canput(stq->q_next))
22775 							connp->conn_did_putbq
22776 							    = 0;
22777 						IP_STAT(ipst, ip_conn_flputbq);
22778 					} else {
22779 						/*
22780 						 * We are not the service proc.
22781 						 * ip_wsrv will be scheduled or
22782 						 * is already running.
22783 						 */
22784 
22785 						(void) putq(connp->conn_wq,
22786 						    first_mp);
22787 					}
22788 				} else {
22789 					out_ill = (ill_t *)stq->q_ptr;
22790 					BUMP_MIB(out_ill->ill_ip_mib,
22791 					    ipIfStatsOutDiscards);
22792 					freemsg(first_mp);
22793 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22794 					    "ip_wput_ire_end: q %p (%S)",
22795 					    q, "discard");
22796 				}
22797 				ire_refrele(ire);
22798 				if (next_mp) {
22799 					ire_refrele(ire1);
22800 					freemsg(next_mp);
22801 				}
22802 				if (conn_outgoing_ill != NULL)
22803 					ill_refrele(conn_outgoing_ill);
22804 				return;
22805 			}
22806 			if ((PROTO == IPPROTO_UDP) &&
22807 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22808 				/*
22809 				 * hlen gets the number of uchar_ts in the
22810 				 * IP header
22811 				 */
22812 				hlen = (V_HLEN & 0xF) << 2;
22813 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22814 				max_frag = ire->ire_max_frag;
22815 				if (*up != 0) {
22816 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22817 					    up, PROTO, hlen, LENGTH, max_frag,
22818 					    ipsec_len, cksum);
22819 					/* Software checksum? */
22820 					if (DB_CKSUMFLAGS(mp) == 0) {
22821 						IP_STAT(ipst, ip_out_sw_cksum);
22822 						IP_STAT_UPDATE(ipst,
22823 						    ip_udp_out_sw_cksum_bytes,
22824 						    LENGTH - hlen);
22825 					}
22826 				}
22827 			}
22828 		}
22829 		/*
22830 		 * Need to do this even when fragmenting. The local
22831 		 * loopback can be done without computing checksums
22832 		 * but forwarding out other interface must be done
22833 		 * after the IP checksum (and ULP checksums) have been
22834 		 * computed.
22835 		 *
22836 		 * NOTE : multicast_forward is set only if this packet
22837 		 * originated from ip_wput. For packets originating from
22838 		 * ip_wput_multicast, it is not set.
22839 		 */
22840 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22841 multi_loopback:
22842 			ip2dbg(("ip_wput: multicast, loop %d\n",
22843 			    conn_multicast_loop));
22844 
22845 			/*  Forget header checksum offload */
22846 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22847 
22848 			/*
22849 			 * Local loopback of multicasts?  Check the
22850 			 * ill.
22851 			 *
22852 			 * Note that the loopback function will not come
22853 			 * in through ip_rput - it will only do the
22854 			 * client fanout thus we need to do an mforward
22855 			 * as well.  The is different from the BSD
22856 			 * logic.
22857 			 */
22858 			if (ill != NULL) {
22859 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22860 				    ALL_ZONES) != NULL) {
22861 					/*
22862 					 * Pass along the virtual output q.
22863 					 * ip_wput_local() will distribute the
22864 					 * packet to all the matching zones,
22865 					 * except the sending zone when
22866 					 * IP_MULTICAST_LOOP is false.
22867 					 */
22868 					ip_multicast_loopback(q, ill, first_mp,
22869 					    conn_multicast_loop ? 0 :
22870 					    IP_FF_NO_MCAST_LOOP, zoneid);
22871 				}
22872 			}
22873 			if (ipha->ipha_ttl == 0) {
22874 				/*
22875 				 * 0 => only to this host i.e. we are
22876 				 * done. We are also done if this was the
22877 				 * loopback interface since it is sufficient
22878 				 * to loopback one copy of a multicast packet.
22879 				 */
22880 				freemsg(first_mp);
22881 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22882 				    "ip_wput_ire_end: q %p (%S)",
22883 				    q, "loopback");
22884 				ire_refrele(ire);
22885 				if (conn_outgoing_ill != NULL)
22886 					ill_refrele(conn_outgoing_ill);
22887 				return;
22888 			}
22889 			/*
22890 			 * ILLF_MULTICAST is checked in ip_newroute
22891 			 * i.e. we don't need to check it here since
22892 			 * all IRE_CACHEs come from ip_newroute.
22893 			 * For multicast traffic, SO_DONTROUTE is interpreted
22894 			 * to mean only send the packet out the interface
22895 			 * (optionally specified with IP_MULTICAST_IF)
22896 			 * and do not forward it out additional interfaces.
22897 			 * RSVP and the rsvp daemon is an example of a
22898 			 * protocol and user level process that
22899 			 * handles it's own routing. Hence, it uses the
22900 			 * SO_DONTROUTE option to accomplish this.
22901 			 */
22902 
22903 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22904 			    ill != NULL) {
22905 				/* Unconditionally redo the checksum */
22906 				ipha->ipha_hdr_checksum = 0;
22907 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22908 
22909 				/*
22910 				 * If this needs to go out secure, we need
22911 				 * to wait till we finish the IPsec
22912 				 * processing.
22913 				 */
22914 				if (ipsec_len == 0 &&
22915 				    ip_mforward(ill, ipha, mp)) {
22916 					freemsg(first_mp);
22917 					ip1dbg(("ip_wput: mforward failed\n"));
22918 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22919 					    "ip_wput_ire_end: q %p (%S)",
22920 					    q, "mforward failed");
22921 					ire_refrele(ire);
22922 					if (conn_outgoing_ill != NULL)
22923 						ill_refrele(conn_outgoing_ill);
22924 					return;
22925 				}
22926 			}
22927 		}
22928 		max_frag = ire->ire_max_frag;
22929 		cksum += ttl_protocol;
22930 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22931 			/* No fragmentation required for this one. */
22932 			/*
22933 			 * Don't use frag_flag if packet is pre-built or source
22934 			 * routed or if multicast (since multicast packets do
22935 			 * not solicit ICMP "packet too big" messages).
22936 			 */
22937 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22938 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22939 			    !ip_source_route_included(ipha)) &&
22940 			    !CLASSD(ipha->ipha_dst))
22941 				ipha->ipha_fragment_offset_and_flags |=
22942 				    htons(ire->ire_frag_flag);
22943 
22944 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22945 				/* Complete the IP header checksum. */
22946 				cksum += ipha->ipha_ident;
22947 				cksum += (v_hlen_tos_len >> 16)+
22948 				    (v_hlen_tos_len & 0xFFFF);
22949 				cksum += ipha->ipha_fragment_offset_and_flags;
22950 				hlen = (V_HLEN & 0xF) -
22951 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22952 				if (hlen) {
22953 checksumoptions:
22954 					/*
22955 					 * Account for the IP Options in the IP
22956 					 * header checksum.
22957 					 */
22958 					up = (uint16_t *)(rptr+
22959 					    IP_SIMPLE_HDR_LENGTH);
22960 					do {
22961 						cksum += up[0];
22962 						cksum += up[1];
22963 						up += 2;
22964 					} while (--hlen);
22965 				}
22966 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22967 				cksum = ~(cksum + (cksum >> 16));
22968 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22969 			}
22970 			if (ipsec_len != 0) {
22971 				ipsec_out_process(q, first_mp, ire, ill_index);
22972 				if (!next_mp) {
22973 					ire_refrele(ire);
22974 					if (conn_outgoing_ill != NULL)
22975 						ill_refrele(conn_outgoing_ill);
22976 					return;
22977 				}
22978 				goto next;
22979 			}
22980 
22981 			/*
22982 			 * multirt_send has already been handled
22983 			 * for broadcast, but not yet for multicast
22984 			 * or IP options.
22985 			 */
22986 			if (next_mp == NULL) {
22987 				if (ire->ire_flags & RTF_MULTIRT) {
22988 					multirt_send = B_TRUE;
22989 				}
22990 			}
22991 
22992 			/*
22993 			 * In most cases, the emission loop below is
22994 			 * entered only once. Only in the case where
22995 			 * the ire holds the RTF_MULTIRT flag, do we loop
22996 			 * to process all RTF_MULTIRT ires in the bucket,
22997 			 * and send the packet through all crossed
22998 			 * RTF_MULTIRT routes.
22999 			 */
23000 			do {
23001 				if (multirt_send) {
23002 					irb_t *irb;
23003 
23004 					irb = ire->ire_bucket;
23005 					ASSERT(irb != NULL);
23006 					/*
23007 					 * We are in a multiple send case,
23008 					 * need to get the next IRE and make
23009 					 * a duplicate of the packet.
23010 					 */
23011 					IRB_REFHOLD(irb);
23012 					for (ire1 = ire->ire_next;
23013 					    ire1 != NULL;
23014 					    ire1 = ire1->ire_next) {
23015 						if (!(ire1->ire_flags &
23016 						    RTF_MULTIRT))
23017 							continue;
23018 
23019 						if (ire1->ire_addr !=
23020 						    ire->ire_addr)
23021 							continue;
23022 
23023 						if (ire1->ire_marks &
23024 						    (IRE_MARK_CONDEMNED |
23025 						    IRE_MARK_TESTHIDDEN))
23026 							continue;
23027 
23028 						/* Got one */
23029 						IRE_REFHOLD(ire1);
23030 						break;
23031 					}
23032 					IRB_REFRELE(irb);
23033 
23034 					if (ire1 != NULL) {
23035 						next_mp = copyb(mp);
23036 						if ((next_mp == NULL) ||
23037 						    ((mp->b_cont != NULL) &&
23038 						    ((next_mp->b_cont =
23039 						    dupmsg(mp->b_cont))
23040 						    == NULL))) {
23041 							freemsg(next_mp);
23042 							next_mp = NULL;
23043 							ire_refrele(ire1);
23044 							ire1 = NULL;
23045 						}
23046 					}
23047 
23048 					/*
23049 					 * Last multiroute ire; don't loop
23050 					 * anymore. The emission is over
23051 					 * and next_mp is NULL.
23052 					 */
23053 					if (ire1 == NULL) {
23054 						multirt_send = B_FALSE;
23055 					}
23056 				}
23057 
23058 				out_ill = ire_to_ill(ire);
23059 				DTRACE_PROBE4(ip4__physical__out__start,
23060 				    ill_t *, NULL,
23061 				    ill_t *, out_ill,
23062 				    ipha_t *, ipha, mblk_t *, mp);
23063 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23064 				    ipst->ips_ipv4firewall_physical_out,
23065 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23066 				DTRACE_PROBE1(ip4__physical__out__end,
23067 				    mblk_t *, mp);
23068 				if (mp == NULL)
23069 					goto release_ire_and_ill_2;
23070 
23071 				ASSERT(ipsec_len == 0);
23072 				mp->b_prev =
23073 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23074 				DTRACE_PROBE2(ip__xmit__2,
23075 				    mblk_t *, mp, ire_t *, ire);
23076 				pktxmit_state = ip_xmit_v4(mp, ire,
23077 				    NULL, B_TRUE, connp);
23078 				if ((pktxmit_state == SEND_FAILED) ||
23079 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23080 release_ire_and_ill_2:
23081 					if (next_mp) {
23082 						freemsg(next_mp);
23083 						ire_refrele(ire1);
23084 					}
23085 					ire_refrele(ire);
23086 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23087 					    "ip_wput_ire_end: q %p (%S)",
23088 					    q, "discard MDATA");
23089 					if (conn_outgoing_ill != NULL)
23090 						ill_refrele(conn_outgoing_ill);
23091 					return;
23092 				}
23093 
23094 				if (CLASSD(dst)) {
23095 					BUMP_MIB(out_ill->ill_ip_mib,
23096 					    ipIfStatsHCOutMcastPkts);
23097 					UPDATE_MIB(out_ill->ill_ip_mib,
23098 					    ipIfStatsHCOutMcastOctets,
23099 					    LENGTH);
23100 				} else if (ire->ire_type == IRE_BROADCAST) {
23101 					BUMP_MIB(out_ill->ill_ip_mib,
23102 					    ipIfStatsHCOutBcastPkts);
23103 				}
23104 
23105 				if (multirt_send) {
23106 					/*
23107 					 * We are in a multiple send case,
23108 					 * need to re-enter the sending loop
23109 					 * using the next ire.
23110 					 */
23111 					ire_refrele(ire);
23112 					ire = ire1;
23113 					stq = ire->ire_stq;
23114 					mp = next_mp;
23115 					next_mp = NULL;
23116 					ipha = (ipha_t *)mp->b_rptr;
23117 					ill_index = Q_TO_INDEX(stq);
23118 				}
23119 			} while (multirt_send);
23120 
23121 			if (!next_mp) {
23122 				/*
23123 				 * Last copy going out (the ultra-common
23124 				 * case).  Note that we intentionally replicate
23125 				 * the putnext rather than calling it before
23126 				 * the next_mp check in hopes of a little
23127 				 * tail-call action out of the compiler.
23128 				 */
23129 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23130 				    "ip_wput_ire_end: q %p (%S)",
23131 				    q, "last copy out(1)");
23132 				ire_refrele(ire);
23133 				if (conn_outgoing_ill != NULL)
23134 					ill_refrele(conn_outgoing_ill);
23135 				return;
23136 			}
23137 			/* More copies going out below. */
23138 		} else {
23139 			int offset;
23140 fragmentit:
23141 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23142 			/*
23143 			 * If this would generate a icmp_frag_needed message,
23144 			 * we need to handle it before we do the IPsec
23145 			 * processing. Otherwise, we need to strip the IPsec
23146 			 * headers before we send up the message to the ULPs
23147 			 * which becomes messy and difficult.
23148 			 */
23149 			if (ipsec_len != 0) {
23150 				if ((max_frag < (unsigned int)(LENGTH +
23151 				    ipsec_len)) && (offset & IPH_DF)) {
23152 					out_ill = (ill_t *)stq->q_ptr;
23153 					BUMP_MIB(out_ill->ill_ip_mib,
23154 					    ipIfStatsOutFragFails);
23155 					BUMP_MIB(out_ill->ill_ip_mib,
23156 					    ipIfStatsOutFragReqds);
23157 					ipha->ipha_hdr_checksum = 0;
23158 					ipha->ipha_hdr_checksum =
23159 					    (uint16_t)ip_csum_hdr(ipha);
23160 					icmp_frag_needed(ire->ire_stq, first_mp,
23161 					    max_frag, zoneid, ipst);
23162 					if (!next_mp) {
23163 						ire_refrele(ire);
23164 						if (conn_outgoing_ill != NULL) {
23165 							ill_refrele(
23166 							    conn_outgoing_ill);
23167 						}
23168 						return;
23169 					}
23170 				} else {
23171 					/*
23172 					 * This won't cause a icmp_frag_needed
23173 					 * message. to be generated. Send it on
23174 					 * the wire. Note that this could still
23175 					 * cause fragmentation and all we
23176 					 * do is the generation of the message
23177 					 * to the ULP if needed before IPsec.
23178 					 */
23179 					if (!next_mp) {
23180 						ipsec_out_process(q, first_mp,
23181 						    ire, ill_index);
23182 						TRACE_2(TR_FAC_IP,
23183 						    TR_IP_WPUT_IRE_END,
23184 						    "ip_wput_ire_end: q %p "
23185 						    "(%S)", q,
23186 						    "last ipsec_out_process");
23187 						ire_refrele(ire);
23188 						if (conn_outgoing_ill != NULL) {
23189 							ill_refrele(
23190 							    conn_outgoing_ill);
23191 						}
23192 						return;
23193 					}
23194 					ipsec_out_process(q, first_mp,
23195 					    ire, ill_index);
23196 				}
23197 			} else {
23198 				/*
23199 				 * Initiate IPPF processing. For
23200 				 * fragmentable packets we finish
23201 				 * all QOS packet processing before
23202 				 * calling:
23203 				 * ip_wput_ire_fragmentit->ip_wput_frag
23204 				 */
23205 
23206 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23207 					ip_process(IPP_LOCAL_OUT, &mp,
23208 					    ill_index);
23209 					if (mp == NULL) {
23210 						out_ill = (ill_t *)stq->q_ptr;
23211 						BUMP_MIB(out_ill->ill_ip_mib,
23212 						    ipIfStatsOutDiscards);
23213 						if (next_mp != NULL) {
23214 							freemsg(next_mp);
23215 							ire_refrele(ire1);
23216 						}
23217 						ire_refrele(ire);
23218 						TRACE_2(TR_FAC_IP,
23219 						    TR_IP_WPUT_IRE_END,
23220 						    "ip_wput_ire: q %p (%S)",
23221 						    q, "discard MDATA");
23222 						if (conn_outgoing_ill != NULL) {
23223 							ill_refrele(
23224 							    conn_outgoing_ill);
23225 						}
23226 						return;
23227 					}
23228 				}
23229 				if (!next_mp) {
23230 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23231 					    "ip_wput_ire_end: q %p (%S)",
23232 					    q, "last fragmentation");
23233 					ip_wput_ire_fragmentit(mp, ire,
23234 					    zoneid, ipst, connp);
23235 					ire_refrele(ire);
23236 					if (conn_outgoing_ill != NULL)
23237 						ill_refrele(conn_outgoing_ill);
23238 					return;
23239 				}
23240 				ip_wput_ire_fragmentit(mp, ire,
23241 				    zoneid, ipst, connp);
23242 			}
23243 		}
23244 	} else {
23245 nullstq:
23246 		/* A NULL stq means the destination address is local. */
23247 		UPDATE_OB_PKT_COUNT(ire);
23248 		ire->ire_last_used_time = lbolt;
23249 		ASSERT(ire->ire_ipif != NULL);
23250 		if (!next_mp) {
23251 			/*
23252 			 * Is there an "in" and "out" for traffic local
23253 			 * to a host (loopback)?  The code in Solaris doesn't
23254 			 * explicitly draw a line in its code for in vs out,
23255 			 * so we've had to draw a line in the sand: ip_wput_ire
23256 			 * is considered to be the "output" side and
23257 			 * ip_wput_local to be the "input" side.
23258 			 */
23259 			out_ill = ire_to_ill(ire);
23260 
23261 			/*
23262 			 * DTrace this as ip:::send.  A blocked packet will
23263 			 * fire the send probe, but not the receive probe.
23264 			 */
23265 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23266 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23267 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23268 
23269 			DTRACE_PROBE4(ip4__loopback__out__start,
23270 			    ill_t *, NULL, ill_t *, out_ill,
23271 			    ipha_t *, ipha, mblk_t *, first_mp);
23272 
23273 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23274 			    ipst->ips_ipv4firewall_loopback_out,
23275 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23276 
23277 			DTRACE_PROBE1(ip4__loopback__out_end,
23278 			    mblk_t *, first_mp);
23279 
23280 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23281 			    "ip_wput_ire_end: q %p (%S)",
23282 			    q, "local address");
23283 
23284 			if (first_mp != NULL)
23285 				ip_wput_local(q, out_ill, ipha,
23286 				    first_mp, ire, 0, ire->ire_zoneid);
23287 			ire_refrele(ire);
23288 			if (conn_outgoing_ill != NULL)
23289 				ill_refrele(conn_outgoing_ill);
23290 			return;
23291 		}
23292 
23293 		out_ill = ire_to_ill(ire);
23294 
23295 		/*
23296 		 * DTrace this as ip:::send.  A blocked packet will fire the
23297 		 * send probe, but not the receive probe.
23298 		 */
23299 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23300 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23301 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23302 
23303 		DTRACE_PROBE4(ip4__loopback__out__start,
23304 		    ill_t *, NULL, ill_t *, out_ill,
23305 		    ipha_t *, ipha, mblk_t *, first_mp);
23306 
23307 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23308 		    ipst->ips_ipv4firewall_loopback_out,
23309 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23310 
23311 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23312 
23313 		if (first_mp != NULL)
23314 			ip_wput_local(q, out_ill, ipha,
23315 			    first_mp, ire, 0, ire->ire_zoneid);
23316 	}
23317 next:
23318 	/*
23319 	 * More copies going out to additional interfaces.
23320 	 * ire1 has already been held. We don't need the
23321 	 * "ire" anymore.
23322 	 */
23323 	ire_refrele(ire);
23324 	ire = ire1;
23325 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23326 	mp = next_mp;
23327 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23328 	ill = ire_to_ill(ire);
23329 	first_mp = mp;
23330 	if (ipsec_len != 0) {
23331 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23332 		mp = mp->b_cont;
23333 	}
23334 	dst = ire->ire_addr;
23335 	ipha = (ipha_t *)mp->b_rptr;
23336 	/*
23337 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23338 	 * Restore ipha_ident "no checksum" flag.
23339 	 */
23340 	src = orig_src;
23341 	ipha->ipha_ident = ip_hdr_included;
23342 	goto another;
23343 
23344 #undef	rptr
23345 #undef	Q_TO_INDEX
23346 }
23347 
23348 /*
23349  * Routine to allocate a message that is used to notify the ULP about MDT.
23350  * The caller may provide a pointer to the link-layer MDT capabilities,
23351  * or NULL if MDT is to be disabled on the stream.
23352  */
23353 mblk_t *
23354 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23355 {
23356 	mblk_t *mp;
23357 	ip_mdt_info_t *mdti;
23358 	ill_mdt_capab_t *idst;
23359 
23360 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23361 		DB_TYPE(mp) = M_CTL;
23362 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23363 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23364 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23365 		idst = &(mdti->mdt_capab);
23366 
23367 		/*
23368 		 * If the caller provides us with the capability, copy
23369 		 * it over into our notification message; otherwise
23370 		 * we zero out the capability portion.
23371 		 */
23372 		if (isrc != NULL)
23373 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23374 		else
23375 			bzero((caddr_t)idst, sizeof (*idst));
23376 	}
23377 	return (mp);
23378 }
23379 
23380 /*
23381  * Routine which determines whether MDT can be enabled on the destination
23382  * IRE and IPC combination, and if so, allocates and returns the MDT
23383  * notification mblk that may be used by ULP.  We also check if we need to
23384  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23385  * MDT usage in the past have been lifted.  This gets called during IP
23386  * and ULP binding.
23387  */
23388 mblk_t *
23389 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23390     ill_mdt_capab_t *mdt_cap)
23391 {
23392 	mblk_t *mp;
23393 	boolean_t rc = B_FALSE;
23394 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23395 
23396 	ASSERT(dst_ire != NULL);
23397 	ASSERT(connp != NULL);
23398 	ASSERT(mdt_cap != NULL);
23399 
23400 	/*
23401 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23402 	 * Multidata, which is handled in tcp_multisend().  This
23403 	 * is the reason why we do all these checks here, to ensure
23404 	 * that we don't enable Multidata for the cases which we
23405 	 * can't handle at the moment.
23406 	 */
23407 	do {
23408 		/* Only do TCP at the moment */
23409 		if (connp->conn_ulp != IPPROTO_TCP)
23410 			break;
23411 
23412 		/*
23413 		 * IPsec outbound policy present?  Note that we get here
23414 		 * after calling ipsec_conn_cache_policy() where the global
23415 		 * policy checking is performed.  conn_latch will be
23416 		 * non-NULL as long as there's a policy defined,
23417 		 * i.e. conn_out_enforce_policy may be NULL in such case
23418 		 * when the connection is non-secure, and hence we check
23419 		 * further if the latch refers to an outbound policy.
23420 		 */
23421 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23422 			break;
23423 
23424 		/* CGTP (multiroute) is enabled? */
23425 		if (dst_ire->ire_flags & RTF_MULTIRT)
23426 			break;
23427 
23428 		/* Outbound IPQoS enabled? */
23429 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23430 			/*
23431 			 * In this case, we disable MDT for this and all
23432 			 * future connections going over the interface.
23433 			 */
23434 			mdt_cap->ill_mdt_on = 0;
23435 			break;
23436 		}
23437 
23438 		/* socket option(s) present? */
23439 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23440 			break;
23441 
23442 		rc = B_TRUE;
23443 	/* CONSTCOND */
23444 	} while (0);
23445 
23446 	/* Remember the result */
23447 	connp->conn_mdt_ok = rc;
23448 
23449 	if (!rc)
23450 		return (NULL);
23451 	else if (!mdt_cap->ill_mdt_on) {
23452 		/*
23453 		 * If MDT has been previously turned off in the past, and we
23454 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23455 		 * then enable it for this interface.
23456 		 */
23457 		mdt_cap->ill_mdt_on = 1;
23458 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23459 		    "interface %s\n", ill_name));
23460 	}
23461 
23462 	/* Allocate the MDT info mblk */
23463 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23464 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23465 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23466 		return (NULL);
23467 	}
23468 	return (mp);
23469 }
23470 
23471 /*
23472  * Routine to allocate a message that is used to notify the ULP about LSO.
23473  * The caller may provide a pointer to the link-layer LSO capabilities,
23474  * or NULL if LSO is to be disabled on the stream.
23475  */
23476 mblk_t *
23477 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23478 {
23479 	mblk_t *mp;
23480 	ip_lso_info_t *lsoi;
23481 	ill_lso_capab_t *idst;
23482 
23483 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23484 		DB_TYPE(mp) = M_CTL;
23485 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23486 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23487 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23488 		idst = &(lsoi->lso_capab);
23489 
23490 		/*
23491 		 * If the caller provides us with the capability, copy
23492 		 * it over into our notification message; otherwise
23493 		 * we zero out the capability portion.
23494 		 */
23495 		if (isrc != NULL)
23496 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23497 		else
23498 			bzero((caddr_t)idst, sizeof (*idst));
23499 	}
23500 	return (mp);
23501 }
23502 
23503 /*
23504  * Routine which determines whether LSO can be enabled on the destination
23505  * IRE and IPC combination, and if so, allocates and returns the LSO
23506  * notification mblk that may be used by ULP.  We also check if we need to
23507  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23508  * LSO usage in the past have been lifted.  This gets called during IP
23509  * and ULP binding.
23510  */
23511 mblk_t *
23512 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23513     ill_lso_capab_t *lso_cap)
23514 {
23515 	mblk_t *mp;
23516 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23517 
23518 	ASSERT(dst_ire != NULL);
23519 	ASSERT(connp != NULL);
23520 	ASSERT(lso_cap != NULL);
23521 
23522 	connp->conn_lso_ok = B_TRUE;
23523 
23524 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23525 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23526 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23527 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23528 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23529 		connp->conn_lso_ok = B_FALSE;
23530 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23531 			/*
23532 			 * Disable LSO for this and all future connections going
23533 			 * over the interface.
23534 			 */
23535 			lso_cap->ill_lso_on = 0;
23536 		}
23537 	}
23538 
23539 	if (!connp->conn_lso_ok)
23540 		return (NULL);
23541 	else if (!lso_cap->ill_lso_on) {
23542 		/*
23543 		 * If LSO has been previously turned off in the past, and we
23544 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23545 		 * then enable it for this interface.
23546 		 */
23547 		lso_cap->ill_lso_on = 1;
23548 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23549 		    ill_name));
23550 	}
23551 
23552 	/* Allocate the LSO info mblk */
23553 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23554 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23555 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23556 
23557 	return (mp);
23558 }
23559 
23560 /*
23561  * Create destination address attribute, and fill it with the physical
23562  * destination address and SAP taken from the template DL_UNITDATA_REQ
23563  * message block.
23564  */
23565 boolean_t
23566 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23567 {
23568 	dl_unitdata_req_t *dlurp;
23569 	pattr_t *pa;
23570 	pattrinfo_t pa_info;
23571 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23572 	uint_t das_len, das_off;
23573 
23574 	ASSERT(dlmp != NULL);
23575 
23576 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23577 	das_len = dlurp->dl_dest_addr_length;
23578 	das_off = dlurp->dl_dest_addr_offset;
23579 
23580 	pa_info.type = PATTR_DSTADDRSAP;
23581 	pa_info.len = sizeof (**das) + das_len - 1;
23582 
23583 	/* create and associate the attribute */
23584 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23585 	if (pa != NULL) {
23586 		ASSERT(*das != NULL);
23587 		(*das)->addr_is_group = 0;
23588 		(*das)->addr_len = (uint8_t)das_len;
23589 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23590 	}
23591 
23592 	return (pa != NULL);
23593 }
23594 
23595 /*
23596  * Create hardware checksum attribute and fill it with the values passed.
23597  */
23598 boolean_t
23599 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23600     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23601 {
23602 	pattr_t *pa;
23603 	pattrinfo_t pa_info;
23604 
23605 	ASSERT(mmd != NULL);
23606 
23607 	pa_info.type = PATTR_HCKSUM;
23608 	pa_info.len = sizeof (pattr_hcksum_t);
23609 
23610 	/* create and associate the attribute */
23611 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23612 	if (pa != NULL) {
23613 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23614 
23615 		hck->hcksum_start_offset = start_offset;
23616 		hck->hcksum_stuff_offset = stuff_offset;
23617 		hck->hcksum_end_offset = end_offset;
23618 		hck->hcksum_flags = flags;
23619 	}
23620 	return (pa != NULL);
23621 }
23622 
23623 /*
23624  * Create zerocopy attribute and fill it with the specified flags
23625  */
23626 boolean_t
23627 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23628 {
23629 	pattr_t *pa;
23630 	pattrinfo_t pa_info;
23631 
23632 	ASSERT(mmd != NULL);
23633 	pa_info.type = PATTR_ZCOPY;
23634 	pa_info.len = sizeof (pattr_zcopy_t);
23635 
23636 	/* create and associate the attribute */
23637 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23638 	if (pa != NULL) {
23639 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23640 
23641 		zcopy->zcopy_flags = flags;
23642 	}
23643 	return (pa != NULL);
23644 }
23645 
23646 /*
23647  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23648  * block chain. We could rewrite to handle arbitrary message block chains but
23649  * that would make the code complicated and slow. Right now there three
23650  * restrictions:
23651  *
23652  *   1. The first message block must contain the complete IP header and
23653  *	at least 1 byte of payload data.
23654  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23655  *	so that we can use a single Multidata message.
23656  *   3. No frag must be distributed over two or more message blocks so
23657  *	that we don't need more than two packet descriptors per frag.
23658  *
23659  * The above restrictions allow us to support userland applications (which
23660  * will send down a single message block) and NFS over UDP (which will
23661  * send down a chain of at most three message blocks).
23662  *
23663  * We also don't use MDT for payloads with less than or equal to
23664  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23665  */
23666 boolean_t
23667 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23668 {
23669 	int	blocks;
23670 	ssize_t	total, missing, size;
23671 
23672 	ASSERT(mp != NULL);
23673 	ASSERT(hdr_len > 0);
23674 
23675 	size = MBLKL(mp) - hdr_len;
23676 	if (size <= 0)
23677 		return (B_FALSE);
23678 
23679 	/* The first mblk contains the header and some payload. */
23680 	blocks = 1;
23681 	total = size;
23682 	size %= len;
23683 	missing = (size == 0) ? 0 : (len - size);
23684 	mp = mp->b_cont;
23685 
23686 	while (mp != NULL) {
23687 		/*
23688 		 * Give up if we encounter a zero length message block.
23689 		 * In practice, this should rarely happen and therefore
23690 		 * not worth the trouble of freeing and re-linking the
23691 		 * mblk from the chain to handle such case.
23692 		 */
23693 		if ((size = MBLKL(mp)) == 0)
23694 			return (B_FALSE);
23695 
23696 		/* Too many payload buffers for a single Multidata message? */
23697 		if (++blocks > MULTIDATA_MAX_PBUFS)
23698 			return (B_FALSE);
23699 
23700 		total += size;
23701 		/* Is a frag distributed over two or more message blocks? */
23702 		if (missing > size)
23703 			return (B_FALSE);
23704 		size -= missing;
23705 
23706 		size %= len;
23707 		missing = (size == 0) ? 0 : (len - size);
23708 
23709 		mp = mp->b_cont;
23710 	}
23711 
23712 	return (total > ip_wput_frag_mdt_min);
23713 }
23714 
23715 /*
23716  * Outbound IPv4 fragmentation routine using MDT.
23717  */
23718 static void
23719 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23720     uint32_t frag_flag, int offset)
23721 {
23722 	ipha_t		*ipha_orig;
23723 	int		i1, ip_data_end;
23724 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23725 	mblk_t		*hdr_mp, *md_mp = NULL;
23726 	unsigned char	*hdr_ptr, *pld_ptr;
23727 	multidata_t	*mmd;
23728 	ip_pdescinfo_t	pdi;
23729 	ill_t		*ill;
23730 	ip_stack_t	*ipst = ire->ire_ipst;
23731 
23732 	ASSERT(DB_TYPE(mp) == M_DATA);
23733 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23734 
23735 	ill = ire_to_ill(ire);
23736 	ASSERT(ill != NULL);
23737 
23738 	ipha_orig = (ipha_t *)mp->b_rptr;
23739 	mp->b_rptr += sizeof (ipha_t);
23740 
23741 	/* Calculate how many packets we will send out */
23742 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23743 	pkts = (i1 + len - 1) / len;
23744 	ASSERT(pkts > 1);
23745 
23746 	/* Allocate a message block which will hold all the IP Headers. */
23747 	wroff = ipst->ips_ip_wroff_extra;
23748 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23749 
23750 	i1 = pkts * hdr_chunk_len;
23751 	/*
23752 	 * Create the header buffer, Multidata and destination address
23753 	 * and SAP attribute that should be associated with it.
23754 	 */
23755 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23756 	    ((hdr_mp->b_wptr += i1),
23757 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23758 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23759 		freemsg(mp);
23760 		if (md_mp == NULL) {
23761 			freemsg(hdr_mp);
23762 		} else {
23763 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23764 			freemsg(md_mp);
23765 		}
23766 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23767 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23768 		return;
23769 	}
23770 	IP_STAT(ipst, ip_frag_mdt_allocd);
23771 
23772 	/*
23773 	 * Add a payload buffer to the Multidata; this operation must not
23774 	 * fail, or otherwise our logic in this routine is broken.  There
23775 	 * is no memory allocation done by the routine, so any returned
23776 	 * failure simply tells us that we've done something wrong.
23777 	 *
23778 	 * A failure tells us that either we're adding the same payload
23779 	 * buffer more than once, or we're trying to add more buffers than
23780 	 * allowed.  None of the above cases should happen, and we panic
23781 	 * because either there's horrible heap corruption, and/or
23782 	 * programming mistake.
23783 	 */
23784 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23785 		goto pbuf_panic;
23786 
23787 	hdr_ptr = hdr_mp->b_rptr;
23788 	pld_ptr = mp->b_rptr;
23789 
23790 	/* Establish the ending byte offset, based on the starting offset. */
23791 	offset <<= 3;
23792 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23793 	    IP_SIMPLE_HDR_LENGTH;
23794 
23795 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23796 
23797 	while (pld_ptr < mp->b_wptr) {
23798 		ipha_t		*ipha;
23799 		uint16_t	offset_and_flags;
23800 		uint16_t	ip_len;
23801 		int		error;
23802 
23803 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23804 		ipha = (ipha_t *)(hdr_ptr + wroff);
23805 		ASSERT(OK_32PTR(ipha));
23806 		*ipha = *ipha_orig;
23807 
23808 		if (ip_data_end - offset > len) {
23809 			offset_and_flags = IPH_MF;
23810 		} else {
23811 			/*
23812 			 * Last frag. Set len to the length of this last piece.
23813 			 */
23814 			len = ip_data_end - offset;
23815 			/* A frag of a frag might have IPH_MF non-zero */
23816 			offset_and_flags =
23817 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23818 			    IPH_MF;
23819 		}
23820 		offset_and_flags |= (uint16_t)(offset >> 3);
23821 		offset_and_flags |= (uint16_t)frag_flag;
23822 		/* Store the offset and flags in the IP header. */
23823 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23824 
23825 		/* Store the length in the IP header. */
23826 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23827 		ipha->ipha_length = htons(ip_len);
23828 
23829 		/*
23830 		 * Set the IP header checksum.  Note that mp is just
23831 		 * the header, so this is easy to pass to ip_csum.
23832 		 */
23833 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23834 
23835 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23836 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23837 		    NULL, int, 0);
23838 
23839 		/*
23840 		 * Record offset and size of header and data of the next packet
23841 		 * in the multidata message.
23842 		 */
23843 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23844 		PDESC_PLD_INIT(&pdi);
23845 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23846 		ASSERT(i1 > 0);
23847 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23848 		if (i1 == len) {
23849 			pld_ptr += len;
23850 		} else {
23851 			i1 = len - i1;
23852 			mp = mp->b_cont;
23853 			ASSERT(mp != NULL);
23854 			ASSERT(MBLKL(mp) >= i1);
23855 			/*
23856 			 * Attach the next payload message block to the
23857 			 * multidata message.
23858 			 */
23859 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23860 				goto pbuf_panic;
23861 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23862 			pld_ptr = mp->b_rptr + i1;
23863 		}
23864 
23865 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23866 		    KM_NOSLEEP)) == NULL) {
23867 			/*
23868 			 * Any failure other than ENOMEM indicates that we
23869 			 * have passed in invalid pdesc info or parameters
23870 			 * to mmd_addpdesc, which must not happen.
23871 			 *
23872 			 * EINVAL is a result of failure on boundary checks
23873 			 * against the pdesc info contents.  It should not
23874 			 * happen, and we panic because either there's
23875 			 * horrible heap corruption, and/or programming
23876 			 * mistake.
23877 			 */
23878 			if (error != ENOMEM) {
23879 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23880 				    "pdesc logic error detected for "
23881 				    "mmd %p pinfo %p (%d)\n",
23882 				    (void *)mmd, (void *)&pdi, error);
23883 				/* NOTREACHED */
23884 			}
23885 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23886 			/* Free unattached payload message blocks as well */
23887 			md_mp->b_cont = mp->b_cont;
23888 			goto free_mmd;
23889 		}
23890 
23891 		/* Advance fragment offset. */
23892 		offset += len;
23893 
23894 		/* Advance to location for next header in the buffer. */
23895 		hdr_ptr += hdr_chunk_len;
23896 
23897 		/* Did we reach the next payload message block? */
23898 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23899 			mp = mp->b_cont;
23900 			/*
23901 			 * Attach the next message block with payload
23902 			 * data to the multidata message.
23903 			 */
23904 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23905 				goto pbuf_panic;
23906 			pld_ptr = mp->b_rptr;
23907 		}
23908 	}
23909 
23910 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23911 	ASSERT(mp->b_wptr == pld_ptr);
23912 
23913 	/* Update IP statistics */
23914 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23915 
23916 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23917 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23918 
23919 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23920 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23921 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23922 
23923 	if (pkt_type == OB_PKT) {
23924 		ire->ire_ob_pkt_count += pkts;
23925 		if (ire->ire_ipif != NULL)
23926 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23927 	} else {
23928 		/* The type is IB_PKT in the forwarding path. */
23929 		ire->ire_ib_pkt_count += pkts;
23930 		ASSERT(!IRE_IS_LOCAL(ire));
23931 		if (ire->ire_type & IRE_BROADCAST) {
23932 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23933 		} else {
23934 			UPDATE_MIB(ill->ill_ip_mib,
23935 			    ipIfStatsHCOutForwDatagrams, pkts);
23936 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23937 		}
23938 	}
23939 	ire->ire_last_used_time = lbolt;
23940 	/* Send it down */
23941 	putnext(ire->ire_stq, md_mp);
23942 	return;
23943 
23944 pbuf_panic:
23945 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23946 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23947 	    pbuf_idx);
23948 	/* NOTREACHED */
23949 }
23950 
23951 /*
23952  * Outbound IP fragmentation routine.
23953  *
23954  * NOTE : This routine does not ire_refrele the ire that is passed in
23955  * as the argument.
23956  */
23957 static void
23958 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23959     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
23960 {
23961 	int		i1;
23962 	mblk_t		*ll_hdr_mp;
23963 	int 		ll_hdr_len;
23964 	int		hdr_len;
23965 	mblk_t		*hdr_mp;
23966 	ipha_t		*ipha;
23967 	int		ip_data_end;
23968 	int		len;
23969 	mblk_t		*mp = mp_orig, *mp1;
23970 	int		offset;
23971 	queue_t		*q;
23972 	uint32_t	v_hlen_tos_len;
23973 	mblk_t		*first_mp;
23974 	boolean_t	mctl_present;
23975 	ill_t		*ill;
23976 	ill_t		*out_ill;
23977 	mblk_t		*xmit_mp;
23978 	mblk_t		*carve_mp;
23979 	ire_t		*ire1 = NULL;
23980 	ire_t		*save_ire = NULL;
23981 	mblk_t  	*next_mp = NULL;
23982 	boolean_t	last_frag = B_FALSE;
23983 	boolean_t	multirt_send = B_FALSE;
23984 	ire_t		*first_ire = NULL;
23985 	irb_t		*irb = NULL;
23986 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23987 
23988 	ill = ire_to_ill(ire);
23989 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
23990 
23991 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23992 
23993 	if (max_frag == 0) {
23994 		ip1dbg(("ip_wput_frag: ire frag size is 0"
23995 		    " -  dropping packet\n"));
23996 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23997 		freemsg(mp);
23998 		return;
23999 	}
24000 
24001 	/*
24002 	 * IPsec does not allow hw accelerated packets to be fragmented
24003 	 * This check is made in ip_wput_ipsec_out prior to coming here
24004 	 * via ip_wput_ire_fragmentit.
24005 	 *
24006 	 * If at this point we have an ire whose ARP request has not
24007 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24008 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24009 	 * This packet and all fragmentable packets for this ire will
24010 	 * continue to get dropped while ire_nce->nce_state remains in
24011 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24012 	 * ND_REACHABLE, all subsquent large packets for this ire will
24013 	 * get fragemented and sent out by this function.
24014 	 */
24015 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24016 		/* If nce_state is ND_INITIAL, trigger ARP query */
24017 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24018 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24019 		    " -  dropping packet\n"));
24020 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24021 		freemsg(mp);
24022 		return;
24023 	}
24024 
24025 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24026 	    "ip_wput_frag_start:");
24027 
24028 	if (mp->b_datap->db_type == M_CTL) {
24029 		first_mp = mp;
24030 		mp_orig = mp = mp->b_cont;
24031 		mctl_present = B_TRUE;
24032 	} else {
24033 		first_mp = mp;
24034 		mctl_present = B_FALSE;
24035 	}
24036 
24037 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24038 	ipha = (ipha_t *)mp->b_rptr;
24039 
24040 	/*
24041 	 * If the Don't Fragment flag is on, generate an ICMP destination
24042 	 * unreachable, fragmentation needed.
24043 	 */
24044 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24045 	if (offset & IPH_DF) {
24046 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24047 		if (is_system_labeled()) {
24048 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24049 			    ire->ire_max_frag - max_frag, AF_INET);
24050 		}
24051 		/*
24052 		 * Need to compute hdr checksum if called from ip_wput_ire.
24053 		 * Note that ip_rput_forward verifies the checksum before
24054 		 * calling this routine so in that case this is a noop.
24055 		 */
24056 		ipha->ipha_hdr_checksum = 0;
24057 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24058 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24059 		    ipst);
24060 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24061 		    "ip_wput_frag_end:(%S)",
24062 		    "don't fragment");
24063 		return;
24064 	}
24065 	/*
24066 	 * Labeled systems adjust max_frag if they add a label
24067 	 * to send the correct path mtu.  We need the real mtu since we
24068 	 * are fragmenting the packet after label adjustment.
24069 	 */
24070 	if (is_system_labeled())
24071 		max_frag = ire->ire_max_frag;
24072 	if (mctl_present)
24073 		freeb(first_mp);
24074 	/*
24075 	 * Establish the starting offset.  May not be zero if we are fragging
24076 	 * a fragment that is being forwarded.
24077 	 */
24078 	offset = offset & IPH_OFFSET;
24079 
24080 	/* TODO why is this test needed? */
24081 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24082 	if (((max_frag - LENGTH) & ~7) < 8) {
24083 		/* TODO: notify ulp somehow */
24084 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24085 		freemsg(mp);
24086 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24087 		    "ip_wput_frag_end:(%S)",
24088 		    "len < 8");
24089 		return;
24090 	}
24091 
24092 	hdr_len = (V_HLEN & 0xF) << 2;
24093 
24094 	ipha->ipha_hdr_checksum = 0;
24095 
24096 	/*
24097 	 * Establish the number of bytes maximum per frag, after putting
24098 	 * in the header.
24099 	 */
24100 	len = (max_frag - hdr_len) & ~7;
24101 
24102 	/* Check if we can use MDT to send out the frags. */
24103 	ASSERT(!IRE_IS_LOCAL(ire));
24104 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24105 	    ipst->ips_ip_multidata_outbound &&
24106 	    !(ire->ire_flags & RTF_MULTIRT) &&
24107 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24108 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24109 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24110 		ASSERT(ill->ill_mdt_capab != NULL);
24111 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24112 			/*
24113 			 * If MDT has been previously turned off in the past,
24114 			 * and we currently can do MDT (due to IPQoS policy
24115 			 * removal, etc.) then enable it for this interface.
24116 			 */
24117 			ill->ill_mdt_capab->ill_mdt_on = 1;
24118 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24119 			    ill->ill_name));
24120 		}
24121 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24122 		    offset);
24123 		return;
24124 	}
24125 
24126 	/* Get a copy of the header for the trailing frags */
24127 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24128 	    mp);
24129 	if (!hdr_mp) {
24130 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24131 		freemsg(mp);
24132 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24133 		    "ip_wput_frag_end:(%S)",
24134 		    "couldn't copy hdr");
24135 		return;
24136 	}
24137 
24138 	/* Store the starting offset, with the MoreFrags flag. */
24139 	i1 = offset | IPH_MF | frag_flag;
24140 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24141 
24142 	/* Establish the ending byte offset, based on the starting offset. */
24143 	offset <<= 3;
24144 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24145 
24146 	/* Store the length of the first fragment in the IP header. */
24147 	i1 = len + hdr_len;
24148 	ASSERT(i1 <= IP_MAXPACKET);
24149 	ipha->ipha_length = htons((uint16_t)i1);
24150 
24151 	/*
24152 	 * Compute the IP header checksum for the first frag.  We have to
24153 	 * watch out that we stop at the end of the header.
24154 	 */
24155 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24156 
24157 	/*
24158 	 * Now carve off the first frag.  Note that this will include the
24159 	 * original IP header.
24160 	 */
24161 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24162 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24163 		freeb(hdr_mp);
24164 		freemsg(mp_orig);
24165 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24166 		    "ip_wput_frag_end:(%S)",
24167 		    "couldn't carve first");
24168 		return;
24169 	}
24170 
24171 	/*
24172 	 * Multirouting case. Each fragment is replicated
24173 	 * via all non-condemned RTF_MULTIRT routes
24174 	 * currently resolved.
24175 	 * We ensure that first_ire is the first RTF_MULTIRT
24176 	 * ire in the bucket.
24177 	 */
24178 	if (ire->ire_flags & RTF_MULTIRT) {
24179 		irb = ire->ire_bucket;
24180 		ASSERT(irb != NULL);
24181 
24182 		multirt_send = B_TRUE;
24183 
24184 		/* Make sure we do not omit any multiroute ire. */
24185 		IRB_REFHOLD(irb);
24186 		for (first_ire = irb->irb_ire;
24187 		    first_ire != NULL;
24188 		    first_ire = first_ire->ire_next) {
24189 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24190 			    (first_ire->ire_addr == ire->ire_addr) &&
24191 			    !(first_ire->ire_marks &
24192 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24193 				break;
24194 		}
24195 
24196 		if (first_ire != NULL) {
24197 			if (first_ire != ire) {
24198 				IRE_REFHOLD(first_ire);
24199 				/*
24200 				 * Do not release the ire passed in
24201 				 * as the argument.
24202 				 */
24203 				ire = first_ire;
24204 			} else {
24205 				first_ire = NULL;
24206 			}
24207 		}
24208 		IRB_REFRELE(irb);
24209 
24210 		/*
24211 		 * Save the first ire; we will need to restore it
24212 		 * for the trailing frags.
24213 		 * We REFHOLD save_ire, as each iterated ire will be
24214 		 * REFRELEd.
24215 		 */
24216 		save_ire = ire;
24217 		IRE_REFHOLD(save_ire);
24218 	}
24219 
24220 	/*
24221 	 * First fragment emission loop.
24222 	 * In most cases, the emission loop below is entered only
24223 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24224 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24225 	 * bucket, and send the fragment through all crossed
24226 	 * RTF_MULTIRT routes.
24227 	 */
24228 	do {
24229 		if (ire->ire_flags & RTF_MULTIRT) {
24230 			/*
24231 			 * We are in a multiple send case, need to get
24232 			 * the next ire and make a copy of the packet.
24233 			 * ire1 holds here the next ire to process in the
24234 			 * bucket. If multirouting is expected,
24235 			 * any non-RTF_MULTIRT ire that has the
24236 			 * right destination address is ignored.
24237 			 *
24238 			 * We have to take into account the MTU of
24239 			 * each walked ire. max_frag is set by the
24240 			 * the caller and generally refers to
24241 			 * the primary ire entry. Here we ensure that
24242 			 * no route with a lower MTU will be used, as
24243 			 * fragments are carved once for all ires,
24244 			 * then replicated.
24245 			 */
24246 			ASSERT(irb != NULL);
24247 			IRB_REFHOLD(irb);
24248 			for (ire1 = ire->ire_next;
24249 			    ire1 != NULL;
24250 			    ire1 = ire1->ire_next) {
24251 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24252 					continue;
24253 				if (ire1->ire_addr != ire->ire_addr)
24254 					continue;
24255 				if (ire1->ire_marks &
24256 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24257 					continue;
24258 				/*
24259 				 * Ensure we do not exceed the MTU
24260 				 * of the next route.
24261 				 */
24262 				if (ire1->ire_max_frag < max_frag) {
24263 					ip_multirt_bad_mtu(ire1, max_frag);
24264 					continue;
24265 				}
24266 
24267 				/* Got one. */
24268 				IRE_REFHOLD(ire1);
24269 				break;
24270 			}
24271 			IRB_REFRELE(irb);
24272 
24273 			if (ire1 != NULL) {
24274 				next_mp = copyb(mp);
24275 				if ((next_mp == NULL) ||
24276 				    ((mp->b_cont != NULL) &&
24277 				    ((next_mp->b_cont =
24278 				    dupmsg(mp->b_cont)) == NULL))) {
24279 					freemsg(next_mp);
24280 					next_mp = NULL;
24281 					ire_refrele(ire1);
24282 					ire1 = NULL;
24283 				}
24284 			}
24285 
24286 			/* Last multiroute ire; don't loop anymore. */
24287 			if (ire1 == NULL) {
24288 				multirt_send = B_FALSE;
24289 			}
24290 		}
24291 
24292 		ll_hdr_len = 0;
24293 		LOCK_IRE_FP_MP(ire);
24294 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24295 		if (ll_hdr_mp != NULL) {
24296 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24297 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24298 		} else {
24299 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24300 		}
24301 
24302 		/* If there is a transmit header, get a copy for this frag. */
24303 		/*
24304 		 * TODO: should check db_ref before calling ip_carve_mp since
24305 		 * it might give us a dup.
24306 		 */
24307 		if (!ll_hdr_mp) {
24308 			/* No xmit header. */
24309 			xmit_mp = mp;
24310 
24311 		/* We have a link-layer header that can fit in our mblk. */
24312 		} else if (mp->b_datap->db_ref == 1 &&
24313 		    ll_hdr_len != 0 &&
24314 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24315 			/* M_DATA fastpath */
24316 			mp->b_rptr -= ll_hdr_len;
24317 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24318 			xmit_mp = mp;
24319 
24320 		/* Corner case if copyb has failed */
24321 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24322 			UNLOCK_IRE_FP_MP(ire);
24323 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24324 			freeb(hdr_mp);
24325 			freemsg(mp);
24326 			freemsg(mp_orig);
24327 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24328 			    "ip_wput_frag_end:(%S)",
24329 			    "discard");
24330 
24331 			if (multirt_send) {
24332 				ASSERT(ire1);
24333 				ASSERT(next_mp);
24334 
24335 				freemsg(next_mp);
24336 				ire_refrele(ire1);
24337 			}
24338 			if (save_ire != NULL)
24339 				IRE_REFRELE(save_ire);
24340 
24341 			if (first_ire != NULL)
24342 				ire_refrele(first_ire);
24343 			return;
24344 
24345 		/*
24346 		 * Case of res_mp OR the fastpath mp can't fit
24347 		 * in the mblk
24348 		 */
24349 		} else {
24350 			xmit_mp->b_cont = mp;
24351 
24352 			/*
24353 			 * Get priority marking, if any.
24354 			 * We propagate the CoS marking from the
24355 			 * original packet that went to QoS processing
24356 			 * in ip_wput_ire to the newly carved mp.
24357 			 */
24358 			if (DB_TYPE(xmit_mp) == M_DATA)
24359 				xmit_mp->b_band = mp->b_band;
24360 		}
24361 		UNLOCK_IRE_FP_MP(ire);
24362 
24363 		q = ire->ire_stq;
24364 		out_ill = (ill_t *)q->q_ptr;
24365 
24366 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24367 
24368 		DTRACE_PROBE4(ip4__physical__out__start,
24369 		    ill_t *, NULL, ill_t *, out_ill,
24370 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24371 
24372 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24373 		    ipst->ips_ipv4firewall_physical_out,
24374 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24375 
24376 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24377 
24378 		if (xmit_mp != NULL) {
24379 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24380 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24381 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24382 
24383 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24384 
24385 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24386 			UPDATE_MIB(out_ill->ill_ip_mib,
24387 			    ipIfStatsHCOutOctets, i1);
24388 
24389 			if (pkt_type != OB_PKT) {
24390 				/*
24391 				 * Update the packet count and MIB stats
24392 				 * of trailing RTF_MULTIRT ires.
24393 				 */
24394 				UPDATE_OB_PKT_COUNT(ire);
24395 				BUMP_MIB(out_ill->ill_ip_mib,
24396 				    ipIfStatsOutFragReqds);
24397 			}
24398 		}
24399 
24400 		if (multirt_send) {
24401 			/*
24402 			 * We are in a multiple send case; look for
24403 			 * the next ire and re-enter the loop.
24404 			 */
24405 			ASSERT(ire1);
24406 			ASSERT(next_mp);
24407 			/* REFRELE the current ire before looping */
24408 			ire_refrele(ire);
24409 			ire = ire1;
24410 			ire1 = NULL;
24411 			mp = next_mp;
24412 			next_mp = NULL;
24413 		}
24414 	} while (multirt_send);
24415 
24416 	ASSERT(ire1 == NULL);
24417 
24418 	/* Restore the original ire; we need it for the trailing frags */
24419 	if (save_ire != NULL) {
24420 		/* REFRELE the last iterated ire */
24421 		ire_refrele(ire);
24422 		/* save_ire has been REFHOLDed */
24423 		ire = save_ire;
24424 		save_ire = NULL;
24425 		q = ire->ire_stq;
24426 	}
24427 
24428 	if (pkt_type == OB_PKT) {
24429 		UPDATE_OB_PKT_COUNT(ire);
24430 	} else {
24431 		out_ill = (ill_t *)q->q_ptr;
24432 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24433 		UPDATE_IB_PKT_COUNT(ire);
24434 	}
24435 
24436 	/* Advance the offset to the second frag starting point. */
24437 	offset += len;
24438 	/*
24439 	 * Update hdr_len from the copied header - there might be less options
24440 	 * in the later fragments.
24441 	 */
24442 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24443 	/* Loop until done. */
24444 	for (;;) {
24445 		uint16_t	offset_and_flags;
24446 		uint16_t	ip_len;
24447 
24448 		if (ip_data_end - offset > len) {
24449 			/*
24450 			 * Carve off the appropriate amount from the original
24451 			 * datagram.
24452 			 */
24453 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24454 				mp = NULL;
24455 				break;
24456 			}
24457 			/*
24458 			 * More frags after this one.  Get another copy
24459 			 * of the header.
24460 			 */
24461 			if (carve_mp->b_datap->db_ref == 1 &&
24462 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24463 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24464 				/* Inline IP header */
24465 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24466 				    hdr_mp->b_rptr;
24467 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24468 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24469 				mp = carve_mp;
24470 			} else {
24471 				if (!(mp = copyb(hdr_mp))) {
24472 					freemsg(carve_mp);
24473 					break;
24474 				}
24475 				/* Get priority marking, if any. */
24476 				mp->b_band = carve_mp->b_band;
24477 				mp->b_cont = carve_mp;
24478 			}
24479 			ipha = (ipha_t *)mp->b_rptr;
24480 			offset_and_flags = IPH_MF;
24481 		} else {
24482 			/*
24483 			 * Last frag.  Consume the header. Set len to
24484 			 * the length of this last piece.
24485 			 */
24486 			len = ip_data_end - offset;
24487 
24488 			/*
24489 			 * Carve off the appropriate amount from the original
24490 			 * datagram.
24491 			 */
24492 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24493 				mp = NULL;
24494 				break;
24495 			}
24496 			if (carve_mp->b_datap->db_ref == 1 &&
24497 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24498 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24499 				/* Inline IP header */
24500 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24501 				    hdr_mp->b_rptr;
24502 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24503 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24504 				mp = carve_mp;
24505 				freeb(hdr_mp);
24506 				hdr_mp = mp;
24507 			} else {
24508 				mp = hdr_mp;
24509 				/* Get priority marking, if any. */
24510 				mp->b_band = carve_mp->b_band;
24511 				mp->b_cont = carve_mp;
24512 			}
24513 			ipha = (ipha_t *)mp->b_rptr;
24514 			/* A frag of a frag might have IPH_MF non-zero */
24515 			offset_and_flags =
24516 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24517 			    IPH_MF;
24518 		}
24519 		offset_and_flags |= (uint16_t)(offset >> 3);
24520 		offset_and_flags |= (uint16_t)frag_flag;
24521 		/* Store the offset and flags in the IP header. */
24522 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24523 
24524 		/* Store the length in the IP header. */
24525 		ip_len = (uint16_t)(len + hdr_len);
24526 		ipha->ipha_length = htons(ip_len);
24527 
24528 		/*
24529 		 * Set the IP header checksum.	Note that mp is just
24530 		 * the header, so this is easy to pass to ip_csum.
24531 		 */
24532 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24533 
24534 		/* Attach a transmit header, if any, and ship it. */
24535 		if (pkt_type == OB_PKT) {
24536 			UPDATE_OB_PKT_COUNT(ire);
24537 		} else {
24538 			out_ill = (ill_t *)q->q_ptr;
24539 			BUMP_MIB(out_ill->ill_ip_mib,
24540 			    ipIfStatsHCOutForwDatagrams);
24541 			UPDATE_IB_PKT_COUNT(ire);
24542 		}
24543 
24544 		if (ire->ire_flags & RTF_MULTIRT) {
24545 			irb = ire->ire_bucket;
24546 			ASSERT(irb != NULL);
24547 
24548 			multirt_send = B_TRUE;
24549 
24550 			/*
24551 			 * Save the original ire; we will need to restore it
24552 			 * for the tailing frags.
24553 			 */
24554 			save_ire = ire;
24555 			IRE_REFHOLD(save_ire);
24556 		}
24557 		/*
24558 		 * Emission loop for this fragment, similar
24559 		 * to what is done for the first fragment.
24560 		 */
24561 		do {
24562 			if (multirt_send) {
24563 				/*
24564 				 * We are in a multiple send case, need to get
24565 				 * the next ire and make a copy of the packet.
24566 				 */
24567 				ASSERT(irb != NULL);
24568 				IRB_REFHOLD(irb);
24569 				for (ire1 = ire->ire_next;
24570 				    ire1 != NULL;
24571 				    ire1 = ire1->ire_next) {
24572 					if (!(ire1->ire_flags & RTF_MULTIRT))
24573 						continue;
24574 					if (ire1->ire_addr != ire->ire_addr)
24575 						continue;
24576 					if (ire1->ire_marks &
24577 					    (IRE_MARK_CONDEMNED |
24578 					    IRE_MARK_TESTHIDDEN))
24579 						continue;
24580 					/*
24581 					 * Ensure we do not exceed the MTU
24582 					 * of the next route.
24583 					 */
24584 					if (ire1->ire_max_frag < max_frag) {
24585 						ip_multirt_bad_mtu(ire1,
24586 						    max_frag);
24587 						continue;
24588 					}
24589 
24590 					/* Got one. */
24591 					IRE_REFHOLD(ire1);
24592 					break;
24593 				}
24594 				IRB_REFRELE(irb);
24595 
24596 				if (ire1 != NULL) {
24597 					next_mp = copyb(mp);
24598 					if ((next_mp == NULL) ||
24599 					    ((mp->b_cont != NULL) &&
24600 					    ((next_mp->b_cont =
24601 					    dupmsg(mp->b_cont)) == NULL))) {
24602 						freemsg(next_mp);
24603 						next_mp = NULL;
24604 						ire_refrele(ire1);
24605 						ire1 = NULL;
24606 					}
24607 				}
24608 
24609 				/* Last multiroute ire; don't loop anymore. */
24610 				if (ire1 == NULL) {
24611 					multirt_send = B_FALSE;
24612 				}
24613 			}
24614 
24615 			/* Update transmit header */
24616 			ll_hdr_len = 0;
24617 			LOCK_IRE_FP_MP(ire);
24618 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24619 			if (ll_hdr_mp != NULL) {
24620 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24621 				ll_hdr_len = MBLKL(ll_hdr_mp);
24622 			} else {
24623 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24624 			}
24625 
24626 			if (!ll_hdr_mp) {
24627 				xmit_mp = mp;
24628 
24629 			/*
24630 			 * We have link-layer header that can fit in
24631 			 * our mblk.
24632 			 */
24633 			} else if (mp->b_datap->db_ref == 1 &&
24634 			    ll_hdr_len != 0 &&
24635 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24636 				/* M_DATA fastpath */
24637 				mp->b_rptr -= ll_hdr_len;
24638 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24639 				    ll_hdr_len);
24640 				xmit_mp = mp;
24641 
24642 			/*
24643 			 * Case of res_mp OR the fastpath mp can't fit
24644 			 * in the mblk
24645 			 */
24646 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24647 				xmit_mp->b_cont = mp;
24648 				/* Get priority marking, if any. */
24649 				if (DB_TYPE(xmit_mp) == M_DATA)
24650 					xmit_mp->b_band = mp->b_band;
24651 
24652 			/* Corner case if copyb failed */
24653 			} else {
24654 				/*
24655 				 * Exit both the replication and
24656 				 * fragmentation loops.
24657 				 */
24658 				UNLOCK_IRE_FP_MP(ire);
24659 				goto drop_pkt;
24660 			}
24661 			UNLOCK_IRE_FP_MP(ire);
24662 
24663 			mp1 = mp;
24664 			out_ill = (ill_t *)q->q_ptr;
24665 
24666 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24667 
24668 			DTRACE_PROBE4(ip4__physical__out__start,
24669 			    ill_t *, NULL, ill_t *, out_ill,
24670 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24671 
24672 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24673 			    ipst->ips_ipv4firewall_physical_out,
24674 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24675 
24676 			DTRACE_PROBE1(ip4__physical__out__end,
24677 			    mblk_t *, xmit_mp);
24678 
24679 			if (mp != mp1 && hdr_mp == mp1)
24680 				hdr_mp = mp;
24681 			if (mp != mp1 && mp_orig == mp1)
24682 				mp_orig = mp;
24683 
24684 			if (xmit_mp != NULL) {
24685 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24686 				    NULL, void_ip_t *, ipha,
24687 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24688 				    ipha, ip6_t *, NULL, int, 0);
24689 
24690 				ILL_SEND_TX(out_ill, ire, connp,
24691 				    xmit_mp, 0, connp);
24692 
24693 				BUMP_MIB(out_ill->ill_ip_mib,
24694 				    ipIfStatsHCOutTransmits);
24695 				UPDATE_MIB(out_ill->ill_ip_mib,
24696 				    ipIfStatsHCOutOctets, ip_len);
24697 
24698 				if (pkt_type != OB_PKT) {
24699 					/*
24700 					 * Update the packet count of trailing
24701 					 * RTF_MULTIRT ires.
24702 					 */
24703 					UPDATE_OB_PKT_COUNT(ire);
24704 				}
24705 			}
24706 
24707 			/* All done if we just consumed the hdr_mp. */
24708 			if (mp == hdr_mp) {
24709 				last_frag = B_TRUE;
24710 				BUMP_MIB(out_ill->ill_ip_mib,
24711 				    ipIfStatsOutFragOKs);
24712 			}
24713 
24714 			if (multirt_send) {
24715 				/*
24716 				 * We are in a multiple send case; look for
24717 				 * the next ire and re-enter the loop.
24718 				 */
24719 				ASSERT(ire1);
24720 				ASSERT(next_mp);
24721 				/* REFRELE the current ire before looping */
24722 				ire_refrele(ire);
24723 				ire = ire1;
24724 				ire1 = NULL;
24725 				q = ire->ire_stq;
24726 				mp = next_mp;
24727 				next_mp = NULL;
24728 			}
24729 		} while (multirt_send);
24730 		/*
24731 		 * Restore the original ire; we need it for the
24732 		 * trailing frags
24733 		 */
24734 		if (save_ire != NULL) {
24735 			ASSERT(ire1 == NULL);
24736 			/* REFRELE the last iterated ire */
24737 			ire_refrele(ire);
24738 			/* save_ire has been REFHOLDed */
24739 			ire = save_ire;
24740 			q = ire->ire_stq;
24741 			save_ire = NULL;
24742 		}
24743 
24744 		if (last_frag) {
24745 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24746 			    "ip_wput_frag_end:(%S)",
24747 			    "consumed hdr_mp");
24748 
24749 			if (first_ire != NULL)
24750 				ire_refrele(first_ire);
24751 			return;
24752 		}
24753 		/* Otherwise, advance and loop. */
24754 		offset += len;
24755 	}
24756 
24757 drop_pkt:
24758 	/* Clean up following allocation failure. */
24759 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24760 	freemsg(mp);
24761 	if (mp != hdr_mp)
24762 		freeb(hdr_mp);
24763 	if (mp != mp_orig)
24764 		freemsg(mp_orig);
24765 
24766 	if (save_ire != NULL)
24767 		IRE_REFRELE(save_ire);
24768 	if (first_ire != NULL)
24769 		ire_refrele(first_ire);
24770 
24771 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24772 	    "ip_wput_frag_end:(%S)",
24773 	    "end--alloc failure");
24774 }
24775 
24776 /*
24777  * Copy the header plus those options which have the copy bit set
24778  * src is the template to make sure we preserve the cred for TX purposes.
24779  */
24780 static mblk_t *
24781 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24782     mblk_t *src)
24783 {
24784 	mblk_t	*mp;
24785 	uchar_t	*up;
24786 
24787 	/*
24788 	 * Quick check if we need to look for options without the copy bit
24789 	 * set
24790 	 */
24791 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24792 	if (!mp)
24793 		return (mp);
24794 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24795 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24796 		bcopy(rptr, mp->b_rptr, hdr_len);
24797 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24798 		return (mp);
24799 	}
24800 	up  = mp->b_rptr;
24801 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24802 	up += IP_SIMPLE_HDR_LENGTH;
24803 	rptr += IP_SIMPLE_HDR_LENGTH;
24804 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24805 	while (hdr_len > 0) {
24806 		uint32_t optval;
24807 		uint32_t optlen;
24808 
24809 		optval = *rptr;
24810 		if (optval == IPOPT_EOL)
24811 			break;
24812 		if (optval == IPOPT_NOP)
24813 			optlen = 1;
24814 		else
24815 			optlen = rptr[1];
24816 		if (optval & IPOPT_COPY) {
24817 			bcopy(rptr, up, optlen);
24818 			up += optlen;
24819 		}
24820 		rptr += optlen;
24821 		hdr_len -= optlen;
24822 	}
24823 	/*
24824 	 * Make sure that we drop an even number of words by filling
24825 	 * with EOL to the next word boundary.
24826 	 */
24827 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24828 	    hdr_len & 0x3; hdr_len++)
24829 		*up++ = IPOPT_EOL;
24830 	mp->b_wptr = up;
24831 	/* Update header length */
24832 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24833 	return (mp);
24834 }
24835 
24836 /*
24837  * Delivery to local recipients including fanout to multiple recipients.
24838  * Does not do checksumming of UDP/TCP.
24839  * Note: q should be the read side queue for either the ill or conn.
24840  * Note: rq should be the read side q for the lower (ill) stream.
24841  * We don't send packets to IPPF processing, thus the last argument
24842  * to all the fanout calls are B_FALSE.
24843  */
24844 void
24845 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24846     int fanout_flags, zoneid_t zoneid)
24847 {
24848 	uint32_t	protocol;
24849 	mblk_t		*first_mp;
24850 	boolean_t	mctl_present;
24851 	int		ire_type;
24852 #define	rptr	((uchar_t *)ipha)
24853 	ip_stack_t	*ipst = ill->ill_ipst;
24854 
24855 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24856 	    "ip_wput_local_start: q %p", q);
24857 
24858 	if (ire != NULL) {
24859 		ire_type = ire->ire_type;
24860 	} else {
24861 		/*
24862 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24863 		 * packet is not multicast, we can't tell the ire type.
24864 		 */
24865 		ASSERT(CLASSD(ipha->ipha_dst));
24866 		ire_type = IRE_BROADCAST;
24867 	}
24868 
24869 	first_mp = mp;
24870 	if (first_mp->b_datap->db_type == M_CTL) {
24871 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24872 		if (!io->ipsec_out_secure) {
24873 			/*
24874 			 * This ipsec_out_t was allocated in ip_wput
24875 			 * for multicast packets to store the ill_index.
24876 			 * As this is being delivered locally, we don't
24877 			 * need this anymore.
24878 			 */
24879 			mp = first_mp->b_cont;
24880 			freeb(first_mp);
24881 			first_mp = mp;
24882 			mctl_present = B_FALSE;
24883 		} else {
24884 			/*
24885 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24886 			 * security properties for the looped-back packet.
24887 			 */
24888 			mctl_present = B_TRUE;
24889 			mp = first_mp->b_cont;
24890 			ASSERT(mp != NULL);
24891 			ipsec_out_to_in(first_mp);
24892 		}
24893 	} else {
24894 		mctl_present = B_FALSE;
24895 	}
24896 
24897 	DTRACE_PROBE4(ip4__loopback__in__start,
24898 	    ill_t *, ill, ill_t *, NULL,
24899 	    ipha_t *, ipha, mblk_t *, first_mp);
24900 
24901 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24902 	    ipst->ips_ipv4firewall_loopback_in,
24903 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24904 
24905 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24906 
24907 	if (first_mp == NULL)
24908 		return;
24909 
24910 	if (ipst->ips_ip4_observe.he_interested) {
24911 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
24912 		zoneid_t stackzoneid = netstackid_to_zoneid(
24913 		    ipst->ips_netstack->netstack_stackid);
24914 
24915 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
24916 		/*
24917 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
24918 		 * address.  Restrict the lookup below to the destination zone.
24919 		 */
24920 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
24921 			lookup_zoneid = zoneid;
24922 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
24923 		    lookup_zoneid);
24924 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill, ipst);
24925 	}
24926 
24927 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
24928 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
24929 	    int, 1);
24930 
24931 	ipst->ips_loopback_packets++;
24932 
24933 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24934 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24935 	if (!IS_SIMPLE_IPH(ipha)) {
24936 		ip_wput_local_options(ipha, ipst);
24937 	}
24938 
24939 	protocol = ipha->ipha_protocol;
24940 	switch (protocol) {
24941 	case IPPROTO_ICMP: {
24942 		ire_t		*ire_zone;
24943 		ilm_t		*ilm;
24944 		mblk_t		*mp1;
24945 		zoneid_t	last_zoneid;
24946 		ilm_walker_t	ilw;
24947 
24948 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24949 			ASSERT(ire_type == IRE_BROADCAST);
24950 			/*
24951 			 * In the multicast case, applications may have joined
24952 			 * the group from different zones, so we need to deliver
24953 			 * the packet to each of them. Loop through the
24954 			 * multicast memberships structures (ilm) on the receive
24955 			 * ill and send a copy of the packet up each matching
24956 			 * one. However, we don't do this for multicasts sent on
24957 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24958 			 * they must stay in the sender's zone.
24959 			 *
24960 			 * ilm_add_v6() ensures that ilms in the same zone are
24961 			 * contiguous in the ill_ilm list. We use this property
24962 			 * to avoid sending duplicates needed when two
24963 			 * applications in the same zone join the same group on
24964 			 * different logical interfaces: we ignore the ilm if
24965 			 * it's zoneid is the same as the last matching one.
24966 			 * In addition, the sending of the packet for
24967 			 * ire_zoneid is delayed until all of the other ilms
24968 			 * have been exhausted.
24969 			 */
24970 			last_zoneid = -1;
24971 			ilm = ilm_walker_start(&ilw, ill);
24972 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
24973 				if (ipha->ipha_dst != ilm->ilm_addr ||
24974 				    ilm->ilm_zoneid == last_zoneid ||
24975 				    ilm->ilm_zoneid == zoneid ||
24976 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24977 					continue;
24978 				mp1 = ip_copymsg(first_mp);
24979 				if (mp1 == NULL)
24980 					continue;
24981 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
24982 				    0, 0, mctl_present, B_FALSE, ill,
24983 				    ilm->ilm_zoneid);
24984 				last_zoneid = ilm->ilm_zoneid;
24985 			}
24986 			ilm_walker_finish(&ilw);
24987 			/*
24988 			 * Loopback case: the sending endpoint has
24989 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24990 			 * dispatch the multicast packet to the sending zone.
24991 			 */
24992 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24993 				freemsg(first_mp);
24994 				return;
24995 			}
24996 		} else if (ire_type == IRE_BROADCAST) {
24997 			/*
24998 			 * In the broadcast case, there may be many zones
24999 			 * which need a copy of the packet delivered to them.
25000 			 * There is one IRE_BROADCAST per broadcast address
25001 			 * and per zone; we walk those using a helper function.
25002 			 * In addition, the sending of the packet for zoneid is
25003 			 * delayed until all of the other ires have been
25004 			 * processed.
25005 			 */
25006 			IRB_REFHOLD(ire->ire_bucket);
25007 			ire_zone = NULL;
25008 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25009 			    ire)) != NULL) {
25010 				mp1 = ip_copymsg(first_mp);
25011 				if (mp1 == NULL)
25012 					continue;
25013 
25014 				UPDATE_IB_PKT_COUNT(ire_zone);
25015 				ire_zone->ire_last_used_time = lbolt;
25016 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25017 				    mctl_present, B_FALSE, ill,
25018 				    ire_zone->ire_zoneid);
25019 			}
25020 			IRB_REFRELE(ire->ire_bucket);
25021 		}
25022 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25023 		    0, mctl_present, B_FALSE, ill, zoneid);
25024 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25025 		    "ip_wput_local_end: q %p (%S)",
25026 		    q, "icmp");
25027 		return;
25028 	}
25029 	case IPPROTO_IGMP:
25030 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25031 			/* Bad packet - discarded by igmp_input */
25032 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25033 			    "ip_wput_local_end: q %p (%S)",
25034 			    q, "igmp_input--bad packet");
25035 			if (mctl_present)
25036 				freeb(first_mp);
25037 			return;
25038 		}
25039 		/*
25040 		 * igmp_input() may have returned the pulled up message.
25041 		 * So first_mp and ipha need to be reinitialized.
25042 		 */
25043 		ipha = (ipha_t *)mp->b_rptr;
25044 		if (mctl_present)
25045 			first_mp->b_cont = mp;
25046 		else
25047 			first_mp = mp;
25048 		/* deliver to local raw users */
25049 		break;
25050 	case IPPROTO_ENCAP:
25051 		/*
25052 		 * This case is covered by either ip_fanout_proto, or by
25053 		 * the above security processing for self-tunneled packets.
25054 		 */
25055 		break;
25056 	case IPPROTO_UDP: {
25057 		uint16_t	*up;
25058 		uint32_t	ports;
25059 
25060 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25061 		    UDP_PORTS_OFFSET);
25062 		/* Force a 'valid' checksum. */
25063 		up[3] = 0;
25064 
25065 		ports = *(uint32_t *)up;
25066 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25067 		    (ire_type == IRE_BROADCAST),
25068 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25069 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25070 		    ill, zoneid);
25071 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25072 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25073 		return;
25074 	}
25075 	case IPPROTO_TCP: {
25076 
25077 		/*
25078 		 * For TCP, discard broadcast packets.
25079 		 */
25080 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25081 			freemsg(first_mp);
25082 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25083 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25084 			return;
25085 		}
25086 
25087 		if (mp->b_datap->db_type == M_DATA) {
25088 			/*
25089 			 * M_DATA mblk, so init mblk (chain) for no struio().
25090 			 */
25091 			mblk_t	*mp1 = mp;
25092 
25093 			do {
25094 				mp1->b_datap->db_struioflag = 0;
25095 			} while ((mp1 = mp1->b_cont) != NULL);
25096 		}
25097 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25098 		    <= mp->b_wptr);
25099 		ip_fanout_tcp(q, first_mp, ill, ipha,
25100 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25101 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25102 		    mctl_present, B_FALSE, zoneid);
25103 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25104 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25105 		return;
25106 	}
25107 	case IPPROTO_SCTP:
25108 	{
25109 		uint32_t	ports;
25110 
25111 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25112 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25113 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25114 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25115 		return;
25116 	}
25117 
25118 	default:
25119 		break;
25120 	}
25121 	/*
25122 	 * Find a client for some other protocol.  We give
25123 	 * copies to multiple clients, if more than one is
25124 	 * bound.
25125 	 */
25126 	ip_fanout_proto(q, first_mp, ill, ipha,
25127 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25128 	    mctl_present, B_FALSE, ill, zoneid);
25129 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25130 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25131 #undef	rptr
25132 }
25133 
25134 /*
25135  * Update any source route, record route, or timestamp options.
25136  * Check that we are at end of strict source route.
25137  * The options have been sanity checked by ip_wput_options().
25138  */
25139 static void
25140 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25141 {
25142 	ipoptp_t	opts;
25143 	uchar_t		*opt;
25144 	uint8_t		optval;
25145 	uint8_t		optlen;
25146 	ipaddr_t	dst;
25147 	uint32_t	ts;
25148 	ire_t		*ire;
25149 	timestruc_t	now;
25150 
25151 	ip2dbg(("ip_wput_local_options\n"));
25152 	for (optval = ipoptp_first(&opts, ipha);
25153 	    optval != IPOPT_EOL;
25154 	    optval = ipoptp_next(&opts)) {
25155 		opt = opts.ipoptp_cur;
25156 		optlen = opts.ipoptp_len;
25157 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25158 		switch (optval) {
25159 			uint32_t off;
25160 		case IPOPT_SSRR:
25161 		case IPOPT_LSRR:
25162 			off = opt[IPOPT_OFFSET];
25163 			off--;
25164 			if (optlen < IP_ADDR_LEN ||
25165 			    off > optlen - IP_ADDR_LEN) {
25166 				/* End of source route */
25167 				break;
25168 			}
25169 			/*
25170 			 * This will only happen if two consecutive entries
25171 			 * in the source route contains our address or if
25172 			 * it is a packet with a loose source route which
25173 			 * reaches us before consuming the whole source route
25174 			 */
25175 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25176 			if (optval == IPOPT_SSRR) {
25177 				return;
25178 			}
25179 			/*
25180 			 * Hack: instead of dropping the packet truncate the
25181 			 * source route to what has been used by filling the
25182 			 * rest with IPOPT_NOP.
25183 			 */
25184 			opt[IPOPT_OLEN] = (uint8_t)off;
25185 			while (off < optlen) {
25186 				opt[off++] = IPOPT_NOP;
25187 			}
25188 			break;
25189 		case IPOPT_RR:
25190 			off = opt[IPOPT_OFFSET];
25191 			off--;
25192 			if (optlen < IP_ADDR_LEN ||
25193 			    off > optlen - IP_ADDR_LEN) {
25194 				/* No more room - ignore */
25195 				ip1dbg((
25196 				    "ip_wput_forward_options: end of RR\n"));
25197 				break;
25198 			}
25199 			dst = htonl(INADDR_LOOPBACK);
25200 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25201 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25202 			break;
25203 		case IPOPT_TS:
25204 			/* Insert timestamp if there is romm */
25205 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25206 			case IPOPT_TS_TSONLY:
25207 				off = IPOPT_TS_TIMELEN;
25208 				break;
25209 			case IPOPT_TS_PRESPEC:
25210 			case IPOPT_TS_PRESPEC_RFC791:
25211 				/* Verify that the address matched */
25212 				off = opt[IPOPT_OFFSET] - 1;
25213 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25214 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25215 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25216 				    ipst);
25217 				if (ire == NULL) {
25218 					/* Not for us */
25219 					break;
25220 				}
25221 				ire_refrele(ire);
25222 				/* FALLTHRU */
25223 			case IPOPT_TS_TSANDADDR:
25224 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25225 				break;
25226 			default:
25227 				/*
25228 				 * ip_*put_options should have already
25229 				 * dropped this packet.
25230 				 */
25231 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25232 				    "unknown IT - bug in ip_wput_options?\n");
25233 				return;	/* Keep "lint" happy */
25234 			}
25235 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25236 				/* Increase overflow counter */
25237 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25238 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25239 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25240 				    (off << 4);
25241 				break;
25242 			}
25243 			off = opt[IPOPT_OFFSET] - 1;
25244 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25245 			case IPOPT_TS_PRESPEC:
25246 			case IPOPT_TS_PRESPEC_RFC791:
25247 			case IPOPT_TS_TSANDADDR:
25248 				dst = htonl(INADDR_LOOPBACK);
25249 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25250 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25251 				/* FALLTHRU */
25252 			case IPOPT_TS_TSONLY:
25253 				off = opt[IPOPT_OFFSET] - 1;
25254 				/* Compute # of milliseconds since midnight */
25255 				gethrestime(&now);
25256 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25257 				    now.tv_nsec / (NANOSEC / MILLISEC);
25258 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25259 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25260 				break;
25261 			}
25262 			break;
25263 		}
25264 	}
25265 }
25266 
25267 /*
25268  * Send out a multicast packet on interface ipif.
25269  * The sender does not have an conn.
25270  * Caller verifies that this isn't a PHYI_LOOPBACK.
25271  */
25272 void
25273 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25274 {
25275 	ipha_t	*ipha;
25276 	ire_t	*ire;
25277 	ipaddr_t	dst;
25278 	mblk_t		*first_mp;
25279 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25280 
25281 	/* igmp_sendpkt always allocates a ipsec_out_t */
25282 	ASSERT(mp->b_datap->db_type == M_CTL);
25283 	ASSERT(!ipif->ipif_isv6);
25284 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25285 
25286 	first_mp = mp;
25287 	mp = first_mp->b_cont;
25288 	ASSERT(mp->b_datap->db_type == M_DATA);
25289 	ipha = (ipha_t *)mp->b_rptr;
25290 
25291 	/*
25292 	 * Find an IRE which matches the destination and the outgoing
25293 	 * queue (i.e. the outgoing interface.)
25294 	 */
25295 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25296 		dst = ipif->ipif_pp_dst_addr;
25297 	else
25298 		dst = ipha->ipha_dst;
25299 	/*
25300 	 * The source address has already been initialized by the
25301 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25302 	 * be sufficient rather than MATCH_IRE_IPIF.
25303 	 *
25304 	 * This function is used for sending IGMP packets.  For IPMP,
25305 	 * we sidestep IGMP snooping issues by sending all multicast
25306 	 * traffic on a single interface in the IPMP group.
25307 	 */
25308 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25309 	    MATCH_IRE_ILL, ipst);
25310 	if (!ire) {
25311 		/*
25312 		 * Mark this packet to make it be delivered to
25313 		 * ip_wput_ire after the new ire has been
25314 		 * created.
25315 		 */
25316 		mp->b_prev = NULL;
25317 		mp->b_next = NULL;
25318 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25319 		    zoneid, &zero_info);
25320 		return;
25321 	}
25322 
25323 	/*
25324 	 * Honor the RTF_SETSRC flag; this is the only case
25325 	 * where we force this addr whatever the current src addr is,
25326 	 * because this address is set by igmp_sendpkt(), and
25327 	 * cannot be specified by any user.
25328 	 */
25329 	if (ire->ire_flags & RTF_SETSRC) {
25330 		ipha->ipha_src = ire->ire_src_addr;
25331 	}
25332 
25333 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25334 }
25335 
25336 /*
25337  * NOTE : This function does not ire_refrele the ire argument passed in.
25338  *
25339  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25340  * failure. The nce_fp_mp can vanish any time in the case of
25341  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25342  * the ire_lock to access the nce_fp_mp in this case.
25343  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25344  * prepending a fastpath message IPQoS processing must precede it, we also set
25345  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25346  * (IPQoS might have set the b_band for CoS marking).
25347  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25348  * must follow it so that IPQoS can mark the dl_priority field for CoS
25349  * marking, if needed.
25350  */
25351 static mblk_t *
25352 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25353     uint32_t ill_index, ipha_t **iphap)
25354 {
25355 	uint_t	hlen;
25356 	ipha_t *ipha;
25357 	mblk_t *mp1;
25358 	boolean_t qos_done = B_FALSE;
25359 	uchar_t	*ll_hdr;
25360 	ip_stack_t	*ipst = ire->ire_ipst;
25361 
25362 #define	rptr	((uchar_t *)ipha)
25363 
25364 	ipha = (ipha_t *)mp->b_rptr;
25365 	hlen = 0;
25366 	LOCK_IRE_FP_MP(ire);
25367 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25368 		ASSERT(DB_TYPE(mp1) == M_DATA);
25369 		/* Initiate IPPF processing */
25370 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25371 			UNLOCK_IRE_FP_MP(ire);
25372 			ip_process(proc, &mp, ill_index);
25373 			if (mp == NULL)
25374 				return (NULL);
25375 
25376 			ipha = (ipha_t *)mp->b_rptr;
25377 			LOCK_IRE_FP_MP(ire);
25378 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25379 				qos_done = B_TRUE;
25380 				goto no_fp_mp;
25381 			}
25382 			ASSERT(DB_TYPE(mp1) == M_DATA);
25383 		}
25384 		hlen = MBLKL(mp1);
25385 		/*
25386 		 * Check if we have enough room to prepend fastpath
25387 		 * header
25388 		 */
25389 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25390 			ll_hdr = rptr - hlen;
25391 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25392 			/*
25393 			 * Set the b_rptr to the start of the link layer
25394 			 * header
25395 			 */
25396 			mp->b_rptr = ll_hdr;
25397 			mp1 = mp;
25398 		} else {
25399 			mp1 = copyb(mp1);
25400 			if (mp1 == NULL)
25401 				goto unlock_err;
25402 			mp1->b_band = mp->b_band;
25403 			mp1->b_cont = mp;
25404 			/*
25405 			 * XXX disable ICK_VALID and compute checksum
25406 			 * here; can happen if nce_fp_mp changes and
25407 			 * it can't be copied now due to insufficient
25408 			 * space. (unlikely, fp mp can change, but it
25409 			 * does not increase in length)
25410 			 */
25411 		}
25412 		UNLOCK_IRE_FP_MP(ire);
25413 	} else {
25414 no_fp_mp:
25415 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25416 		if (mp1 == NULL) {
25417 unlock_err:
25418 			UNLOCK_IRE_FP_MP(ire);
25419 			freemsg(mp);
25420 			return (NULL);
25421 		}
25422 		UNLOCK_IRE_FP_MP(ire);
25423 		mp1->b_cont = mp;
25424 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25425 			ip_process(proc, &mp1, ill_index);
25426 			if (mp1 == NULL)
25427 				return (NULL);
25428 
25429 			if (mp1->b_cont == NULL)
25430 				ipha = NULL;
25431 			else
25432 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25433 		}
25434 	}
25435 
25436 	*iphap = ipha;
25437 	return (mp1);
25438 #undef rptr
25439 }
25440 
25441 /*
25442  * Finish the outbound IPsec processing for an IPv6 packet. This function
25443  * is called from ipsec_out_process() if the IPsec packet was processed
25444  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25445  * asynchronously.
25446  */
25447 void
25448 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25449     ire_t *ire_arg)
25450 {
25451 	in6_addr_t *v6dstp;
25452 	ire_t *ire;
25453 	mblk_t *mp;
25454 	ip6_t *ip6h1;
25455 	uint_t	ill_index;
25456 	ipsec_out_t *io;
25457 	boolean_t hwaccel;
25458 	uint32_t flags = IP6_NO_IPPOLICY;
25459 	int match_flags;
25460 	zoneid_t zoneid;
25461 	boolean_t ill_need_rele = B_FALSE;
25462 	boolean_t ire_need_rele = B_FALSE;
25463 	ip_stack_t	*ipst;
25464 
25465 	mp = ipsec_mp->b_cont;
25466 	ip6h1 = (ip6_t *)mp->b_rptr;
25467 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25468 	ASSERT(io->ipsec_out_ns != NULL);
25469 	ipst = io->ipsec_out_ns->netstack_ip;
25470 	ill_index = io->ipsec_out_ill_index;
25471 	if (io->ipsec_out_reachable) {
25472 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25473 	}
25474 	hwaccel = io->ipsec_out_accelerated;
25475 	zoneid = io->ipsec_out_zoneid;
25476 	ASSERT(zoneid != ALL_ZONES);
25477 	ASSERT(IPH_HDR_VERSION(ip6h) == IPV6_VERSION);
25478 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25479 	/* Multicast addresses should have non-zero ill_index. */
25480 	v6dstp = &ip6h->ip6_dst;
25481 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25482 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25483 
25484 	if (ill == NULL && ill_index != 0) {
25485 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25486 		/* Failure case frees things for us. */
25487 		if (ill == NULL)
25488 			return;
25489 
25490 		ill_need_rele = B_TRUE;
25491 	}
25492 	ASSERT(mp != NULL);
25493 
25494 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25495 		boolean_t unspec_src;
25496 		ipif_t	*ipif;
25497 
25498 		/*
25499 		 * Use the ill_index to get the right ill.
25500 		 */
25501 		unspec_src = io->ipsec_out_unspec_src;
25502 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25503 		if (ipif == NULL) {
25504 			if (ill_need_rele)
25505 				ill_refrele(ill);
25506 			freemsg(ipsec_mp);
25507 			return;
25508 		}
25509 
25510 		if (ire_arg != NULL) {
25511 			ire = ire_arg;
25512 		} else {
25513 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25514 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25515 			ire_need_rele = B_TRUE;
25516 		}
25517 		if (ire != NULL) {
25518 			ipif_refrele(ipif);
25519 			/*
25520 			 * XXX Do the multicast forwarding now, as the IPsec
25521 			 * processing has been done.
25522 			 */
25523 			goto send;
25524 		}
25525 
25526 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25527 		mp->b_prev = NULL;
25528 		mp->b_next = NULL;
25529 
25530 		/*
25531 		 * If the IPsec packet was processed asynchronously,
25532 		 * drop it now.
25533 		 */
25534 		if (q == NULL) {
25535 			if (ill_need_rele)
25536 				ill_refrele(ill);
25537 			freemsg(ipsec_mp);
25538 			ipif_refrele(ipif);
25539 			return;
25540 		}
25541 
25542 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25543 		    unspec_src, zoneid);
25544 		ipif_refrele(ipif);
25545 	} else {
25546 		if (ire_arg != NULL) {
25547 			ire = ire_arg;
25548 		} else {
25549 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25550 			ire_need_rele = B_TRUE;
25551 		}
25552 		if (ire != NULL)
25553 			goto send;
25554 		/*
25555 		 * ire disappeared underneath.
25556 		 *
25557 		 * What we need to do here is the ip_newroute
25558 		 * logic to get the ire without doing the IPsec
25559 		 * processing. Follow the same old path. But this
25560 		 * time, ip_wput or ire_add_then_send will call us
25561 		 * directly as all the IPsec operations are done.
25562 		 */
25563 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25564 		mp->b_prev = NULL;
25565 		mp->b_next = NULL;
25566 
25567 		/*
25568 		 * If the IPsec packet was processed asynchronously,
25569 		 * drop it now.
25570 		 */
25571 		if (q == NULL) {
25572 			if (ill_need_rele)
25573 				ill_refrele(ill);
25574 			freemsg(ipsec_mp);
25575 			return;
25576 		}
25577 
25578 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25579 		    zoneid, ipst);
25580 	}
25581 	if (ill != NULL && ill_need_rele)
25582 		ill_refrele(ill);
25583 	return;
25584 send:
25585 	if (ill != NULL && ill_need_rele)
25586 		ill_refrele(ill);
25587 
25588 	/* Local delivery */
25589 	if (ire->ire_stq == NULL) {
25590 		ill_t	*out_ill;
25591 		ASSERT(q != NULL);
25592 
25593 		/* PFHooks: LOOPBACK_OUT */
25594 		out_ill = ire_to_ill(ire);
25595 
25596 		/*
25597 		 * DTrace this as ip:::send.  A blocked packet will fire the
25598 		 * send probe, but not the receive probe.
25599 		 */
25600 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25601 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25602 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25603 
25604 		DTRACE_PROBE4(ip6__loopback__out__start,
25605 		    ill_t *, NULL, ill_t *, out_ill,
25606 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25607 
25608 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25609 		    ipst->ips_ipv6firewall_loopback_out,
25610 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25611 
25612 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25613 
25614 		if (ipsec_mp != NULL) {
25615 			ip_wput_local_v6(RD(q), out_ill,
25616 			    ip6h, ipsec_mp, ire, 0, zoneid);
25617 		}
25618 		if (ire_need_rele)
25619 			ire_refrele(ire);
25620 		return;
25621 	}
25622 	/*
25623 	 * Everything is done. Send it out on the wire.
25624 	 * We force the insertion of a fragment header using the
25625 	 * IPH_FRAG_HDR flag in two cases:
25626 	 * - after reception of an ICMPv6 "packet too big" message
25627 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25628 	 * - for multirouted IPv6 packets, so that the receiver can
25629 	 *   discard duplicates according to their fragment identifier
25630 	 */
25631 	/* XXX fix flow control problems. */
25632 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25633 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25634 		if (hwaccel) {
25635 			/*
25636 			 * hardware acceleration does not handle these
25637 			 * "slow path" cases.
25638 			 */
25639 			/* IPsec KSTATS: should bump bean counter here. */
25640 			if (ire_need_rele)
25641 				ire_refrele(ire);
25642 			freemsg(ipsec_mp);
25643 			return;
25644 		}
25645 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25646 		    (mp->b_cont ? msgdsize(mp) :
25647 		    mp->b_wptr - (uchar_t *)ip6h)) {
25648 			/* IPsec KSTATS: should bump bean counter here. */
25649 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25650 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25651 			    msgdsize(mp)));
25652 			if (ire_need_rele)
25653 				ire_refrele(ire);
25654 			freemsg(ipsec_mp);
25655 			return;
25656 		}
25657 		ASSERT(mp->b_prev == NULL);
25658 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25659 		    ntohs(ip6h->ip6_plen) +
25660 		    IPV6_HDR_LEN, ire->ire_max_frag));
25661 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25662 		    ire->ire_max_frag);
25663 	} else {
25664 		UPDATE_OB_PKT_COUNT(ire);
25665 		ire->ire_last_used_time = lbolt;
25666 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25667 	}
25668 	if (ire_need_rele)
25669 		ire_refrele(ire);
25670 	freeb(ipsec_mp);
25671 }
25672 
25673 void
25674 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25675 {
25676 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25677 	da_ipsec_t *hada;	/* data attributes */
25678 	ill_t *ill = (ill_t *)q->q_ptr;
25679 
25680 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25681 
25682 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25683 		/* IPsec KSTATS: Bump lose counter here! */
25684 		freemsg(mp);
25685 		return;
25686 	}
25687 
25688 	/*
25689 	 * It's an IPsec packet that must be
25690 	 * accelerated by the Provider, and the
25691 	 * outbound ill is IPsec acceleration capable.
25692 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25693 	 * to the ill.
25694 	 * IPsec KSTATS: should bump packet counter here.
25695 	 */
25696 
25697 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25698 	if (hada_mp == NULL) {
25699 		/* IPsec KSTATS: should bump packet counter here. */
25700 		freemsg(mp);
25701 		return;
25702 	}
25703 
25704 	hada_mp->b_datap->db_type = M_CTL;
25705 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25706 	hada_mp->b_cont = mp;
25707 
25708 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25709 	bzero(hada, sizeof (da_ipsec_t));
25710 	hada->da_type = IPHADA_M_CTL;
25711 
25712 	putnext(q, hada_mp);
25713 }
25714 
25715 /*
25716  * Finish the outbound IPsec processing. This function is called from
25717  * ipsec_out_process() if the IPsec packet was processed
25718  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25719  * asynchronously.
25720  */
25721 void
25722 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25723     ire_t *ire_arg)
25724 {
25725 	uint32_t v_hlen_tos_len;
25726 	ipaddr_t	dst;
25727 	ipif_t	*ipif = NULL;
25728 	ire_t *ire;
25729 	ire_t *ire1 = NULL;
25730 	mblk_t *next_mp = NULL;
25731 	uint32_t max_frag;
25732 	boolean_t multirt_send = B_FALSE;
25733 	mblk_t *mp;
25734 	ipha_t *ipha1;
25735 	uint_t	ill_index;
25736 	ipsec_out_t *io;
25737 	int match_flags;
25738 	irb_t *irb = NULL;
25739 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25740 	zoneid_t zoneid;
25741 	ipxmit_state_t	pktxmit_state;
25742 	ip_stack_t	*ipst;
25743 
25744 #ifdef	_BIG_ENDIAN
25745 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25746 #else
25747 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25748 #endif
25749 
25750 	mp = ipsec_mp->b_cont;
25751 	ipha1 = (ipha_t *)mp->b_rptr;
25752 	ASSERT(mp != NULL);
25753 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25754 	dst = ipha->ipha_dst;
25755 
25756 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25757 	ill_index = io->ipsec_out_ill_index;
25758 	zoneid = io->ipsec_out_zoneid;
25759 	ASSERT(zoneid != ALL_ZONES);
25760 	ipst = io->ipsec_out_ns->netstack_ip;
25761 	ASSERT(io->ipsec_out_ns != NULL);
25762 
25763 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25764 	if (ill == NULL && ill_index != 0) {
25765 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25766 		/* Failure case frees things for us. */
25767 		if (ill == NULL)
25768 			return;
25769 
25770 		ill_need_rele = B_TRUE;
25771 	}
25772 
25773 	if (CLASSD(dst)) {
25774 		boolean_t conn_dontroute;
25775 		/*
25776 		 * Use the ill_index to get the right ipif.
25777 		 */
25778 		conn_dontroute = io->ipsec_out_dontroute;
25779 		if (ill_index == 0)
25780 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25781 		else
25782 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25783 		if (ipif == NULL) {
25784 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25785 			    " multicast\n"));
25786 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25787 			freemsg(ipsec_mp);
25788 			goto done;
25789 		}
25790 		/*
25791 		 * ipha_src has already been intialized with the
25792 		 * value of the ipif in ip_wput. All we need now is
25793 		 * an ire to send this downstream.
25794 		 */
25795 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25796 		    msg_getlabel(mp), match_flags, ipst);
25797 		if (ire != NULL) {
25798 			ill_t *ill1;
25799 			/*
25800 			 * Do the multicast forwarding now, as the IPsec
25801 			 * processing has been done.
25802 			 */
25803 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25804 			    (ill1 = ire_to_ill(ire))) {
25805 				if (ip_mforward(ill1, ipha, mp)) {
25806 					freemsg(ipsec_mp);
25807 					ip1dbg(("ip_wput_ipsec_out: mforward "
25808 					    "failed\n"));
25809 					ire_refrele(ire);
25810 					goto done;
25811 				}
25812 			}
25813 			goto send;
25814 		}
25815 
25816 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25817 		mp->b_prev = NULL;
25818 		mp->b_next = NULL;
25819 
25820 		/*
25821 		 * If the IPsec packet was processed asynchronously,
25822 		 * drop it now.
25823 		 */
25824 		if (q == NULL) {
25825 			freemsg(ipsec_mp);
25826 			goto done;
25827 		}
25828 
25829 		/*
25830 		 * We may be using a wrong ipif to create the ire.
25831 		 * But it is okay as the source address is assigned
25832 		 * for the packet already. Next outbound packet would
25833 		 * create the IRE with the right IPIF in ip_wput.
25834 		 *
25835 		 * Also handle RTF_MULTIRT routes.
25836 		 */
25837 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25838 		    zoneid, &zero_info);
25839 	} else {
25840 		if (ire_arg != NULL) {
25841 			ire = ire_arg;
25842 			ire_need_rele = B_FALSE;
25843 		} else {
25844 			ire = ire_cache_lookup(dst, zoneid,
25845 			    msg_getlabel(mp), ipst);
25846 		}
25847 		if (ire != NULL) {
25848 			goto send;
25849 		}
25850 
25851 		/*
25852 		 * ire disappeared underneath.
25853 		 *
25854 		 * What we need to do here is the ip_newroute
25855 		 * logic to get the ire without doing the IPsec
25856 		 * processing. Follow the same old path. But this
25857 		 * time, ip_wput or ire_add_then_put will call us
25858 		 * directly as all the IPsec operations are done.
25859 		 */
25860 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25861 		mp->b_prev = NULL;
25862 		mp->b_next = NULL;
25863 
25864 		/*
25865 		 * If the IPsec packet was processed asynchronously,
25866 		 * drop it now.
25867 		 */
25868 		if (q == NULL) {
25869 			freemsg(ipsec_mp);
25870 			goto done;
25871 		}
25872 
25873 		/*
25874 		 * Since we're going through ip_newroute() again, we
25875 		 * need to make sure we don't:
25876 		 *
25877 		 *	1.) Trigger the ASSERT() with the ipha_ident
25878 		 *	    overloading.
25879 		 *	2.) Redo transport-layer checksumming, since we've
25880 		 *	    already done all that to get this far.
25881 		 *
25882 		 * The easiest way not do either of the above is to set
25883 		 * the ipha_ident field to IP_HDR_INCLUDED.
25884 		 */
25885 		ipha->ipha_ident = IP_HDR_INCLUDED;
25886 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25887 		    zoneid, ipst);
25888 	}
25889 	goto done;
25890 send:
25891 	if (ire->ire_stq == NULL) {
25892 		ill_t	*out_ill;
25893 		/*
25894 		 * Loopbacks go through ip_wput_local except for one case.
25895 		 * We come here if we generate a icmp_frag_needed message
25896 		 * after IPsec processing is over. When this function calls
25897 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25898 		 * icmp_frag_needed. The message generated comes back here
25899 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25900 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25901 		 * source address as it is usually set in ip_wput_ire. As
25902 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25903 		 * and we end up here. We can't enter ip_wput_ire once the
25904 		 * IPsec processing is over and hence we need to do it here.
25905 		 */
25906 		ASSERT(q != NULL);
25907 		UPDATE_OB_PKT_COUNT(ire);
25908 		ire->ire_last_used_time = lbolt;
25909 		if (ipha->ipha_src == 0)
25910 			ipha->ipha_src = ire->ire_src_addr;
25911 
25912 		/* PFHooks: LOOPBACK_OUT */
25913 		out_ill = ire_to_ill(ire);
25914 
25915 		/*
25916 		 * DTrace this as ip:::send.  A blocked packet will fire the
25917 		 * send probe, but not the receive probe.
25918 		 */
25919 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25920 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
25921 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
25922 
25923 		DTRACE_PROBE4(ip4__loopback__out__start,
25924 		    ill_t *, NULL, ill_t *, out_ill,
25925 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25926 
25927 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25928 		    ipst->ips_ipv4firewall_loopback_out,
25929 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
25930 
25931 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25932 
25933 		if (ipsec_mp != NULL)
25934 			ip_wput_local(RD(q), out_ill,
25935 			    ipha, ipsec_mp, ire, 0, zoneid);
25936 		if (ire_need_rele)
25937 			ire_refrele(ire);
25938 		goto done;
25939 	}
25940 
25941 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25942 		/*
25943 		 * We are through with IPsec processing.
25944 		 * Fragment this and send it on the wire.
25945 		 */
25946 		if (io->ipsec_out_accelerated) {
25947 			/*
25948 			 * The packet has been accelerated but must
25949 			 * be fragmented. This should not happen
25950 			 * since AH and ESP must not accelerate
25951 			 * packets that need fragmentation, however
25952 			 * the configuration could have changed
25953 			 * since the AH or ESP processing.
25954 			 * Drop packet.
25955 			 * IPsec KSTATS: bump bean counter here.
25956 			 */
25957 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25958 			    "fragmented accelerated packet!\n"));
25959 			freemsg(ipsec_mp);
25960 		} else {
25961 			ip_wput_ire_fragmentit(ipsec_mp, ire,
25962 			    zoneid, ipst, NULL);
25963 		}
25964 		if (ire_need_rele)
25965 			ire_refrele(ire);
25966 		goto done;
25967 	}
25968 
25969 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25970 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25971 	    (void *)ire->ire_ipif, (void *)ipif));
25972 
25973 	/*
25974 	 * Multiroute the secured packet.
25975 	 */
25976 	if (ire->ire_flags & RTF_MULTIRT) {
25977 		ire_t *first_ire;
25978 		irb = ire->ire_bucket;
25979 		ASSERT(irb != NULL);
25980 		/*
25981 		 * This ire has been looked up as the one that
25982 		 * goes through the given ipif;
25983 		 * make sure we do not omit any other multiroute ire
25984 		 * that may be present in the bucket before this one.
25985 		 */
25986 		IRB_REFHOLD(irb);
25987 		for (first_ire = irb->irb_ire;
25988 		    first_ire != NULL;
25989 		    first_ire = first_ire->ire_next) {
25990 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25991 			    (first_ire->ire_addr == ire->ire_addr) &&
25992 			    !(first_ire->ire_marks &
25993 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
25994 				break;
25995 		}
25996 
25997 		if ((first_ire != NULL) && (first_ire != ire)) {
25998 			/*
25999 			 * Don't change the ire if the packet must
26000 			 * be fragmented if sent via this new one.
26001 			 */
26002 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26003 				IRE_REFHOLD(first_ire);
26004 				if (ire_need_rele)
26005 					ire_refrele(ire);
26006 				else
26007 					ire_need_rele = B_TRUE;
26008 				ire = first_ire;
26009 			}
26010 		}
26011 		IRB_REFRELE(irb);
26012 
26013 		multirt_send = B_TRUE;
26014 		max_frag = ire->ire_max_frag;
26015 	}
26016 
26017 	/*
26018 	 * In most cases, the emission loop below is entered only once.
26019 	 * Only in the case where the ire holds the RTF_MULTIRT
26020 	 * flag, we loop to process all RTF_MULTIRT ires in the
26021 	 * bucket, and send the packet through all crossed
26022 	 * RTF_MULTIRT routes.
26023 	 */
26024 	do {
26025 		if (multirt_send) {
26026 			/*
26027 			 * ire1 holds here the next ire to process in the
26028 			 * bucket. If multirouting is expected,
26029 			 * any non-RTF_MULTIRT ire that has the
26030 			 * right destination address is ignored.
26031 			 */
26032 			ASSERT(irb != NULL);
26033 			IRB_REFHOLD(irb);
26034 			for (ire1 = ire->ire_next;
26035 			    ire1 != NULL;
26036 			    ire1 = ire1->ire_next) {
26037 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26038 					continue;
26039 				if (ire1->ire_addr != ire->ire_addr)
26040 					continue;
26041 				if (ire1->ire_marks &
26042 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26043 					continue;
26044 				/* No loopback here */
26045 				if (ire1->ire_stq == NULL)
26046 					continue;
26047 				/*
26048 				 * Ensure we do not exceed the MTU
26049 				 * of the next route.
26050 				 */
26051 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26052 					ip_multirt_bad_mtu(ire1, max_frag);
26053 					continue;
26054 				}
26055 
26056 				IRE_REFHOLD(ire1);
26057 				break;
26058 			}
26059 			IRB_REFRELE(irb);
26060 			if (ire1 != NULL) {
26061 				/*
26062 				 * We are in a multiple send case, need to
26063 				 * make a copy of the packet.
26064 				 */
26065 				next_mp = copymsg(ipsec_mp);
26066 				if (next_mp == NULL) {
26067 					ire_refrele(ire1);
26068 					ire1 = NULL;
26069 				}
26070 			}
26071 		}
26072 		/*
26073 		 * Everything is done. Send it out on the wire
26074 		 *
26075 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26076 		 * either send it on the wire or, in the case of
26077 		 * HW acceleration, call ipsec_hw_putnext.
26078 		 */
26079 		if (ire->ire_nce &&
26080 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26081 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26082 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26083 			/*
26084 			 * If ire's link-layer is unresolved (this
26085 			 * would only happen if the incomplete ire
26086 			 * was added to cachetable via forwarding path)
26087 			 * don't bother going to ip_xmit_v4. Just drop the
26088 			 * packet.
26089 			 * There is a slight risk here, in that, if we
26090 			 * have the forwarding path create an incomplete
26091 			 * IRE, then until the IRE is completed, any
26092 			 * transmitted IPsec packets will be dropped
26093 			 * instead of being queued waiting for resolution.
26094 			 *
26095 			 * But the likelihood of a forwarding packet and a wput
26096 			 * packet sending to the same dst at the same time
26097 			 * and there not yet be an ARP entry for it is small.
26098 			 * Furthermore, if this actually happens, it might
26099 			 * be likely that wput would generate multiple
26100 			 * packets (and forwarding would also have a train
26101 			 * of packets) for that destination. If this is
26102 			 * the case, some of them would have been dropped
26103 			 * anyway, since ARP only queues a few packets while
26104 			 * waiting for resolution
26105 			 *
26106 			 * NOTE: We should really call ip_xmit_v4,
26107 			 * and let it queue the packet and send the
26108 			 * ARP query and have ARP come back thus:
26109 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26110 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26111 			 * hw accel work. But it's too complex to get
26112 			 * the IPsec hw  acceleration approach to fit
26113 			 * well with ip_xmit_v4 doing ARP without
26114 			 * doing IPsec simplification. For now, we just
26115 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26116 			 * that we can continue with the send on the next
26117 			 * attempt.
26118 			 *
26119 			 * XXX THis should be revisited, when
26120 			 * the IPsec/IP interaction is cleaned up
26121 			 */
26122 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26123 			    " - dropping packet\n"));
26124 			freemsg(ipsec_mp);
26125 			/*
26126 			 * Call ip_xmit_v4() to trigger ARP query
26127 			 * in case the nce_state is ND_INITIAL
26128 			 */
26129 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26130 			goto drop_pkt;
26131 		}
26132 
26133 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26134 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26135 		    mblk_t *, ipsec_mp);
26136 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26137 		    ipst->ips_ipv4firewall_physical_out, NULL,
26138 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26139 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26140 		if (ipsec_mp == NULL)
26141 			goto drop_pkt;
26142 
26143 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26144 		pktxmit_state = ip_xmit_v4(mp, ire,
26145 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26146 
26147 		if ((pktxmit_state ==  SEND_FAILED) ||
26148 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26149 
26150 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26151 drop_pkt:
26152 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26153 			    ipIfStatsOutDiscards);
26154 			if (ire_need_rele)
26155 				ire_refrele(ire);
26156 			if (ire1 != NULL) {
26157 				ire_refrele(ire1);
26158 				freemsg(next_mp);
26159 			}
26160 			goto done;
26161 		}
26162 
26163 		freeb(ipsec_mp);
26164 		if (ire_need_rele)
26165 			ire_refrele(ire);
26166 
26167 		if (ire1 != NULL) {
26168 			ire = ire1;
26169 			ire_need_rele = B_TRUE;
26170 			ASSERT(next_mp);
26171 			ipsec_mp = next_mp;
26172 			mp = ipsec_mp->b_cont;
26173 			ire1 = NULL;
26174 			next_mp = NULL;
26175 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26176 		} else {
26177 			multirt_send = B_FALSE;
26178 		}
26179 	} while (multirt_send);
26180 done:
26181 	if (ill != NULL && ill_need_rele)
26182 		ill_refrele(ill);
26183 	if (ipif != NULL)
26184 		ipif_refrele(ipif);
26185 }
26186 
26187 /*
26188  * Get the ill corresponding to the specified ire, and compare its
26189  * capabilities with the protocol and algorithms specified by the
26190  * the SA obtained from ipsec_out. If they match, annotate the
26191  * ipsec_out structure to indicate that the packet needs acceleration.
26192  *
26193  *
26194  * A packet is eligible for outbound hardware acceleration if the
26195  * following conditions are satisfied:
26196  *
26197  * 1. the packet will not be fragmented
26198  * 2. the provider supports the algorithm
26199  * 3. there is no pending control message being exchanged
26200  * 4. snoop is not attached
26201  * 5. the destination address is not a broadcast or multicast address.
26202  *
26203  * Rationale:
26204  *	- Hardware drivers do not support fragmentation with
26205  *	  the current interface.
26206  *	- snoop, multicast, and broadcast may result in exposure of
26207  *	  a cleartext datagram.
26208  * We check all five of these conditions here.
26209  *
26210  * XXX would like to nuke "ire_t *" parameter here; problem is that
26211  * IRE is only way to figure out if a v4 address is a broadcast and
26212  * thus ineligible for acceleration...
26213  */
26214 static void
26215 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26216 {
26217 	ipsec_out_t *io;
26218 	mblk_t *data_mp;
26219 	uint_t plen, overhead;
26220 	ip_stack_t	*ipst;
26221 	phyint_t	*phyint;
26222 
26223 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26224 		return;
26225 
26226 	if (ill == NULL)
26227 		return;
26228 	ipst = ill->ill_ipst;
26229 	phyint = ill->ill_phyint;
26230 
26231 	/*
26232 	 * Destination address is a broadcast or multicast.  Punt.
26233 	 */
26234 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26235 	    IRE_LOCAL)))
26236 		return;
26237 
26238 	data_mp = ipsec_mp->b_cont;
26239 
26240 	if (ill->ill_isv6) {
26241 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26242 
26243 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26244 			return;
26245 
26246 		plen = ip6h->ip6_plen;
26247 	} else {
26248 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26249 
26250 		if (CLASSD(ipha->ipha_dst))
26251 			return;
26252 
26253 		plen = ipha->ipha_length;
26254 	}
26255 	/*
26256 	 * Is there a pending DLPI control message being exchanged
26257 	 * between IP/IPsec and the DLS Provider? If there is, it
26258 	 * could be a SADB update, and the state of the DLS Provider
26259 	 * SADB might not be in sync with the SADB maintained by
26260 	 * IPsec. To avoid dropping packets or using the wrong keying
26261 	 * material, we do not accelerate this packet.
26262 	 */
26263 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26264 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26265 		    "ill_dlpi_pending! don't accelerate packet\n"));
26266 		return;
26267 	}
26268 
26269 	/*
26270 	 * Is the Provider in promiscous mode? If it does, we don't
26271 	 * accelerate the packet since it will bounce back up to the
26272 	 * listeners in the clear.
26273 	 */
26274 	if (phyint->phyint_flags & PHYI_PROMISC) {
26275 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26276 		    "ill in promiscous mode, don't accelerate packet\n"));
26277 		return;
26278 	}
26279 
26280 	/*
26281 	 * Will the packet require fragmentation?
26282 	 */
26283 
26284 	/*
26285 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26286 	 * as is used elsewhere.
26287 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26288 	 *	+ 2-byte trailer
26289 	 */
26290 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26291 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26292 
26293 	if ((plen + overhead) > ill->ill_max_mtu)
26294 		return;
26295 
26296 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26297 
26298 	/*
26299 	 * Can the ill accelerate this IPsec protocol and algorithm
26300 	 * specified by the SA?
26301 	 */
26302 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26303 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26304 		return;
26305 	}
26306 
26307 	/*
26308 	 * Tell AH or ESP that the outbound ill is capable of
26309 	 * accelerating this packet.
26310 	 */
26311 	io->ipsec_out_is_capab_ill = B_TRUE;
26312 }
26313 
26314 /*
26315  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26316  *
26317  * If this function returns B_TRUE, the requested SA's have been filled
26318  * into the ipsec_out_*_sa pointers.
26319  *
26320  * If the function returns B_FALSE, the packet has been "consumed", most
26321  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26322  *
26323  * The SA references created by the protocol-specific "select"
26324  * function will be released when the ipsec_mp is freed, thanks to the
26325  * ipsec_out_free destructor -- see spd.c.
26326  */
26327 static boolean_t
26328 ipsec_out_select_sa(mblk_t *ipsec_mp)
26329 {
26330 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26331 	ipsec_out_t *io;
26332 	ipsec_policy_t *pp;
26333 	ipsec_action_t *ap;
26334 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26335 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26336 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26337 
26338 	if (!io->ipsec_out_secure) {
26339 		/*
26340 		 * We came here by mistake.
26341 		 * Don't bother with ipsec processing
26342 		 * We should "discourage" this path in the future.
26343 		 */
26344 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26345 		return (B_FALSE);
26346 	}
26347 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26348 	ASSERT((io->ipsec_out_policy != NULL) ||
26349 	    (io->ipsec_out_act != NULL));
26350 
26351 	ASSERT(io->ipsec_out_failed == B_FALSE);
26352 
26353 	/*
26354 	 * IPsec processing has started.
26355 	 */
26356 	io->ipsec_out_proc_begin = B_TRUE;
26357 	ap = io->ipsec_out_act;
26358 	if (ap == NULL) {
26359 		pp = io->ipsec_out_policy;
26360 		ASSERT(pp != NULL);
26361 		ap = pp->ipsp_act;
26362 		ASSERT(ap != NULL);
26363 	}
26364 
26365 	/*
26366 	 * We have an action.  now, let's select SA's.
26367 	 * (In the future, we can cache this in the conn_t..)
26368 	 */
26369 	if (ap->ipa_want_esp) {
26370 		if (io->ipsec_out_esp_sa == NULL) {
26371 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26372 			    IPPROTO_ESP);
26373 		}
26374 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26375 	}
26376 
26377 	if (ap->ipa_want_ah) {
26378 		if (io->ipsec_out_ah_sa == NULL) {
26379 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26380 			    IPPROTO_AH);
26381 		}
26382 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26383 		/*
26384 		 * The ESP and AH processing order needs to be preserved
26385 		 * when both protocols are required (ESP should be applied
26386 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26387 		 * when both ESP and AH are required, and an AH ACQUIRE
26388 		 * is needed.
26389 		 */
26390 		if (ap->ipa_want_esp && need_ah_acquire)
26391 			need_esp_acquire = B_TRUE;
26392 	}
26393 
26394 	/*
26395 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26396 	 * Release SAs that got referenced, but will not be used until we
26397 	 * acquire _all_ of the SAs we need.
26398 	 */
26399 	if (need_ah_acquire || need_esp_acquire) {
26400 		if (io->ipsec_out_ah_sa != NULL) {
26401 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26402 			io->ipsec_out_ah_sa = NULL;
26403 		}
26404 		if (io->ipsec_out_esp_sa != NULL) {
26405 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26406 			io->ipsec_out_esp_sa = NULL;
26407 		}
26408 
26409 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26410 		return (B_FALSE);
26411 	}
26412 
26413 	return (B_TRUE);
26414 }
26415 
26416 /*
26417  * Process an IPSEC_OUT message and see what you can
26418  * do with it.
26419  * IPQoS Notes:
26420  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26421  * IPsec.
26422  * XXX would like to nuke ire_t.
26423  * XXX ill_index better be "real"
26424  */
26425 void
26426 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26427 {
26428 	ipsec_out_t *io;
26429 	ipsec_policy_t *pp;
26430 	ipsec_action_t *ap;
26431 	ipha_t *ipha;
26432 	ip6_t *ip6h;
26433 	mblk_t *mp;
26434 	ill_t *ill;
26435 	zoneid_t zoneid;
26436 	ipsec_status_t ipsec_rc;
26437 	boolean_t ill_need_rele = B_FALSE;
26438 	ip_stack_t	*ipst;
26439 	ipsec_stack_t	*ipss;
26440 
26441 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26442 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26443 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26444 	ipst = io->ipsec_out_ns->netstack_ip;
26445 	mp = ipsec_mp->b_cont;
26446 
26447 	/*
26448 	 * Initiate IPPF processing. We do it here to account for packets
26449 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26450 	 * We can check for ipsec_out_proc_begin even for such packets, as
26451 	 * they will always be false (asserted below).
26452 	 */
26453 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26454 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26455 		    io->ipsec_out_ill_index : ill_index);
26456 		if (mp == NULL) {
26457 			ip2dbg(("ipsec_out_process: packet dropped "\
26458 			    "during IPPF processing\n"));
26459 			freeb(ipsec_mp);
26460 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26461 			return;
26462 		}
26463 	}
26464 
26465 	if (!io->ipsec_out_secure) {
26466 		/*
26467 		 * We came here by mistake.
26468 		 * Don't bother with ipsec processing
26469 		 * Should "discourage" this path in the future.
26470 		 */
26471 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26472 		goto done;
26473 	}
26474 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26475 	ASSERT((io->ipsec_out_policy != NULL) ||
26476 	    (io->ipsec_out_act != NULL));
26477 	ASSERT(io->ipsec_out_failed == B_FALSE);
26478 
26479 	ipss = ipst->ips_netstack->netstack_ipsec;
26480 	if (!ipsec_loaded(ipss)) {
26481 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26482 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26483 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26484 		} else {
26485 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26486 		}
26487 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26488 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26489 		    &ipss->ipsec_dropper);
26490 		return;
26491 	}
26492 
26493 	/*
26494 	 * IPsec processing has started.
26495 	 */
26496 	io->ipsec_out_proc_begin = B_TRUE;
26497 	ap = io->ipsec_out_act;
26498 	if (ap == NULL) {
26499 		pp = io->ipsec_out_policy;
26500 		ASSERT(pp != NULL);
26501 		ap = pp->ipsp_act;
26502 		ASSERT(ap != NULL);
26503 	}
26504 
26505 	/*
26506 	 * Save the outbound ill index. When the packet comes back
26507 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26508 	 * before sending it the accelerated packet.
26509 	 */
26510 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26511 		ill = ire_to_ill(ire);
26512 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26513 	}
26514 
26515 	/*
26516 	 * The order of processing is first insert a IP header if needed.
26517 	 * Then insert the ESP header and then the AH header.
26518 	 */
26519 	if ((io->ipsec_out_se_done == B_FALSE) &&
26520 	    (ap->ipa_want_se)) {
26521 		/*
26522 		 * First get the outer IP header before sending
26523 		 * it to ESP.
26524 		 */
26525 		ipha_t *oipha, *iipha;
26526 		mblk_t *outer_mp, *inner_mp;
26527 
26528 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26529 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26530 			    "ipsec_out_process: "
26531 			    "Self-Encapsulation failed: Out of memory\n");
26532 			freemsg(ipsec_mp);
26533 			if (ill != NULL) {
26534 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26535 			} else {
26536 				BUMP_MIB(&ipst->ips_ip_mib,
26537 				    ipIfStatsOutDiscards);
26538 			}
26539 			return;
26540 		}
26541 		inner_mp = ipsec_mp->b_cont;
26542 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26543 		oipha = (ipha_t *)outer_mp->b_rptr;
26544 		iipha = (ipha_t *)inner_mp->b_rptr;
26545 		*oipha = *iipha;
26546 		outer_mp->b_wptr += sizeof (ipha_t);
26547 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26548 		    sizeof (ipha_t));
26549 		oipha->ipha_protocol = IPPROTO_ENCAP;
26550 		oipha->ipha_version_and_hdr_length =
26551 		    IP_SIMPLE_HDR_VERSION;
26552 		oipha->ipha_hdr_checksum = 0;
26553 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26554 		outer_mp->b_cont = inner_mp;
26555 		ipsec_mp->b_cont = outer_mp;
26556 
26557 		io->ipsec_out_se_done = B_TRUE;
26558 		io->ipsec_out_tunnel = B_TRUE;
26559 	}
26560 
26561 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26562 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26563 	    !ipsec_out_select_sa(ipsec_mp))
26564 		return;
26565 
26566 	/*
26567 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26568 	 * to do the heavy lifting.
26569 	 */
26570 	zoneid = io->ipsec_out_zoneid;
26571 	ASSERT(zoneid != ALL_ZONES);
26572 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26573 		ASSERT(io->ipsec_out_esp_sa != NULL);
26574 		io->ipsec_out_esp_done = B_TRUE;
26575 		/*
26576 		 * Note that since hw accel can only apply one transform,
26577 		 * not two, we skip hw accel for ESP if we also have AH
26578 		 * This is an design limitation of the interface
26579 		 * which should be revisited.
26580 		 */
26581 		ASSERT(ire != NULL);
26582 		if (io->ipsec_out_ah_sa == NULL) {
26583 			ill = (ill_t *)ire->ire_stq->q_ptr;
26584 			ipsec_out_is_accelerated(ipsec_mp,
26585 			    io->ipsec_out_esp_sa, ill, ire);
26586 		}
26587 
26588 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26589 		switch (ipsec_rc) {
26590 		case IPSEC_STATUS_SUCCESS:
26591 			break;
26592 		case IPSEC_STATUS_FAILED:
26593 			if (ill != NULL) {
26594 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26595 			} else {
26596 				BUMP_MIB(&ipst->ips_ip_mib,
26597 				    ipIfStatsOutDiscards);
26598 			}
26599 			/* FALLTHRU */
26600 		case IPSEC_STATUS_PENDING:
26601 			return;
26602 		}
26603 	}
26604 
26605 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26606 		ASSERT(io->ipsec_out_ah_sa != NULL);
26607 		io->ipsec_out_ah_done = B_TRUE;
26608 		if (ire == NULL) {
26609 			int idx = io->ipsec_out_capab_ill_index;
26610 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26611 			    NULL, NULL, NULL, NULL, ipst);
26612 			ill_need_rele = B_TRUE;
26613 		} else {
26614 			ill = (ill_t *)ire->ire_stq->q_ptr;
26615 		}
26616 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26617 		    ire);
26618 
26619 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26620 		switch (ipsec_rc) {
26621 		case IPSEC_STATUS_SUCCESS:
26622 			break;
26623 		case IPSEC_STATUS_FAILED:
26624 			if (ill != NULL) {
26625 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26626 			} else {
26627 				BUMP_MIB(&ipst->ips_ip_mib,
26628 				    ipIfStatsOutDiscards);
26629 			}
26630 			/* FALLTHRU */
26631 		case IPSEC_STATUS_PENDING:
26632 			if (ill != NULL && ill_need_rele)
26633 				ill_refrele(ill);
26634 			return;
26635 		}
26636 	}
26637 	/*
26638 	 * We are done with IPsec processing. Send it over the wire.
26639 	 */
26640 done:
26641 	mp = ipsec_mp->b_cont;
26642 	ipha = (ipha_t *)mp->b_rptr;
26643 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26644 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26645 		    ire);
26646 	} else {
26647 		ip6h = (ip6_t *)ipha;
26648 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26649 		    ire);
26650 	}
26651 	if (ill != NULL && ill_need_rele)
26652 		ill_refrele(ill);
26653 }
26654 
26655 /* ARGSUSED */
26656 void
26657 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26658 {
26659 	opt_restart_t	*or;
26660 	int	err;
26661 	conn_t	*connp;
26662 	cred_t	*cr;
26663 
26664 	ASSERT(CONN_Q(q));
26665 	connp = Q_TO_CONN(q);
26666 
26667 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26668 	or = (opt_restart_t *)first_mp->b_rptr;
26669 	/*
26670 	 * We checked for a db_credp the first time svr4_optcom_req
26671 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26672 	 */
26673 	cr = msg_getcred(first_mp, NULL);
26674 	ASSERT(cr != NULL);
26675 
26676 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26677 		err = svr4_optcom_req(q, first_mp, cr,
26678 		    &ip_opt_obj, B_FALSE);
26679 	} else {
26680 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26681 		err = tpi_optcom_req(q, first_mp, cr,
26682 		    &ip_opt_obj, B_FALSE);
26683 	}
26684 	if (err != EINPROGRESS) {
26685 		/* operation is done */
26686 		CONN_OPER_PENDING_DONE(connp);
26687 	}
26688 }
26689 
26690 /*
26691  * ioctls that go through a down/up sequence may need to wait for the down
26692  * to complete. This involves waiting for the ire and ipif refcnts to go down
26693  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26694  */
26695 /* ARGSUSED */
26696 void
26697 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26698 {
26699 	struct iocblk *iocp;
26700 	mblk_t *mp1;
26701 	ip_ioctl_cmd_t *ipip;
26702 	int err;
26703 	sin_t	*sin;
26704 	struct lifreq *lifr;
26705 	struct ifreq *ifr;
26706 
26707 	iocp = (struct iocblk *)mp->b_rptr;
26708 	ASSERT(ipsq != NULL);
26709 	/* Existence of mp1 verified in ip_wput_nondata */
26710 	mp1 = mp->b_cont->b_cont;
26711 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26712 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26713 		/*
26714 		 * Special case where ipx_current_ipif is not set:
26715 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26716 		 * We are here as were not able to complete the operation in
26717 		 * ipif_set_values because we could not become exclusive on
26718 		 * the new ipsq.
26719 		 */
26720 		ill_t *ill = q->q_ptr;
26721 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26722 	}
26723 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26724 
26725 	if (ipip->ipi_cmd_type == IF_CMD) {
26726 		/* This a old style SIOC[GS]IF* command */
26727 		ifr = (struct ifreq *)mp1->b_rptr;
26728 		sin = (sin_t *)&ifr->ifr_addr;
26729 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26730 		/* This a new style SIOC[GS]LIF* command */
26731 		lifr = (struct lifreq *)mp1->b_rptr;
26732 		sin = (sin_t *)&lifr->lifr_addr;
26733 	} else {
26734 		sin = NULL;
26735 	}
26736 
26737 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26738 	    q, mp, ipip, mp1->b_rptr);
26739 
26740 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26741 }
26742 
26743 /*
26744  * ioctl processing
26745  *
26746  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26747  * the ioctl command in the ioctl tables, determines the copyin data size
26748  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26749  *
26750  * ioctl processing then continues when the M_IOCDATA makes its way down to
26751  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26752  * associated 'conn' is refheld till the end of the ioctl and the general
26753  * ioctl processing function ip_process_ioctl() is called to extract the
26754  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26755  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26756  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26757  * is used to extract the ioctl's arguments.
26758  *
26759  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26760  * so goes thru the serialization primitive ipsq_try_enter. Then the
26761  * appropriate function to handle the ioctl is called based on the entry in
26762  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26763  * which also refreleases the 'conn' that was refheld at the start of the
26764  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26765  *
26766  * Many exclusive ioctls go thru an internal down up sequence as part of
26767  * the operation. For example an attempt to change the IP address of an
26768  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26769  * does all the cleanup such as deleting all ires that use this address.
26770  * Then we need to wait till all references to the interface go away.
26771  */
26772 void
26773 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26774 {
26775 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26776 	ip_ioctl_cmd_t *ipip = arg;
26777 	ip_extract_func_t *extract_funcp;
26778 	cmd_info_t ci;
26779 	int err;
26780 	boolean_t entered_ipsq = B_FALSE;
26781 
26782 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26783 
26784 	if (ipip == NULL)
26785 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26786 
26787 	/*
26788 	 * SIOCLIFADDIF needs to go thru a special path since the
26789 	 * ill may not exist yet. This happens in the case of lo0
26790 	 * which is created using this ioctl.
26791 	 */
26792 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26793 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26794 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26795 		return;
26796 	}
26797 
26798 	ci.ci_ipif = NULL;
26799 	if (ipip->ipi_cmd_type == MISC_CMD) {
26800 		/*
26801 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26802 		 */
26803 		if (ipip->ipi_cmd == IF_UNITSEL) {
26804 			/* ioctl comes down the ill */
26805 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26806 			ipif_refhold(ci.ci_ipif);
26807 		}
26808 		err = 0;
26809 		ci.ci_sin = NULL;
26810 		ci.ci_sin6 = NULL;
26811 		ci.ci_lifr = NULL;
26812 	} else {
26813 		switch (ipip->ipi_cmd_type) {
26814 		case IF_CMD:
26815 		case LIF_CMD:
26816 			extract_funcp = ip_extract_lifreq;
26817 			break;
26818 
26819 		case ARP_CMD:
26820 		case XARP_CMD:
26821 			extract_funcp = ip_extract_arpreq;
26822 			break;
26823 
26824 		case MSFILT_CMD:
26825 			extract_funcp = ip_extract_msfilter;
26826 			break;
26827 
26828 		default:
26829 			ASSERT(0);
26830 		}
26831 
26832 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26833 		if (err != 0) {
26834 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26835 			return;
26836 		}
26837 
26838 		/*
26839 		 * All of the extraction functions return a refheld ipif.
26840 		 */
26841 		ASSERT(ci.ci_ipif != NULL);
26842 	}
26843 
26844 	if (!(ipip->ipi_flags & IPI_WR)) {
26845 		/*
26846 		 * A return value of EINPROGRESS means the ioctl is
26847 		 * either queued and waiting for some reason or has
26848 		 * already completed.
26849 		 */
26850 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26851 		    ci.ci_lifr);
26852 		if (ci.ci_ipif != NULL)
26853 			ipif_refrele(ci.ci_ipif);
26854 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26855 		return;
26856 	}
26857 
26858 	ASSERT(ci.ci_ipif != NULL);
26859 
26860 	/*
26861 	 * If ipsq is non-NULL, we are already being called exclusively.
26862 	 */
26863 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26864 	if (ipsq == NULL) {
26865 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26866 		    NEW_OP, B_TRUE);
26867 		if (ipsq == NULL) {
26868 			ipif_refrele(ci.ci_ipif);
26869 			return;
26870 		}
26871 		entered_ipsq = B_TRUE;
26872 	}
26873 
26874 	/*
26875 	 * Release the ipif so that ipif_down and friends that wait for
26876 	 * references to go away are not misled about the current ipif_refcnt
26877 	 * values. We are writer so we can access the ipif even after releasing
26878 	 * the ipif.
26879 	 */
26880 	ipif_refrele(ci.ci_ipif);
26881 
26882 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26883 
26884 	/*
26885 	 * A return value of EINPROGRESS means the ioctl is
26886 	 * either queued and waiting for some reason or has
26887 	 * already completed.
26888 	 */
26889 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26890 
26891 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26892 
26893 	if (entered_ipsq)
26894 		ipsq_exit(ipsq);
26895 }
26896 
26897 /*
26898  * Complete the ioctl. Typically ioctls use the mi package and need to
26899  * do mi_copyout/mi_copy_done.
26900  */
26901 void
26902 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26903 {
26904 	conn_t	*connp = NULL;
26905 
26906 	if (err == EINPROGRESS)
26907 		return;
26908 
26909 	if (CONN_Q(q)) {
26910 		connp = Q_TO_CONN(q);
26911 		ASSERT(connp->conn_ref >= 2);
26912 	}
26913 
26914 	switch (mode) {
26915 	case COPYOUT:
26916 		if (err == 0)
26917 			mi_copyout(q, mp);
26918 		else
26919 			mi_copy_done(q, mp, err);
26920 		break;
26921 
26922 	case NO_COPYOUT:
26923 		mi_copy_done(q, mp, err);
26924 		break;
26925 
26926 	default:
26927 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26928 		break;
26929 	}
26930 
26931 	/*
26932 	 * The refhold placed at the start of the ioctl is released here.
26933 	 */
26934 	if (connp != NULL)
26935 		CONN_OPER_PENDING_DONE(connp);
26936 
26937 	if (ipsq != NULL)
26938 		ipsq_current_finish(ipsq);
26939 }
26940 
26941 /* Called from ip_wput for all non data messages */
26942 /* ARGSUSED */
26943 void
26944 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26945 {
26946 	mblk_t		*mp1;
26947 	ire_t		*ire, *fake_ire;
26948 	ill_t		*ill;
26949 	struct iocblk	*iocp;
26950 	ip_ioctl_cmd_t	*ipip;
26951 	cred_t		*cr;
26952 	conn_t		*connp;
26953 	int		err;
26954 	nce_t		*nce;
26955 	ipif_t		*ipif;
26956 	ip_stack_t	*ipst;
26957 	char		*proto_str;
26958 
26959 	if (CONN_Q(q)) {
26960 		connp = Q_TO_CONN(q);
26961 		ipst = connp->conn_netstack->netstack_ip;
26962 	} else {
26963 		connp = NULL;
26964 		ipst = ILLQ_TO_IPST(q);
26965 	}
26966 
26967 	switch (DB_TYPE(mp)) {
26968 	case M_IOCTL:
26969 		/*
26970 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26971 		 * will arrange to copy in associated control structures.
26972 		 */
26973 		ip_sioctl_copyin_setup(q, mp);
26974 		return;
26975 	case M_IOCDATA:
26976 		/*
26977 		 * Ensure that this is associated with one of our trans-
26978 		 * parent ioctls.  If it's not ours, discard it if we're
26979 		 * running as a driver, or pass it on if we're a module.
26980 		 */
26981 		iocp = (struct iocblk *)mp->b_rptr;
26982 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26983 		if (ipip == NULL) {
26984 			if (q->q_next == NULL) {
26985 				goto nak;
26986 			} else {
26987 				putnext(q, mp);
26988 			}
26989 			return;
26990 		}
26991 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
26992 			/*
26993 			 * the ioctl is one we recognise, but is not
26994 			 * consumed by IP as a module, pass M_IOCDATA
26995 			 * for processing downstream, but only for
26996 			 * common Streams ioctls.
26997 			 */
26998 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26999 				putnext(q, mp);
27000 				return;
27001 			} else {
27002 				goto nak;
27003 			}
27004 		}
27005 
27006 		/* IOCTL continuation following copyin or copyout. */
27007 		if (mi_copy_state(q, mp, NULL) == -1) {
27008 			/*
27009 			 * The copy operation failed.  mi_copy_state already
27010 			 * cleaned up, so we're out of here.
27011 			 */
27012 			return;
27013 		}
27014 		/*
27015 		 * If we just completed a copy in, we become writer and
27016 		 * continue processing in ip_sioctl_copyin_done.  If it
27017 		 * was a copy out, we call mi_copyout again.  If there is
27018 		 * nothing more to copy out, it will complete the IOCTL.
27019 		 */
27020 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27021 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27022 				mi_copy_done(q, mp, EPROTO);
27023 				return;
27024 			}
27025 			/*
27026 			 * Check for cases that need more copying.  A return
27027 			 * value of 0 means a second copyin has been started,
27028 			 * so we return; a return value of 1 means no more
27029 			 * copying is needed, so we continue.
27030 			 */
27031 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27032 			    MI_COPY_COUNT(mp) == 1) {
27033 				if (ip_copyin_msfilter(q, mp) == 0)
27034 					return;
27035 			}
27036 			/*
27037 			 * Refhold the conn, till the ioctl completes. This is
27038 			 * needed in case the ioctl ends up in the pending mp
27039 			 * list. Every mp in the ill_pending_mp list and
27040 			 * the ipx_pending_mp must have a refhold on the conn
27041 			 * to resume processing. The refhold is released when
27042 			 * the ioctl completes. (normally or abnormally)
27043 			 * In all cases ip_ioctl_finish is called to finish
27044 			 * the ioctl.
27045 			 */
27046 			if (connp != NULL) {
27047 				/* This is not a reentry */
27048 				ASSERT(ipsq == NULL);
27049 				CONN_INC_REF(connp);
27050 			} else {
27051 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27052 					mi_copy_done(q, mp, EINVAL);
27053 					return;
27054 				}
27055 			}
27056 
27057 			ip_process_ioctl(ipsq, q, mp, ipip);
27058 
27059 		} else {
27060 			mi_copyout(q, mp);
27061 		}
27062 		return;
27063 nak:
27064 		iocp->ioc_error = EINVAL;
27065 		mp->b_datap->db_type = M_IOCNAK;
27066 		iocp->ioc_count = 0;
27067 		qreply(q, mp);
27068 		return;
27069 
27070 	case M_IOCNAK:
27071 		/*
27072 		 * The only way we could get here is if a resolver didn't like
27073 		 * an IOCTL we sent it.	 This shouldn't happen.
27074 		 */
27075 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27076 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27077 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27078 		freemsg(mp);
27079 		return;
27080 	case M_IOCACK:
27081 		/* /dev/ip shouldn't see this */
27082 		if (CONN_Q(q))
27083 			goto nak;
27084 
27085 		/*
27086 		 * Finish socket ioctls passed through to ARP.  We use the
27087 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27088 		 * we need to become writer before calling ip_sioctl_iocack().
27089 		 * Note that qwriter_ip() will release the refhold, and that a
27090 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27091 		 * ill stream.
27092 		 */
27093 		iocp = (struct iocblk *)mp->b_rptr;
27094 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27095 			ip_sioctl_iocack(NULL, q, mp, NULL);
27096 			return;
27097 		}
27098 
27099 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27100 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27101 		ill = q->q_ptr;
27102 		ill_refhold(ill);
27103 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27104 		return;
27105 	case M_FLUSH:
27106 		if (*mp->b_rptr & FLUSHW)
27107 			flushq(q, FLUSHALL);
27108 		if (q->q_next) {
27109 			putnext(q, mp);
27110 			return;
27111 		}
27112 		if (*mp->b_rptr & FLUSHR) {
27113 			*mp->b_rptr &= ~FLUSHW;
27114 			qreply(q, mp);
27115 			return;
27116 		}
27117 		freemsg(mp);
27118 		return;
27119 	case IRE_DB_REQ_TYPE:
27120 		if (connp == NULL) {
27121 			proto_str = "IRE_DB_REQ_TYPE";
27122 			goto protonak;
27123 		}
27124 		/* An Upper Level Protocol wants a copy of an IRE. */
27125 		ip_ire_req(q, mp);
27126 		return;
27127 	case M_CTL:
27128 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27129 			break;
27130 
27131 		/* M_CTL messages are used by ARP to tell us things. */
27132 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27133 			break;
27134 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27135 		case AR_ENTRY_SQUERY:
27136 			putnext(q, mp);
27137 			return;
27138 		case AR_CLIENT_NOTIFY:
27139 			ip_arp_news(q, mp);
27140 			return;
27141 		case AR_DLPIOP_DONE:
27142 			ASSERT(q->q_next != NULL);
27143 			ill = (ill_t *)q->q_ptr;
27144 			/* qwriter_ip releases the refhold */
27145 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27146 			ill_refhold(ill);
27147 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27148 			return;
27149 		case AR_ARP_CLOSING:
27150 			/*
27151 			 * ARP (above us) is closing. If no ARP bringup is
27152 			 * currently pending, ack the message so that ARP
27153 			 * can complete its close. Also mark ill_arp_closing
27154 			 * so that new ARP bringups will fail. If any
27155 			 * ARP bringup is currently in progress, we will
27156 			 * ack this when the current ARP bringup completes.
27157 			 */
27158 			ASSERT(q->q_next != NULL);
27159 			ill = (ill_t *)q->q_ptr;
27160 			mutex_enter(&ill->ill_lock);
27161 			ill->ill_arp_closing = 1;
27162 			if (!ill->ill_arp_bringup_pending) {
27163 				mutex_exit(&ill->ill_lock);
27164 				qreply(q, mp);
27165 			} else {
27166 				mutex_exit(&ill->ill_lock);
27167 				freemsg(mp);
27168 			}
27169 			return;
27170 		case AR_ARP_EXTEND:
27171 			/*
27172 			 * The ARP module above us is capable of duplicate
27173 			 * address detection.  Old ATM drivers will not send
27174 			 * this message.
27175 			 */
27176 			ASSERT(q->q_next != NULL);
27177 			ill = (ill_t *)q->q_ptr;
27178 			ill->ill_arp_extend = B_TRUE;
27179 			freemsg(mp);
27180 			return;
27181 		default:
27182 			break;
27183 		}
27184 		break;
27185 	case M_PROTO:
27186 	case M_PCPROTO:
27187 		/*
27188 		 * The only PROTO messages we expect are copies of option
27189 		 * negotiation acknowledgements, AH and ESP bind requests
27190 		 * are also expected.
27191 		 */
27192 		switch (((union T_primitives *)mp->b_rptr)->type) {
27193 		case O_T_BIND_REQ:
27194 		case T_BIND_REQ: {
27195 			/* Request can get queued in bind */
27196 			if (connp == NULL) {
27197 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27198 				goto protonak;
27199 			}
27200 			/*
27201 			 * The transports except SCTP call ip_bind_{v4,v6}()
27202 			 * directly instead of a a putnext. SCTP doesn't
27203 			 * generate any T_BIND_REQ since it has its own
27204 			 * fanout data structures. However, ESP and AH
27205 			 * come in for regular binds; all other cases are
27206 			 * bind retries.
27207 			 */
27208 			ASSERT(!IPCL_IS_SCTP(connp));
27209 
27210 			/* Don't increment refcnt if this is a re-entry */
27211 			if (ipsq == NULL)
27212 				CONN_INC_REF(connp);
27213 
27214 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27215 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27216 			ASSERT(mp != NULL);
27217 
27218 			ASSERT(!IPCL_IS_TCP(connp));
27219 			ASSERT(!IPCL_IS_UDP(connp));
27220 			ASSERT(!IPCL_IS_RAWIP(connp));
27221 			ASSERT(!IPCL_IS_IPTUN(connp));
27222 
27223 			/* The case of AH and ESP */
27224 			qreply(q, mp);
27225 			CONN_OPER_PENDING_DONE(connp);
27226 			return;
27227 		}
27228 		case T_SVR4_OPTMGMT_REQ:
27229 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27230 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27231 
27232 			if (connp == NULL) {
27233 				proto_str = "T_SVR4_OPTMGMT_REQ";
27234 				goto protonak;
27235 			}
27236 
27237 			/*
27238 			 * All Solaris components should pass a db_credp
27239 			 * for this TPI message, hence we ASSERT.
27240 			 * But in case there is some other M_PROTO that looks
27241 			 * like a TPI message sent by some other kernel
27242 			 * component, we check and return an error.
27243 			 */
27244 			cr = msg_getcred(mp, NULL);
27245 			ASSERT(cr != NULL);
27246 			if (cr == NULL) {
27247 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27248 				if (mp != NULL)
27249 					qreply(q, mp);
27250 				return;
27251 			}
27252 
27253 			if (!snmpcom_req(q, mp, ip_snmp_set,
27254 			    ip_snmp_get, cr)) {
27255 				/*
27256 				 * Call svr4_optcom_req so that it can
27257 				 * generate the ack. We don't come here
27258 				 * if this operation is being restarted.
27259 				 * ip_restart_optmgmt will drop the conn ref.
27260 				 * In the case of ipsec option after the ipsec
27261 				 * load is complete conn_restart_ipsec_waiter
27262 				 * drops the conn ref.
27263 				 */
27264 				ASSERT(ipsq == NULL);
27265 				CONN_INC_REF(connp);
27266 				if (ip_check_for_ipsec_opt(q, mp))
27267 					return;
27268 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27269 				    B_FALSE);
27270 				if (err != EINPROGRESS) {
27271 					/* Operation is done */
27272 					CONN_OPER_PENDING_DONE(connp);
27273 				}
27274 			}
27275 			return;
27276 		case T_OPTMGMT_REQ:
27277 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27278 			/*
27279 			 * Note: No snmpcom_req support through new
27280 			 * T_OPTMGMT_REQ.
27281 			 * Call tpi_optcom_req so that it can
27282 			 * generate the ack.
27283 			 */
27284 			if (connp == NULL) {
27285 				proto_str = "T_OPTMGMT_REQ";
27286 				goto protonak;
27287 			}
27288 
27289 			/*
27290 			 * All Solaris components should pass a db_credp
27291 			 * for this TPI message, hence we ASSERT.
27292 			 * But in case there is some other M_PROTO that looks
27293 			 * like a TPI message sent by some other kernel
27294 			 * component, we check and return an error.
27295 			 */
27296 			cr = msg_getcred(mp, NULL);
27297 			ASSERT(cr != NULL);
27298 			if (cr == NULL) {
27299 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27300 				if (mp != NULL)
27301 					qreply(q, mp);
27302 				return;
27303 			}
27304 			ASSERT(ipsq == NULL);
27305 			/*
27306 			 * We don't come here for restart. ip_restart_optmgmt
27307 			 * will drop the conn ref. In the case of ipsec option
27308 			 * after the ipsec load is complete
27309 			 * conn_restart_ipsec_waiter drops the conn ref.
27310 			 */
27311 			CONN_INC_REF(connp);
27312 			if (ip_check_for_ipsec_opt(q, mp))
27313 				return;
27314 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27315 			if (err != EINPROGRESS) {
27316 				/* Operation is done */
27317 				CONN_OPER_PENDING_DONE(connp);
27318 			}
27319 			return;
27320 		case T_UNBIND_REQ:
27321 			if (connp == NULL) {
27322 				proto_str = "T_UNBIND_REQ";
27323 				goto protonak;
27324 			}
27325 			ip_unbind(Q_TO_CONN(q));
27326 			mp = mi_tpi_ok_ack_alloc(mp);
27327 			qreply(q, mp);
27328 			return;
27329 		default:
27330 			/*
27331 			 * Have to drop any DLPI messages coming down from
27332 			 * arp (such as an info_req which would cause ip
27333 			 * to receive an extra info_ack if it was passed
27334 			 * through.
27335 			 */
27336 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27337 			    (int)*(uint_t *)mp->b_rptr));
27338 			freemsg(mp);
27339 			return;
27340 		}
27341 		/* NOTREACHED */
27342 	case IRE_DB_TYPE: {
27343 		nce_t		*nce;
27344 		ill_t		*ill;
27345 		in6_addr_t	gw_addr_v6;
27346 
27347 		/*
27348 		 * This is a response back from a resolver.  It
27349 		 * consists of a message chain containing:
27350 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27351 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27352 		 * The LL_HDR_MBLK is the DLPI header to use to get
27353 		 * the attached packet, and subsequent ones for the
27354 		 * same destination, transmitted.
27355 		 */
27356 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27357 			break;
27358 		/*
27359 		 * First, check to make sure the resolution succeeded.
27360 		 * If it failed, the second mblk will be empty.
27361 		 * If it is, free the chain, dropping the packet.
27362 		 * (We must ire_delete the ire; that frees the ire mblk)
27363 		 * We're doing this now to support PVCs for ATM; it's
27364 		 * a partial xresolv implementation. When we fully implement
27365 		 * xresolv interfaces, instead of freeing everything here
27366 		 * we'll initiate neighbor discovery.
27367 		 *
27368 		 * For v4 (ARP and other external resolvers) the resolver
27369 		 * frees the message, so no check is needed. This check
27370 		 * is required, though, for a full xresolve implementation.
27371 		 * Including this code here now both shows how external
27372 		 * resolvers can NACK a resolution request using an
27373 		 * existing design that has no specific provisions for NACKs,
27374 		 * and also takes into account that the current non-ARP
27375 		 * external resolver has been coded to use this method of
27376 		 * NACKing for all IPv6 (xresolv) cases,
27377 		 * whether our xresolv implementation is complete or not.
27378 		 *
27379 		 */
27380 		ire = (ire_t *)mp->b_rptr;
27381 		ill = ire_to_ill(ire);
27382 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27383 		if (mp1->b_rptr == mp1->b_wptr) {
27384 			if (ire->ire_ipversion == IPV6_VERSION) {
27385 				/*
27386 				 * XRESOLV interface.
27387 				 */
27388 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27389 				mutex_enter(&ire->ire_lock);
27390 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27391 				mutex_exit(&ire->ire_lock);
27392 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27393 					nce = ndp_lookup_v6(ill, B_FALSE,
27394 					    &ire->ire_addr_v6, B_FALSE);
27395 				} else {
27396 					nce = ndp_lookup_v6(ill, B_FALSE,
27397 					    &gw_addr_v6, B_FALSE);
27398 				}
27399 				if (nce != NULL) {
27400 					nce_resolv_failed(nce);
27401 					ndp_delete(nce);
27402 					NCE_REFRELE(nce);
27403 				}
27404 			}
27405 			mp->b_cont = NULL;
27406 			freemsg(mp1);		/* frees the pkt as well */
27407 			ASSERT(ire->ire_nce == NULL);
27408 			ire_delete((ire_t *)mp->b_rptr);
27409 			return;
27410 		}
27411 
27412 		/*
27413 		 * Split them into IRE_MBLK and pkt and feed it into
27414 		 * ire_add_then_send. Then in ire_add_then_send
27415 		 * the IRE will be added, and then the packet will be
27416 		 * run back through ip_wput. This time it will make
27417 		 * it to the wire.
27418 		 */
27419 		mp->b_cont = NULL;
27420 		mp = mp1->b_cont;		/* now, mp points to pkt */
27421 		mp1->b_cont = NULL;
27422 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27423 		if (ire->ire_ipversion == IPV6_VERSION) {
27424 			/*
27425 			 * XRESOLV interface. Find the nce and put a copy
27426 			 * of the dl_unitdata_req in nce_res_mp
27427 			 */
27428 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27429 			mutex_enter(&ire->ire_lock);
27430 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27431 			mutex_exit(&ire->ire_lock);
27432 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27433 				nce = ndp_lookup_v6(ill, B_FALSE,
27434 				    &ire->ire_addr_v6, B_FALSE);
27435 			} else {
27436 				nce = ndp_lookup_v6(ill, B_FALSE,
27437 				    &gw_addr_v6, B_FALSE);
27438 			}
27439 			if (nce != NULL) {
27440 				/*
27441 				 * We have to protect nce_res_mp here
27442 				 * from being accessed by other threads
27443 				 * while we change the mblk pointer.
27444 				 * Other functions will also lock the nce when
27445 				 * accessing nce_res_mp.
27446 				 *
27447 				 * The reason we change the mblk pointer
27448 				 * here rather than copying the resolved address
27449 				 * into the template is that, unlike with
27450 				 * ethernet, we have no guarantee that the
27451 				 * resolved address length will be
27452 				 * smaller than or equal to the lla length
27453 				 * with which the template was allocated,
27454 				 * (for ethernet, they're equal)
27455 				 * so we have to use the actual resolved
27456 				 * address mblk - which holds the real
27457 				 * dl_unitdata_req with the resolved address.
27458 				 *
27459 				 * Doing this is the same behavior as was
27460 				 * previously used in the v4 ARP case.
27461 				 */
27462 				mutex_enter(&nce->nce_lock);
27463 				if (nce->nce_res_mp != NULL)
27464 					freemsg(nce->nce_res_mp);
27465 				nce->nce_res_mp = mp1;
27466 				mutex_exit(&nce->nce_lock);
27467 				/*
27468 				 * We do a fastpath probe here because
27469 				 * we have resolved the address without
27470 				 * using Neighbor Discovery.
27471 				 * In the non-XRESOLV v6 case, the fastpath
27472 				 * probe is done right after neighbor
27473 				 * discovery completes.
27474 				 */
27475 				if (nce->nce_res_mp != NULL) {
27476 					int res;
27477 					nce_fastpath_list_add(nce);
27478 					res = ill_fastpath_probe(ill,
27479 					    nce->nce_res_mp);
27480 					if (res != 0 && res != EAGAIN)
27481 						nce_fastpath_list_delete(nce);
27482 				}
27483 
27484 				ire_add_then_send(q, ire, mp);
27485 				/*
27486 				 * Now we have to clean out any packets
27487 				 * that may have been queued on the nce
27488 				 * while it was waiting for address resolution
27489 				 * to complete.
27490 				 */
27491 				mutex_enter(&nce->nce_lock);
27492 				mp1 = nce->nce_qd_mp;
27493 				nce->nce_qd_mp = NULL;
27494 				mutex_exit(&nce->nce_lock);
27495 				while (mp1 != NULL) {
27496 					mblk_t *nxt_mp;
27497 					queue_t *fwdq = NULL;
27498 					ill_t   *inbound_ill;
27499 					uint_t ifindex;
27500 
27501 					nxt_mp = mp1->b_next;
27502 					mp1->b_next = NULL;
27503 					/*
27504 					 * Retrieve ifindex stored in
27505 					 * ip_rput_data_v6()
27506 					 */
27507 					ifindex =
27508 					    (uint_t)(uintptr_t)mp1->b_prev;
27509 					inbound_ill =
27510 					    ill_lookup_on_ifindex(ifindex,
27511 					    B_TRUE, NULL, NULL, NULL,
27512 					    NULL, ipst);
27513 					mp1->b_prev = NULL;
27514 					if (inbound_ill != NULL)
27515 						fwdq = inbound_ill->ill_rq;
27516 
27517 					if (fwdq != NULL) {
27518 						put(fwdq, mp1);
27519 						ill_refrele(inbound_ill);
27520 					} else
27521 						put(WR(ill->ill_rq), mp1);
27522 					mp1 = nxt_mp;
27523 				}
27524 				NCE_REFRELE(nce);
27525 			} else {	/* nce is NULL; clean up */
27526 				ire_delete(ire);
27527 				freemsg(mp);
27528 				freemsg(mp1);
27529 				return;
27530 			}
27531 		} else {
27532 			nce_t *arpce;
27533 			/*
27534 			 * Link layer resolution succeeded. Recompute the
27535 			 * ire_nce.
27536 			 */
27537 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27538 			if ((arpce = ndp_lookup_v4(ill,
27539 			    (ire->ire_gateway_addr != INADDR_ANY ?
27540 			    &ire->ire_gateway_addr : &ire->ire_addr),
27541 			    B_FALSE)) == NULL) {
27542 				freeb(ire->ire_mp);
27543 				freeb(mp1);
27544 				freemsg(mp);
27545 				return;
27546 			}
27547 			mutex_enter(&arpce->nce_lock);
27548 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27549 			if (arpce->nce_state == ND_REACHABLE) {
27550 				/*
27551 				 * Someone resolved this before us;
27552 				 * cleanup the res_mp. Since ire has
27553 				 * not been added yet, the call to ire_add_v4
27554 				 * from ire_add_then_send (when a dup is
27555 				 * detected) will clean up the ire.
27556 				 */
27557 				freeb(mp1);
27558 			} else {
27559 				ASSERT(arpce->nce_res_mp == NULL);
27560 				arpce->nce_res_mp = mp1;
27561 				arpce->nce_state = ND_REACHABLE;
27562 			}
27563 			mutex_exit(&arpce->nce_lock);
27564 			if (ire->ire_marks & IRE_MARK_NOADD) {
27565 				/*
27566 				 * this ire will not be added to the ire
27567 				 * cache table, so we can set the ire_nce
27568 				 * here, as there are no atomicity constraints.
27569 				 */
27570 				ire->ire_nce = arpce;
27571 				/*
27572 				 * We are associating this nce with the ire
27573 				 * so change the nce ref taken in
27574 				 * ndp_lookup_v4() from
27575 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27576 				 */
27577 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27578 			} else {
27579 				NCE_REFRELE(arpce);
27580 			}
27581 			ire_add_then_send(q, ire, mp);
27582 		}
27583 		return;	/* All is well, the packet has been sent. */
27584 	}
27585 	case IRE_ARPRESOLVE_TYPE: {
27586 
27587 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27588 			break;
27589 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27590 		mp->b_cont = NULL;
27591 		/*
27592 		 * First, check to make sure the resolution succeeded.
27593 		 * If it failed, the second mblk will be empty.
27594 		 */
27595 		if (mp1->b_rptr == mp1->b_wptr) {
27596 			/* cleanup  the incomplete ire, free queued packets */
27597 			freemsg(mp); /* fake ire */
27598 			freeb(mp1);  /* dl_unitdata response */
27599 			return;
27600 		}
27601 
27602 		/*
27603 		 * Update any incomplete nce_t found. We search the ctable
27604 		 * and find the nce from the ire->ire_nce because we need
27605 		 * to pass the ire to ip_xmit_v4 later, and can find both
27606 		 * ire and nce in one lookup.
27607 		 */
27608 		fake_ire = (ire_t *)mp->b_rptr;
27609 
27610 		/*
27611 		 * By the time we come back here from ARP the logical outgoing
27612 		 * interface of the incomplete ire we added in ire_forward()
27613 		 * could have disappeared, causing the incomplete ire to also
27614 		 * disappear.  So we need to retreive the proper ipif for the
27615 		 * ire before looking in ctable.  In the case of IPMP, the
27616 		 * ipif may be on the IPMP ill, so look it up based on the
27617 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27618 		 * Then, we can verify that ire_ipif_seqid still exists.
27619 		 */
27620 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27621 		    NULL, NULL, NULL, NULL, ipst);
27622 		if (ill == NULL) {
27623 			ip1dbg(("ill for incomplete ire vanished\n"));
27624 			freemsg(mp); /* fake ire */
27625 			freeb(mp1);  /* dl_unitdata response */
27626 			return;
27627 		}
27628 
27629 		/* Get the outgoing ipif */
27630 		mutex_enter(&ill->ill_lock);
27631 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27632 		if (ipif == NULL) {
27633 			mutex_exit(&ill->ill_lock);
27634 			ill_refrele(ill);
27635 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27636 			freemsg(mp); /* fake_ire */
27637 			freeb(mp1);  /* dl_unitdata response */
27638 			return;
27639 		}
27640 
27641 		ipif_refhold_locked(ipif);
27642 		mutex_exit(&ill->ill_lock);
27643 		ill_refrele(ill);
27644 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27645 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27646 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27647 		ipif_refrele(ipif);
27648 		if (ire == NULL) {
27649 			/*
27650 			 * no ire was found; check if there is an nce
27651 			 * for this lookup; if it has no ire's pointing at it
27652 			 * cleanup.
27653 			 */
27654 			if ((nce = ndp_lookup_v4(q->q_ptr,
27655 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27656 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27657 			    B_FALSE)) != NULL) {
27658 				/*
27659 				 * cleanup:
27660 				 * We check for refcnt 2 (one for the nce
27661 				 * hash list + 1 for the ref taken by
27662 				 * ndp_lookup_v4) to check that there are
27663 				 * no ire's pointing at the nce.
27664 				 */
27665 				if (nce->nce_refcnt == 2)
27666 					ndp_delete(nce);
27667 				NCE_REFRELE(nce);
27668 			}
27669 			freeb(mp1);  /* dl_unitdata response */
27670 			freemsg(mp); /* fake ire */
27671 			return;
27672 		}
27673 
27674 		nce = ire->ire_nce;
27675 		DTRACE_PROBE2(ire__arpresolve__type,
27676 		    ire_t *, ire, nce_t *, nce);
27677 		mutex_enter(&nce->nce_lock);
27678 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27679 		if (nce->nce_state == ND_REACHABLE) {
27680 			/*
27681 			 * Someone resolved this before us;
27682 			 * our response is not needed any more.
27683 			 */
27684 			mutex_exit(&nce->nce_lock);
27685 			freeb(mp1);  /* dl_unitdata response */
27686 		} else {
27687 			ASSERT(nce->nce_res_mp == NULL);
27688 			nce->nce_res_mp = mp1;
27689 			nce->nce_state = ND_REACHABLE;
27690 			mutex_exit(&nce->nce_lock);
27691 			nce_fastpath(nce);
27692 		}
27693 		/*
27694 		 * The cached nce_t has been updated to be reachable;
27695 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27696 		 */
27697 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27698 		freemsg(mp);
27699 		/*
27700 		 * send out queued packets.
27701 		 */
27702 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27703 
27704 		IRE_REFRELE(ire);
27705 		return;
27706 	}
27707 	default:
27708 		break;
27709 	}
27710 	if (q->q_next) {
27711 		putnext(q, mp);
27712 	} else
27713 		freemsg(mp);
27714 	return;
27715 
27716 protonak:
27717 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27718 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27719 		qreply(q, mp);
27720 }
27721 
27722 /*
27723  * Process IP options in an outbound packet.  Modify the destination if there
27724  * is a source route option.
27725  * Returns non-zero if something fails in which case an ICMP error has been
27726  * sent and mp freed.
27727  */
27728 static int
27729 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27730     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27731 {
27732 	ipoptp_t	opts;
27733 	uchar_t		*opt;
27734 	uint8_t		optval;
27735 	uint8_t		optlen;
27736 	ipaddr_t	dst;
27737 	intptr_t	code = 0;
27738 	mblk_t		*mp;
27739 	ire_t		*ire = NULL;
27740 
27741 	ip2dbg(("ip_wput_options\n"));
27742 	mp = ipsec_mp;
27743 	if (mctl_present) {
27744 		mp = ipsec_mp->b_cont;
27745 	}
27746 
27747 	dst = ipha->ipha_dst;
27748 	for (optval = ipoptp_first(&opts, ipha);
27749 	    optval != IPOPT_EOL;
27750 	    optval = ipoptp_next(&opts)) {
27751 		opt = opts.ipoptp_cur;
27752 		optlen = opts.ipoptp_len;
27753 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27754 		    optval, optlen));
27755 		switch (optval) {
27756 			uint32_t off;
27757 		case IPOPT_SSRR:
27758 		case IPOPT_LSRR:
27759 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27760 				ip1dbg((
27761 				    "ip_wput_options: bad option offset\n"));
27762 				code = (char *)&opt[IPOPT_OLEN] -
27763 				    (char *)ipha;
27764 				goto param_prob;
27765 			}
27766 			off = opt[IPOPT_OFFSET];
27767 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27768 			    ntohl(dst)));
27769 			/*
27770 			 * For strict: verify that dst is directly
27771 			 * reachable.
27772 			 */
27773 			if (optval == IPOPT_SSRR) {
27774 				ire = ire_ftable_lookup(dst, 0, 0,
27775 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27776 				    msg_getlabel(mp),
27777 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27778 				if (ire == NULL) {
27779 					ip1dbg(("ip_wput_options: SSRR not"
27780 					    " directly reachable: 0x%x\n",
27781 					    ntohl(dst)));
27782 					goto bad_src_route;
27783 				}
27784 				ire_refrele(ire);
27785 			}
27786 			break;
27787 		case IPOPT_RR:
27788 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27789 				ip1dbg((
27790 				    "ip_wput_options: bad option offset\n"));
27791 				code = (char *)&opt[IPOPT_OLEN] -
27792 				    (char *)ipha;
27793 				goto param_prob;
27794 			}
27795 			break;
27796 		case IPOPT_TS:
27797 			/*
27798 			 * Verify that length >=5 and that there is either
27799 			 * room for another timestamp or that the overflow
27800 			 * counter is not maxed out.
27801 			 */
27802 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27803 			if (optlen < IPOPT_MINLEN_IT) {
27804 				goto param_prob;
27805 			}
27806 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27807 				ip1dbg((
27808 				    "ip_wput_options: bad option offset\n"));
27809 				code = (char *)&opt[IPOPT_OFFSET] -
27810 				    (char *)ipha;
27811 				goto param_prob;
27812 			}
27813 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27814 			case IPOPT_TS_TSONLY:
27815 				off = IPOPT_TS_TIMELEN;
27816 				break;
27817 			case IPOPT_TS_TSANDADDR:
27818 			case IPOPT_TS_PRESPEC:
27819 			case IPOPT_TS_PRESPEC_RFC791:
27820 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27821 				break;
27822 			default:
27823 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27824 				    (char *)ipha;
27825 				goto param_prob;
27826 			}
27827 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27828 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27829 				/*
27830 				 * No room and the overflow counter is 15
27831 				 * already.
27832 				 */
27833 				goto param_prob;
27834 			}
27835 			break;
27836 		}
27837 	}
27838 
27839 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27840 		return (0);
27841 
27842 	ip1dbg(("ip_wput_options: error processing IP options."));
27843 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27844 
27845 param_prob:
27846 	/*
27847 	 * Since ip_wput() isn't close to finished, we fill
27848 	 * in enough of the header for credible error reporting.
27849 	 */
27850 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27851 		/* Failed */
27852 		freemsg(ipsec_mp);
27853 		return (-1);
27854 	}
27855 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27856 	return (-1);
27857 
27858 bad_src_route:
27859 	/*
27860 	 * Since ip_wput() isn't close to finished, we fill
27861 	 * in enough of the header for credible error reporting.
27862 	 */
27863 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27864 		/* Failed */
27865 		freemsg(ipsec_mp);
27866 		return (-1);
27867 	}
27868 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27869 	return (-1);
27870 }
27871 
27872 /*
27873  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27874  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27875  * thru /etc/system.
27876  */
27877 #define	CONN_MAXDRAINCNT	64
27878 
27879 static void
27880 conn_drain_init(ip_stack_t *ipst)
27881 {
27882 	int i, j;
27883 	idl_tx_list_t *itl_tx;
27884 
27885 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27886 
27887 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27888 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27889 		/*
27890 		 * Default value of the number of drainers is the
27891 		 * number of cpus, subject to maximum of 8 drainers.
27892 		 */
27893 		if (boot_max_ncpus != -1)
27894 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27895 		else
27896 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27897 	}
27898 
27899 	ipst->ips_idl_tx_list =
27900 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
27901 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27902 		itl_tx =  &ipst->ips_idl_tx_list[i];
27903 		itl_tx->txl_drain_list =
27904 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27905 		    sizeof (idl_t), KM_SLEEP);
27906 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
27907 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
27908 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
27909 			    MUTEX_DEFAULT, NULL);
27910 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
27911 		}
27912 	}
27913 }
27914 
27915 static void
27916 conn_drain_fini(ip_stack_t *ipst)
27917 {
27918 	int i;
27919 	idl_tx_list_t *itl_tx;
27920 
27921 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27922 		itl_tx =  &ipst->ips_idl_tx_list[i];
27923 		kmem_free(itl_tx->txl_drain_list,
27924 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27925 	}
27926 	kmem_free(ipst->ips_idl_tx_list,
27927 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
27928 	ipst->ips_idl_tx_list = NULL;
27929 }
27930 
27931 /*
27932  * Note: For an overview of how flowcontrol is handled in IP please see the
27933  * IP Flowcontrol notes at the top of this file.
27934  *
27935  * Flow control has blocked us from proceeding. Insert the given conn in one
27936  * of the conn drain lists. These conn wq's will be qenabled later on when
27937  * STREAMS flow control does a backenable. conn_walk_drain will enable
27938  * the first conn in each of these drain lists. Each of these qenabled conns
27939  * in turn enables the next in the list, after it runs, or when it closes,
27940  * thus sustaining the drain process.
27941  */
27942 void
27943 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
27944 {
27945 	idl_t	*idl = tx_list->txl_drain_list;
27946 	uint_t	index;
27947 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27948 
27949 	mutex_enter(&connp->conn_lock);
27950 	if (connp->conn_state_flags & CONN_CLOSING) {
27951 		/*
27952 		 * The conn is closing as a result of which CONN_CLOSING
27953 		 * is set. Return.
27954 		 */
27955 		mutex_exit(&connp->conn_lock);
27956 		return;
27957 	} else if (connp->conn_idl == NULL) {
27958 		/*
27959 		 * Assign the next drain list round robin. We dont' use
27960 		 * a lock, and thus it may not be strictly round robin.
27961 		 * Atomicity of load/stores is enough to make sure that
27962 		 * conn_drain_list_index is always within bounds.
27963 		 */
27964 		index = tx_list->txl_drain_index;
27965 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27966 		connp->conn_idl = &tx_list->txl_drain_list[index];
27967 		index++;
27968 		if (index == ipst->ips_conn_drain_list_cnt)
27969 			index = 0;
27970 		tx_list->txl_drain_index = index;
27971 	}
27972 	mutex_exit(&connp->conn_lock);
27973 
27974 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27975 	if ((connp->conn_drain_prev != NULL) ||
27976 	    (connp->conn_state_flags & CONN_CLOSING)) {
27977 		/*
27978 		 * The conn is already in the drain list, OR
27979 		 * the conn is closing. We need to check again for
27980 		 * the closing case again since close can happen
27981 		 * after we drop the conn_lock, and before we
27982 		 * acquire the CONN_DRAIN_LIST_LOCK.
27983 		 */
27984 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27985 		return;
27986 	} else {
27987 		idl = connp->conn_idl;
27988 	}
27989 
27990 	/*
27991 	 * The conn is not in the drain list. Insert it at the
27992 	 * tail of the drain list. The drain list is circular
27993 	 * and doubly linked. idl_conn points to the 1st element
27994 	 * in the list.
27995 	 */
27996 	if (idl->idl_conn == NULL) {
27997 		idl->idl_conn = connp;
27998 		connp->conn_drain_next = connp;
27999 		connp->conn_drain_prev = connp;
28000 	} else {
28001 		conn_t *head = idl->idl_conn;
28002 
28003 		connp->conn_drain_next = head;
28004 		connp->conn_drain_prev = head->conn_drain_prev;
28005 		head->conn_drain_prev->conn_drain_next = connp;
28006 		head->conn_drain_prev = connp;
28007 	}
28008 	/*
28009 	 * For non streams based sockets assert flow control.
28010 	 */
28011 	if (IPCL_IS_NONSTR(connp)) {
28012 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28013 		(*connp->conn_upcalls->su_txq_full)
28014 		    (connp->conn_upper_handle, B_TRUE);
28015 	} else {
28016 		conn_setqfull(connp);
28017 		noenable(connp->conn_wq);
28018 	}
28019 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28020 }
28021 
28022 /*
28023  * This conn is closing, and we are called from ip_close. OR
28024  * This conn has been serviced by ip_wsrv, and we need to do the tail
28025  * processing.
28026  * If this conn is part of the drain list, we may need to sustain the drain
28027  * process by qenabling the next conn in the drain list. We may also need to
28028  * remove this conn from the list, if it is done.
28029  */
28030 static void
28031 conn_drain_tail(conn_t *connp, boolean_t closing)
28032 {
28033 	idl_t *idl;
28034 
28035 	/*
28036 	 * connp->conn_idl is stable at this point, and no lock is needed
28037 	 * to check it. If we are called from ip_close, close has already
28038 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28039 	 * called us only because conn_idl is non-null. If we are called thru
28040 	 * service, conn_idl could be null, but it cannot change because
28041 	 * service is single-threaded per queue, and there cannot be another
28042 	 * instance of service trying to call conn_drain_insert on this conn
28043 	 * now.
28044 	 */
28045 	ASSERT(!closing || (connp->conn_idl != NULL));
28046 
28047 	/*
28048 	 * If connp->conn_idl is null, the conn has not been inserted into any
28049 	 * drain list even once since creation of the conn. Just return.
28050 	 */
28051 	if (connp->conn_idl == NULL)
28052 		return;
28053 
28054 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28055 
28056 	if (connp->conn_drain_prev == NULL) {
28057 		/* This conn is currently not in the drain list.  */
28058 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28059 		return;
28060 	}
28061 	idl = connp->conn_idl;
28062 	if (idl->idl_conn_draining == connp) {
28063 		/*
28064 		 * This conn is the current drainer. If this is the last conn
28065 		 * in the drain list, we need to do more checks, in the 'if'
28066 		 * below. Otherwwise we need to just qenable the next conn,
28067 		 * to sustain the draining, and is handled in the 'else'
28068 		 * below.
28069 		 */
28070 		if (connp->conn_drain_next == idl->idl_conn) {
28071 			/*
28072 			 * This conn is the last in this list. This round
28073 			 * of draining is complete. If idl_repeat is set,
28074 			 * it means another flow enabling has happened from
28075 			 * the driver/streams and we need to another round
28076 			 * of draining.
28077 			 * If there are more than 2 conns in the drain list,
28078 			 * do a left rotate by 1, so that all conns except the
28079 			 * conn at the head move towards the head by 1, and the
28080 			 * the conn at the head goes to the tail. This attempts
28081 			 * a more even share for all queues that are being
28082 			 * drained.
28083 			 */
28084 			if ((connp->conn_drain_next != connp) &&
28085 			    (idl->idl_conn->conn_drain_next != connp)) {
28086 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28087 			}
28088 			if (idl->idl_repeat) {
28089 				qenable(idl->idl_conn->conn_wq);
28090 				idl->idl_conn_draining = idl->idl_conn;
28091 				idl->idl_repeat = 0;
28092 			} else {
28093 				idl->idl_conn_draining = NULL;
28094 			}
28095 		} else {
28096 			/*
28097 			 * If the next queue that we are now qenable'ing,
28098 			 * is closing, it will remove itself from this list
28099 			 * and qenable the subsequent queue in ip_close().
28100 			 * Serialization is acheived thru idl_lock.
28101 			 */
28102 			qenable(connp->conn_drain_next->conn_wq);
28103 			idl->idl_conn_draining = connp->conn_drain_next;
28104 		}
28105 	}
28106 	if (!connp->conn_did_putbq || closing) {
28107 		/*
28108 		 * Remove ourself from the drain list, if we did not do
28109 		 * a putbq, or if the conn is closing.
28110 		 * Note: It is possible that q->q_first is non-null. It means
28111 		 * that these messages landed after we did a enableok() in
28112 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28113 		 * service them.
28114 		 */
28115 		if (connp->conn_drain_next == connp) {
28116 			/* Singleton in the list */
28117 			ASSERT(connp->conn_drain_prev == connp);
28118 			idl->idl_conn = NULL;
28119 			idl->idl_conn_draining = NULL;
28120 		} else {
28121 			connp->conn_drain_prev->conn_drain_next =
28122 			    connp->conn_drain_next;
28123 			connp->conn_drain_next->conn_drain_prev =
28124 			    connp->conn_drain_prev;
28125 			if (idl->idl_conn == connp)
28126 				idl->idl_conn = connp->conn_drain_next;
28127 			ASSERT(idl->idl_conn_draining != connp);
28128 
28129 		}
28130 		connp->conn_drain_next = NULL;
28131 		connp->conn_drain_prev = NULL;
28132 
28133 		/*
28134 		 * For non streams based sockets open up flow control.
28135 		 */
28136 		if (IPCL_IS_NONSTR(connp)) {
28137 			(*connp->conn_upcalls->su_txq_full)
28138 			    (connp->conn_upper_handle, B_FALSE);
28139 		} else {
28140 			conn_clrqfull(connp);
28141 			enableok(connp->conn_wq);
28142 		}
28143 	}
28144 
28145 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28146 }
28147 
28148 /*
28149  * Write service routine. Shared perimeter entry point.
28150  * ip_wsrv can be called in any of the following ways.
28151  * 1. The device queue's messages has fallen below the low water mark
28152  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28153  *    the drain lists and backenable the first conn in each list.
28154  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28155  *    qenabled non-tcp upper layers. We start dequeing messages and call
28156  *    ip_wput for each message.
28157  */
28158 
28159 void
28160 ip_wsrv(queue_t *q)
28161 {
28162 	conn_t	*connp;
28163 	ill_t	*ill;
28164 	mblk_t	*mp;
28165 
28166 	if (q->q_next) {
28167 		ill = (ill_t *)q->q_ptr;
28168 		if (ill->ill_state_flags == 0) {
28169 			ip_stack_t *ipst = ill->ill_ipst;
28170 
28171 			/*
28172 			 * The device flow control has opened up.
28173 			 * Walk through conn drain lists and qenable the
28174 			 * first conn in each list. This makes sense only
28175 			 * if the stream is fully plumbed and setup.
28176 			 * Hence the if check above.
28177 			 */
28178 			ip1dbg(("ip_wsrv: walking\n"));
28179 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28180 		}
28181 		return;
28182 	}
28183 
28184 	connp = Q_TO_CONN(q);
28185 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28186 
28187 	/*
28188 	 * 1. Set conn_draining flag to signal that service is active.
28189 	 *
28190 	 * 2. ip_output determines whether it has been called from service,
28191 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28192 	 *    has been called from service.
28193 	 *
28194 	 * 3. Message ordering is preserved by the following logic.
28195 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28196 	 *    the message at the tail, if conn_draining is set (i.e. service
28197 	 *    is running) or if q->q_first is non-null.
28198 	 *
28199 	 *    ii. If ip_output is called from service, and if ip_output cannot
28200 	 *    putnext due to flow control, it does a putbq.
28201 	 *
28202 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28203 	 *    (causing an infinite loop).
28204 	 */
28205 	ASSERT(!connp->conn_did_putbq);
28206 
28207 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28208 		connp->conn_draining = 1;
28209 		noenable(q);
28210 		while ((mp = getq(q)) != NULL) {
28211 			ASSERT(CONN_Q(q));
28212 
28213 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28214 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28215 			if (connp->conn_did_putbq) {
28216 				/* ip_wput did a putbq */
28217 				break;
28218 			}
28219 		}
28220 		/*
28221 		 * At this point, a thread coming down from top, calling
28222 		 * ip_wput, may end up queueing the message. We have not yet
28223 		 * enabled the queue, so ip_wsrv won't be called again.
28224 		 * To avoid this race, check q->q_first again (in the loop)
28225 		 * If the other thread queued the message before we call
28226 		 * enableok(), we will catch it in the q->q_first check.
28227 		 * If the other thread queues the message after we call
28228 		 * enableok(), ip_wsrv will be called again by STREAMS.
28229 		 */
28230 		connp->conn_draining = 0;
28231 		enableok(q);
28232 	}
28233 
28234 	/* Enable the next conn for draining */
28235 	conn_drain_tail(connp, B_FALSE);
28236 
28237 	/*
28238 	 * conn_direct_blocked is used to indicate blocked
28239 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28240 	 * This is the only place where it is set without
28241 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28242 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28243 	 */
28244 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28245 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28246 		connp->conn_direct_blocked = B_FALSE;
28247 	}
28248 
28249 	connp->conn_did_putbq = 0;
28250 }
28251 
28252 /*
28253  * Callback to disable flow control in IP.
28254  *
28255  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28256  * is enabled.
28257  *
28258  * When MAC_TX() is not able to send any more packets, dld sets its queue
28259  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28260  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28261  * function and wakes up corresponding mac worker threads, which in turn
28262  * calls this callback function, and disables flow control.
28263  */
28264 void
28265 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28266 {
28267 	ill_t *ill = (ill_t *)arg;
28268 	ip_stack_t *ipst = ill->ill_ipst;
28269 	idl_tx_list_t *idl_txl;
28270 
28271 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28272 	mutex_enter(&idl_txl->txl_lock);
28273 	/* add code to to set a flag to indicate idl_txl is enabled */
28274 	conn_walk_drain(ipst, idl_txl);
28275 	mutex_exit(&idl_txl->txl_lock);
28276 }
28277 
28278 /*
28279  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28280  * of conns that need to be drained, check if drain is already in progress.
28281  * If so set the idl_repeat bit, indicating that the last conn in the list
28282  * needs to reinitiate the drain once again, for the list. If drain is not
28283  * in progress for the list, initiate the draining, by qenabling the 1st
28284  * conn in the list. The drain is self-sustaining, each qenabled conn will
28285  * in turn qenable the next conn, when it is done/blocked/closing.
28286  */
28287 static void
28288 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28289 {
28290 	int i;
28291 	idl_t *idl;
28292 
28293 	IP_STAT(ipst, ip_conn_walk_drain);
28294 
28295 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28296 		idl = &tx_list->txl_drain_list[i];
28297 		mutex_enter(&idl->idl_lock);
28298 		if (idl->idl_conn == NULL) {
28299 			mutex_exit(&idl->idl_lock);
28300 			continue;
28301 		}
28302 		/*
28303 		 * If this list is not being drained currently by
28304 		 * an ip_wsrv thread, start the process.
28305 		 */
28306 		if (idl->idl_conn_draining == NULL) {
28307 			ASSERT(idl->idl_repeat == 0);
28308 			qenable(idl->idl_conn->conn_wq);
28309 			idl->idl_conn_draining = idl->idl_conn;
28310 		} else {
28311 			idl->idl_repeat = 1;
28312 		}
28313 		mutex_exit(&idl->idl_lock);
28314 	}
28315 }
28316 
28317 /*
28318  * Determine if the ill and multicast aspects of that packets
28319  * "matches" the conn.
28320  */
28321 boolean_t
28322 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28323     zoneid_t zoneid)
28324 {
28325 	ill_t *bound_ill;
28326 	boolean_t found;
28327 	ipif_t *ipif;
28328 	ire_t *ire;
28329 	ipaddr_t dst, src;
28330 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28331 
28332 	dst = ipha->ipha_dst;
28333 	src = ipha->ipha_src;
28334 
28335 	/*
28336 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28337 	 * unicast, broadcast and multicast reception to
28338 	 * conn_incoming_ill. conn_wantpacket itself is called
28339 	 * only for BROADCAST and multicast.
28340 	 */
28341 	bound_ill = connp->conn_incoming_ill;
28342 	if (bound_ill != NULL) {
28343 		if (IS_IPMP(bound_ill)) {
28344 			if (bound_ill->ill_grp != ill->ill_grp)
28345 				return (B_FALSE);
28346 		} else {
28347 			if (bound_ill != ill)
28348 				return (B_FALSE);
28349 		}
28350 	}
28351 
28352 	if (!CLASSD(dst)) {
28353 		if (IPCL_ZONE_MATCH(connp, zoneid))
28354 			return (B_TRUE);
28355 		/*
28356 		 * The conn is in a different zone; we need to check that this
28357 		 * broadcast address is configured in the application's zone.
28358 		 */
28359 		ipif = ipif_get_next_ipif(NULL, ill);
28360 		if (ipif == NULL)
28361 			return (B_FALSE);
28362 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28363 		    connp->conn_zoneid, NULL,
28364 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28365 		ipif_refrele(ipif);
28366 		if (ire != NULL) {
28367 			ire_refrele(ire);
28368 			return (B_TRUE);
28369 		} else {
28370 			return (B_FALSE);
28371 		}
28372 	}
28373 
28374 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28375 	    connp->conn_zoneid == zoneid) {
28376 		/*
28377 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28378 		 * disabled, therefore we don't dispatch the multicast packet to
28379 		 * the sending zone.
28380 		 */
28381 		return (B_FALSE);
28382 	}
28383 
28384 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28385 		/*
28386 		 * Multicast packet on the loopback interface: we only match
28387 		 * conns who joined the group in the specified zone.
28388 		 */
28389 		return (B_FALSE);
28390 	}
28391 
28392 	if (connp->conn_multi_router) {
28393 		/* multicast packet and multicast router socket: send up */
28394 		return (B_TRUE);
28395 	}
28396 
28397 	mutex_enter(&connp->conn_lock);
28398 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28399 	mutex_exit(&connp->conn_lock);
28400 	return (found);
28401 }
28402 
28403 static void
28404 conn_setqfull(conn_t *connp)
28405 {
28406 	queue_t *q = connp->conn_wq;
28407 
28408 	if (!(q->q_flag & QFULL)) {
28409 		mutex_enter(QLOCK(q));
28410 		if (!(q->q_flag & QFULL)) {
28411 			/* still need to set QFULL */
28412 			q->q_flag |= QFULL;
28413 			mutex_exit(QLOCK(q));
28414 		} else {
28415 			mutex_exit(QLOCK(q));
28416 		}
28417 	}
28418 }
28419 
28420 static void
28421 conn_clrqfull(conn_t *connp)
28422 {
28423 	queue_t *q = connp->conn_wq;
28424 
28425 	if (q->q_flag & QFULL) {
28426 		mutex_enter(QLOCK(q));
28427 		if (q->q_flag & QFULL) {
28428 			q->q_flag &= ~QFULL;
28429 			mutex_exit(QLOCK(q));
28430 			if (q->q_flag & QWANTW)
28431 				qbackenable(q, 0);
28432 		} else {
28433 			mutex_exit(QLOCK(q));
28434 		}
28435 	}
28436 }
28437 
28438 /*
28439  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28440  */
28441 /* ARGSUSED */
28442 static void
28443 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28444 {
28445 	ill_t *ill = (ill_t *)q->q_ptr;
28446 	mblk_t	*mp1, *mp2;
28447 	ipif_t  *ipif;
28448 	int err = 0;
28449 	conn_t *connp = NULL;
28450 	ipsq_t	*ipsq;
28451 	arc_t	*arc;
28452 
28453 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28454 
28455 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28456 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28457 
28458 	ASSERT(IAM_WRITER_ILL(ill));
28459 	mp2 = mp->b_cont;
28460 	mp->b_cont = NULL;
28461 
28462 	/*
28463 	 * We have now received the arp bringup completion message
28464 	 * from ARP. Mark the arp bringup as done. Also if the arp
28465 	 * stream has already started closing, send up the AR_ARP_CLOSING
28466 	 * ack now since ARP is waiting in close for this ack.
28467 	 */
28468 	mutex_enter(&ill->ill_lock);
28469 	ill->ill_arp_bringup_pending = 0;
28470 	if (ill->ill_arp_closing) {
28471 		mutex_exit(&ill->ill_lock);
28472 		/* Let's reuse the mp for sending the ack */
28473 		arc = (arc_t *)mp->b_rptr;
28474 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28475 		arc->arc_cmd = AR_ARP_CLOSING;
28476 		qreply(q, mp);
28477 	} else {
28478 		mutex_exit(&ill->ill_lock);
28479 		freeb(mp);
28480 	}
28481 
28482 	ipsq = ill->ill_phyint->phyint_ipsq;
28483 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28484 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28485 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28486 	if (mp1 == NULL) {
28487 		/* bringup was aborted by the user */
28488 		freemsg(mp2);
28489 		return;
28490 	}
28491 
28492 	/*
28493 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28494 	 * must have an associated conn_t.  Otherwise, we're bringing this
28495 	 * interface back up as part of handling an asynchronous event (e.g.,
28496 	 * physical address change).
28497 	 */
28498 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28499 		ASSERT(connp != NULL);
28500 		q = CONNP_TO_WQ(connp);
28501 	} else {
28502 		ASSERT(connp == NULL);
28503 		q = ill->ill_rq;
28504 	}
28505 
28506 	/*
28507 	 * If the DL_BIND_REQ fails, it is noted
28508 	 * in arc_name_offset.
28509 	 */
28510 	err = *((int *)mp2->b_rptr);
28511 	if (err == 0) {
28512 		if (ipif->ipif_isv6) {
28513 			if ((err = ipif_up_done_v6(ipif)) != 0)
28514 				ip0dbg(("ip_arp_done: init failed\n"));
28515 		} else {
28516 			if ((err = ipif_up_done(ipif)) != 0)
28517 				ip0dbg(("ip_arp_done: init failed\n"));
28518 		}
28519 	} else {
28520 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28521 	}
28522 
28523 	freemsg(mp2);
28524 
28525 	if ((err == 0) && (ill->ill_up_ipifs)) {
28526 		err = ill_up_ipifs(ill, q, mp1);
28527 		if (err == EINPROGRESS)
28528 			return;
28529 	}
28530 
28531 	/*
28532 	 * If we have a moved ipif to bring up, and everything has succeeded
28533 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28534 	 * down -- the admin can try to bring it up by hand if need be.
28535 	 */
28536 	if (ill->ill_move_ipif != NULL) {
28537 		ipif = ill->ill_move_ipif;
28538 		ill->ill_move_ipif = NULL;
28539 		if (err == 0) {
28540 			err = ipif_up(ipif, q, mp1);
28541 			if (err == EINPROGRESS)
28542 				return;
28543 		}
28544 	}
28545 
28546 	/*
28547 	 * The operation must complete without EINPROGRESS since
28548 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28549 	 * operation will be stuck forever in the ipsq.
28550 	 */
28551 	ASSERT(err != EINPROGRESS);
28552 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28553 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28554 	else
28555 		ipsq_current_finish(ipsq);
28556 }
28557 
28558 /* Allocate the private structure */
28559 static int
28560 ip_priv_alloc(void **bufp)
28561 {
28562 	void	*buf;
28563 
28564 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28565 		return (ENOMEM);
28566 
28567 	*bufp = buf;
28568 	return (0);
28569 }
28570 
28571 /* Function to delete the private structure */
28572 void
28573 ip_priv_free(void *buf)
28574 {
28575 	ASSERT(buf != NULL);
28576 	kmem_free(buf, sizeof (ip_priv_t));
28577 }
28578 
28579 /*
28580  * The entry point for IPPF processing.
28581  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28582  * routine just returns.
28583  *
28584  * When called, ip_process generates an ipp_packet_t structure
28585  * which holds the state information for this packet and invokes the
28586  * the classifier (via ipp_packet_process). The classification, depending on
28587  * configured filters, results in a list of actions for this packet. Invoking
28588  * an action may cause the packet to be dropped, in which case the resulting
28589  * mblk (*mpp) is NULL. proc indicates the callout position for
28590  * this packet and ill_index is the interface this packet on or will leave
28591  * on (inbound and outbound resp.).
28592  */
28593 void
28594 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28595 {
28596 	mblk_t		*mp;
28597 	ip_priv_t	*priv;
28598 	ipp_action_id_t	aid;
28599 	int		rc = 0;
28600 	ipp_packet_t	*pp;
28601 #define	IP_CLASS	"ip"
28602 
28603 	/* If the classifier is not loaded, return  */
28604 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28605 		return;
28606 	}
28607 
28608 	mp = *mpp;
28609 	ASSERT(mp != NULL);
28610 
28611 	/* Allocate the packet structure */
28612 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28613 	if (rc != 0) {
28614 		*mpp = NULL;
28615 		freemsg(mp);
28616 		return;
28617 	}
28618 
28619 	/* Allocate the private structure */
28620 	rc = ip_priv_alloc((void **)&priv);
28621 	if (rc != 0) {
28622 		*mpp = NULL;
28623 		freemsg(mp);
28624 		ipp_packet_free(pp);
28625 		return;
28626 	}
28627 	priv->proc = proc;
28628 	priv->ill_index = ill_index;
28629 	ipp_packet_set_private(pp, priv, ip_priv_free);
28630 	ipp_packet_set_data(pp, mp);
28631 
28632 	/* Invoke the classifier */
28633 	rc = ipp_packet_process(&pp);
28634 	if (pp != NULL) {
28635 		mp = ipp_packet_get_data(pp);
28636 		ipp_packet_free(pp);
28637 		if (rc != 0) {
28638 			freemsg(mp);
28639 			*mpp = NULL;
28640 		}
28641 	} else {
28642 		*mpp = NULL;
28643 	}
28644 #undef	IP_CLASS
28645 }
28646 
28647 /*
28648  * Propagate a multicast group membership operation (add/drop) on
28649  * all the interfaces crossed by the related multirt routes.
28650  * The call is considered successful if the operation succeeds
28651  * on at least one interface.
28652  */
28653 static int
28654 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28655     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28656     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28657     mblk_t *first_mp)
28658 {
28659 	ire_t		*ire_gw;
28660 	irb_t		*irb;
28661 	int		error = 0;
28662 	opt_restart_t	*or;
28663 	ip_stack_t	*ipst = ire->ire_ipst;
28664 
28665 	irb = ire->ire_bucket;
28666 	ASSERT(irb != NULL);
28667 
28668 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28669 
28670 	or = (opt_restart_t *)first_mp->b_rptr;
28671 	IRB_REFHOLD(irb);
28672 	for (; ire != NULL; ire = ire->ire_next) {
28673 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28674 			continue;
28675 		if (ire->ire_addr != group)
28676 			continue;
28677 
28678 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28679 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28680 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28681 		/* No resolver exists for the gateway; skip this ire. */
28682 		if (ire_gw == NULL)
28683 			continue;
28684 
28685 		/*
28686 		 * This function can return EINPROGRESS. If so the operation
28687 		 * will be restarted from ip_restart_optmgmt which will
28688 		 * call ip_opt_set and option processing will restart for
28689 		 * this option. So we may end up calling 'fn' more than once.
28690 		 * This requires that 'fn' is idempotent except for the
28691 		 * return value. The operation is considered a success if
28692 		 * it succeeds at least once on any one interface.
28693 		 */
28694 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28695 		    NULL, fmode, src, first_mp);
28696 		if (error == 0)
28697 			or->or_private = CGTP_MCAST_SUCCESS;
28698 
28699 		if (ip_debug > 0) {
28700 			ulong_t	off;
28701 			char	*ksym;
28702 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28703 			ip2dbg(("ip_multirt_apply_membership: "
28704 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28705 			    "error %d [success %u]\n",
28706 			    ksym ? ksym : "?",
28707 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28708 			    error, or->or_private));
28709 		}
28710 
28711 		ire_refrele(ire_gw);
28712 		if (error == EINPROGRESS) {
28713 			IRB_REFRELE(irb);
28714 			return (error);
28715 		}
28716 	}
28717 	IRB_REFRELE(irb);
28718 	/*
28719 	 * Consider the call as successful if we succeeded on at least
28720 	 * one interface. Otherwise, return the last encountered error.
28721 	 */
28722 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28723 }
28724 
28725 /*
28726  * Issue a warning regarding a route crossing an interface with an
28727  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28728  * amount of time is logged.
28729  */
28730 static void
28731 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28732 {
28733 	hrtime_t	current = gethrtime();
28734 	char		buf[INET_ADDRSTRLEN];
28735 	ip_stack_t	*ipst = ire->ire_ipst;
28736 
28737 	/* Convert interval in ms to hrtime in ns */
28738 	if (ipst->ips_multirt_bad_mtu_last_time +
28739 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28740 	    current) {
28741 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28742 		    "to %s, incorrect MTU %u (expected %u)\n",
28743 		    ip_dot_addr(ire->ire_addr, buf),
28744 		    ire->ire_max_frag, max_frag);
28745 
28746 		ipst->ips_multirt_bad_mtu_last_time = current;
28747 	}
28748 }
28749 
28750 /*
28751  * Get the CGTP (multirouting) filtering status.
28752  * If 0, the CGTP hooks are transparent.
28753  */
28754 /* ARGSUSED */
28755 static int
28756 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28757 {
28758 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28759 
28760 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28761 	return (0);
28762 }
28763 
28764 /*
28765  * Set the CGTP (multirouting) filtering status.
28766  * If the status is changed from active to transparent
28767  * or from transparent to active, forward the new status
28768  * to the filtering module (if loaded).
28769  */
28770 /* ARGSUSED */
28771 static int
28772 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28773     cred_t *ioc_cr)
28774 {
28775 	long		new_value;
28776 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28777 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28778 
28779 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28780 		return (EPERM);
28781 
28782 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28783 	    new_value < 0 || new_value > 1) {
28784 		return (EINVAL);
28785 	}
28786 
28787 	if ((!*ip_cgtp_filter_value) && new_value) {
28788 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28789 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28790 		    " (module not loaded)" : "");
28791 	}
28792 	if (*ip_cgtp_filter_value && (!new_value)) {
28793 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28794 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28795 		    " (module not loaded)" : "");
28796 	}
28797 
28798 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28799 		int	res;
28800 		netstackid_t stackid;
28801 
28802 		stackid = ipst->ips_netstack->netstack_stackid;
28803 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28804 		    new_value);
28805 		if (res)
28806 			return (res);
28807 	}
28808 
28809 	*ip_cgtp_filter_value = (boolean_t)new_value;
28810 
28811 	return (0);
28812 }
28813 
28814 /*
28815  * Return the expected CGTP hooks version number.
28816  */
28817 int
28818 ip_cgtp_filter_supported(void)
28819 {
28820 	return (ip_cgtp_filter_rev);
28821 }
28822 
28823 /*
28824  * CGTP hooks can be registered by invoking this function.
28825  * Checks that the version number matches.
28826  */
28827 int
28828 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28829 {
28830 	netstack_t *ns;
28831 	ip_stack_t *ipst;
28832 
28833 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28834 		return (ENOTSUP);
28835 
28836 	ns = netstack_find_by_stackid(stackid);
28837 	if (ns == NULL)
28838 		return (EINVAL);
28839 	ipst = ns->netstack_ip;
28840 	ASSERT(ipst != NULL);
28841 
28842 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28843 		netstack_rele(ns);
28844 		return (EALREADY);
28845 	}
28846 
28847 	ipst->ips_ip_cgtp_filter_ops = ops;
28848 	netstack_rele(ns);
28849 	return (0);
28850 }
28851 
28852 /*
28853  * CGTP hooks can be unregistered by invoking this function.
28854  * Returns ENXIO if there was no registration.
28855  * Returns EBUSY if the ndd variable has not been turned off.
28856  */
28857 int
28858 ip_cgtp_filter_unregister(netstackid_t stackid)
28859 {
28860 	netstack_t *ns;
28861 	ip_stack_t *ipst;
28862 
28863 	ns = netstack_find_by_stackid(stackid);
28864 	if (ns == NULL)
28865 		return (EINVAL);
28866 	ipst = ns->netstack_ip;
28867 	ASSERT(ipst != NULL);
28868 
28869 	if (ipst->ips_ip_cgtp_filter) {
28870 		netstack_rele(ns);
28871 		return (EBUSY);
28872 	}
28873 
28874 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28875 		netstack_rele(ns);
28876 		return (ENXIO);
28877 	}
28878 	ipst->ips_ip_cgtp_filter_ops = NULL;
28879 	netstack_rele(ns);
28880 	return (0);
28881 }
28882 
28883 /*
28884  * Check whether there is a CGTP filter registration.
28885  * Returns non-zero if there is a registration, otherwise returns zero.
28886  * Note: returns zero if bad stackid.
28887  */
28888 int
28889 ip_cgtp_filter_is_registered(netstackid_t stackid)
28890 {
28891 	netstack_t *ns;
28892 	ip_stack_t *ipst;
28893 	int ret;
28894 
28895 	ns = netstack_find_by_stackid(stackid);
28896 	if (ns == NULL)
28897 		return (0);
28898 	ipst = ns->netstack_ip;
28899 	ASSERT(ipst != NULL);
28900 
28901 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28902 		ret = 1;
28903 	else
28904 		ret = 0;
28905 
28906 	netstack_rele(ns);
28907 	return (ret);
28908 }
28909 
28910 static int
28911 ip_squeue_switch(int val)
28912 {
28913 	int rval = SQ_FILL;
28914 
28915 	switch (val) {
28916 	case IP_SQUEUE_ENTER_NODRAIN:
28917 		rval = SQ_NODRAIN;
28918 		break;
28919 	case IP_SQUEUE_ENTER:
28920 		rval = SQ_PROCESS;
28921 		break;
28922 	default:
28923 		break;
28924 	}
28925 	return (rval);
28926 }
28927 
28928 /* ARGSUSED */
28929 static int
28930 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28931     caddr_t addr, cred_t *cr)
28932 {
28933 	int *v = (int *)addr;
28934 	long new_value;
28935 
28936 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28937 		return (EPERM);
28938 
28939 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28940 		return (EINVAL);
28941 
28942 	ip_squeue_flag = ip_squeue_switch(new_value);
28943 	*v = new_value;
28944 	return (0);
28945 }
28946 
28947 /*
28948  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
28949  * ip_debug.
28950  */
28951 /* ARGSUSED */
28952 static int
28953 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28954     caddr_t addr, cred_t *cr)
28955 {
28956 	int *v = (int *)addr;
28957 	long new_value;
28958 
28959 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28960 		return (EPERM);
28961 
28962 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28963 		return (EINVAL);
28964 
28965 	*v = new_value;
28966 	return (0);
28967 }
28968 
28969 static void *
28970 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
28971 {
28972 	kstat_t *ksp;
28973 
28974 	ip_stat_t template = {
28975 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
28976 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
28977 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
28978 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
28979 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
28980 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
28981 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
28982 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
28983 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
28984 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
28985 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
28986 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
28987 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
28988 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
28989 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
28990 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
28991 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
28992 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
28993 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
28994 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
28995 		{ "ip_opt",			KSTAT_DATA_UINT64 },
28996 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
28997 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
28998 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
28999 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29000 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29001 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29002 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29003 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29004 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29005 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29006 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29007 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29008 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29009 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29010 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29011 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29012 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29013 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29014 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29015 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29016 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29017 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29018 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29019 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29020 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29021 	};
29022 
29023 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29024 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29025 	    KSTAT_FLAG_VIRTUAL, stackid);
29026 
29027 	if (ksp == NULL)
29028 		return (NULL);
29029 
29030 	bcopy(&template, ip_statisticsp, sizeof (template));
29031 	ksp->ks_data = (void *)ip_statisticsp;
29032 	ksp->ks_private = (void *)(uintptr_t)stackid;
29033 
29034 	kstat_install(ksp);
29035 	return (ksp);
29036 }
29037 
29038 static void
29039 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29040 {
29041 	if (ksp != NULL) {
29042 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29043 		kstat_delete_netstack(ksp, stackid);
29044 	}
29045 }
29046 
29047 static void *
29048 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29049 {
29050 	kstat_t	*ksp;
29051 
29052 	ip_named_kstat_t template = {
29053 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29054 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29055 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29056 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29057 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29058 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29059 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29060 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29061 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29062 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29063 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29064 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29065 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29066 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29067 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29068 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29069 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29070 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29071 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29072 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29073 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29074 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29075 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29076 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29077 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29078 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29079 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29080 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29081 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29082 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29083 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29084 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29085 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29086 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29087 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29088 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29089 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29090 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29091 	};
29092 
29093 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29094 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29095 	if (ksp == NULL || ksp->ks_data == NULL)
29096 		return (NULL);
29097 
29098 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29099 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29100 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29101 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29102 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29103 
29104 	template.netToMediaEntrySize.value.i32 =
29105 	    sizeof (mib2_ipNetToMediaEntry_t);
29106 
29107 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29108 
29109 	bcopy(&template, ksp->ks_data, sizeof (template));
29110 	ksp->ks_update = ip_kstat_update;
29111 	ksp->ks_private = (void *)(uintptr_t)stackid;
29112 
29113 	kstat_install(ksp);
29114 	return (ksp);
29115 }
29116 
29117 static void
29118 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29119 {
29120 	if (ksp != NULL) {
29121 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29122 		kstat_delete_netstack(ksp, stackid);
29123 	}
29124 }
29125 
29126 static int
29127 ip_kstat_update(kstat_t *kp, int rw)
29128 {
29129 	ip_named_kstat_t *ipkp;
29130 	mib2_ipIfStatsEntry_t ipmib;
29131 	ill_walk_context_t ctx;
29132 	ill_t *ill;
29133 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29134 	netstack_t	*ns;
29135 	ip_stack_t	*ipst;
29136 
29137 	if (kp == NULL || kp->ks_data == NULL)
29138 		return (EIO);
29139 
29140 	if (rw == KSTAT_WRITE)
29141 		return (EACCES);
29142 
29143 	ns = netstack_find_by_stackid(stackid);
29144 	if (ns == NULL)
29145 		return (-1);
29146 	ipst = ns->netstack_ip;
29147 	if (ipst == NULL) {
29148 		netstack_rele(ns);
29149 		return (-1);
29150 	}
29151 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29152 
29153 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29154 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29155 	ill = ILL_START_WALK_V4(&ctx, ipst);
29156 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29157 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29158 	rw_exit(&ipst->ips_ill_g_lock);
29159 
29160 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29161 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29162 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29163 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29164 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29165 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29166 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29167 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29168 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29169 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29170 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29171 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29172 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29173 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29174 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29175 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29176 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29177 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29178 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29179 
29180 	ipkp->routingDiscards.value.ui32 =	0;
29181 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29182 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29183 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29184 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29185 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29186 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29187 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29188 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29189 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29190 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29191 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29192 
29193 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29194 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29195 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29196 
29197 	netstack_rele(ns);
29198 
29199 	return (0);
29200 }
29201 
29202 static void *
29203 icmp_kstat_init(netstackid_t stackid)
29204 {
29205 	kstat_t	*ksp;
29206 
29207 	icmp_named_kstat_t template = {
29208 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29209 		{ "inErrors",		KSTAT_DATA_UINT32 },
29210 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29211 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29212 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29213 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29214 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29215 		{ "inEchos",		KSTAT_DATA_UINT32 },
29216 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29217 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29218 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29219 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29220 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29221 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29222 		{ "outErrors",		KSTAT_DATA_UINT32 },
29223 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29224 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29225 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29226 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29227 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29228 		{ "outEchos",		KSTAT_DATA_UINT32 },
29229 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29230 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29231 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29232 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29233 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29234 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29235 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29236 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29237 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29238 		{ "outDrops",		KSTAT_DATA_UINT32 },
29239 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29240 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29241 	};
29242 
29243 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29244 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29245 	if (ksp == NULL || ksp->ks_data == NULL)
29246 		return (NULL);
29247 
29248 	bcopy(&template, ksp->ks_data, sizeof (template));
29249 
29250 	ksp->ks_update = icmp_kstat_update;
29251 	ksp->ks_private = (void *)(uintptr_t)stackid;
29252 
29253 	kstat_install(ksp);
29254 	return (ksp);
29255 }
29256 
29257 static void
29258 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29259 {
29260 	if (ksp != NULL) {
29261 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29262 		kstat_delete_netstack(ksp, stackid);
29263 	}
29264 }
29265 
29266 static int
29267 icmp_kstat_update(kstat_t *kp, int rw)
29268 {
29269 	icmp_named_kstat_t *icmpkp;
29270 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29271 	netstack_t	*ns;
29272 	ip_stack_t	*ipst;
29273 
29274 	if ((kp == NULL) || (kp->ks_data == NULL))
29275 		return (EIO);
29276 
29277 	if (rw == KSTAT_WRITE)
29278 		return (EACCES);
29279 
29280 	ns = netstack_find_by_stackid(stackid);
29281 	if (ns == NULL)
29282 		return (-1);
29283 	ipst = ns->netstack_ip;
29284 	if (ipst == NULL) {
29285 		netstack_rele(ns);
29286 		return (-1);
29287 	}
29288 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29289 
29290 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29291 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29292 	icmpkp->inDestUnreachs.value.ui32 =
29293 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29294 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29295 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29296 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29297 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29298 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29299 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29300 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29301 	icmpkp->inTimestampReps.value.ui32 =
29302 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29303 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29304 	icmpkp->inAddrMaskReps.value.ui32 =
29305 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29306 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29307 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29308 	icmpkp->outDestUnreachs.value.ui32 =
29309 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29310 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29311 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29312 	icmpkp->outSrcQuenchs.value.ui32 =
29313 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29314 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29315 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29316 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29317 	icmpkp->outTimestamps.value.ui32 =
29318 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29319 	icmpkp->outTimestampReps.value.ui32 =
29320 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29321 	icmpkp->outAddrMasks.value.ui32 =
29322 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29323 	icmpkp->outAddrMaskReps.value.ui32 =
29324 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29325 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29326 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29327 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29328 	icmpkp->outFragNeeded.value.ui32 =
29329 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29330 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29331 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29332 	icmpkp->inBadRedirects.value.ui32 =
29333 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29334 
29335 	netstack_rele(ns);
29336 	return (0);
29337 }
29338 
29339 /*
29340  * This is the fanout function for raw socket opened for SCTP.  Note
29341  * that it is called after SCTP checks that there is no socket which
29342  * wants a packet.  Then before SCTP handles this out of the blue packet,
29343  * this function is called to see if there is any raw socket for SCTP.
29344  * If there is and it is bound to the correct address, the packet will
29345  * be sent to that socket.  Note that only one raw socket can be bound to
29346  * a port.  This is assured in ipcl_sctp_hash_insert();
29347  */
29348 void
29349 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29350     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29351     zoneid_t zoneid)
29352 {
29353 	conn_t		*connp;
29354 	queue_t		*rq;
29355 	mblk_t		*first_mp;
29356 	boolean_t	secure;
29357 	ip6_t		*ip6h;
29358 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29359 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29360 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29361 	boolean_t	sctp_csum_err = B_FALSE;
29362 
29363 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29364 		sctp_csum_err = B_TRUE;
29365 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29366 	}
29367 
29368 	first_mp = mp;
29369 	if (mctl_present) {
29370 		mp = first_mp->b_cont;
29371 		secure = ipsec_in_is_secure(first_mp);
29372 		ASSERT(mp != NULL);
29373 	} else {
29374 		secure = B_FALSE;
29375 	}
29376 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29377 
29378 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29379 	if (connp == NULL) {
29380 		/*
29381 		 * Although raw sctp is not summed, OOB chunks must be.
29382 		 * Drop the packet here if the sctp checksum failed.
29383 		 */
29384 		if (sctp_csum_err) {
29385 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29386 			freemsg(first_mp);
29387 			return;
29388 		}
29389 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29390 		return;
29391 	}
29392 	rq = connp->conn_rq;
29393 	if (!canputnext(rq)) {
29394 		CONN_DEC_REF(connp);
29395 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29396 		freemsg(first_mp);
29397 		return;
29398 	}
29399 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29400 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29401 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29402 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29403 		if (first_mp == NULL) {
29404 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29405 			CONN_DEC_REF(connp);
29406 			return;
29407 		}
29408 	}
29409 	/*
29410 	 * We probably should not send M_CTL message up to
29411 	 * raw socket.
29412 	 */
29413 	if (mctl_present)
29414 		freeb(first_mp);
29415 
29416 	/* Initiate IPPF processing here if needed. */
29417 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29418 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29419 		ip_process(IPP_LOCAL_IN, &mp,
29420 		    recv_ill->ill_phyint->phyint_ifindex);
29421 		if (mp == NULL) {
29422 			CONN_DEC_REF(connp);
29423 			return;
29424 		}
29425 	}
29426 
29427 	if (connp->conn_recvif || connp->conn_recvslla ||
29428 	    ((connp->conn_ip_recvpktinfo ||
29429 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29430 	    (flags & IP_FF_IPINFO))) {
29431 		int in_flags = 0;
29432 
29433 		/*
29434 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29435 		 * IPF_RECVIF.
29436 		 */
29437 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29438 			in_flags = IPF_RECVIF;
29439 		}
29440 		if (connp->conn_recvslla) {
29441 			in_flags |= IPF_RECVSLLA;
29442 		}
29443 		if (isv4) {
29444 			mp = ip_add_info(mp, recv_ill, in_flags,
29445 			    IPCL_ZONEID(connp), ipst);
29446 		} else {
29447 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29448 			if (mp == NULL) {
29449 				BUMP_MIB(recv_ill->ill_ip_mib,
29450 				    ipIfStatsInDiscards);
29451 				CONN_DEC_REF(connp);
29452 				return;
29453 			}
29454 		}
29455 	}
29456 
29457 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29458 	/*
29459 	 * We are sending the IPSEC_IN message also up. Refer
29460 	 * to comments above this function.
29461 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29462 	 */
29463 	(connp->conn_recv)(connp, mp, NULL);
29464 	CONN_DEC_REF(connp);
29465 }
29466 
29467 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29468 {									\
29469 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29470 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29471 }
29472 /*
29473  * This function should be called only if all packet processing
29474  * including fragmentation is complete. Callers of this function
29475  * must set mp->b_prev to one of these values:
29476  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29477  * prior to handing over the mp as first argument to this function.
29478  *
29479  * If the ire passed by caller is incomplete, this function
29480  * queues the packet and if necessary, sends ARP request and bails.
29481  * If the ire passed is fully resolved, we simply prepend
29482  * the link-layer header to the packet, do ipsec hw acceleration
29483  * work if necessary, and send the packet out on the wire.
29484  *
29485  * NOTE: IPsec will only call this function with fully resolved
29486  * ires if hw acceleration is involved.
29487  * TODO list :
29488  * 	a Handle M_MULTIDATA so that
29489  *	  tcp_multisend->tcp_multisend_data can
29490  *	  call ip_xmit_v4 directly
29491  *	b Handle post-ARP work for fragments so that
29492  *	  ip_wput_frag can call this function.
29493  */
29494 ipxmit_state_t
29495 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29496     boolean_t flow_ctl_enabled, conn_t *connp)
29497 {
29498 	nce_t		*arpce;
29499 	ipha_t		*ipha;
29500 	queue_t		*q;
29501 	int		ill_index;
29502 	mblk_t		*nxt_mp, *first_mp;
29503 	boolean_t	xmit_drop = B_FALSE;
29504 	ip_proc_t	proc;
29505 	ill_t		*out_ill;
29506 	int		pkt_len;
29507 
29508 	arpce = ire->ire_nce;
29509 	ASSERT(arpce != NULL);
29510 
29511 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29512 
29513 	mutex_enter(&arpce->nce_lock);
29514 	switch (arpce->nce_state) {
29515 	case ND_REACHABLE:
29516 		/* If there are other queued packets, queue this packet */
29517 		if (arpce->nce_qd_mp != NULL) {
29518 			if (mp != NULL)
29519 				nce_queue_mp_common(arpce, mp, B_FALSE);
29520 			mp = arpce->nce_qd_mp;
29521 		}
29522 		arpce->nce_qd_mp = NULL;
29523 		mutex_exit(&arpce->nce_lock);
29524 
29525 		/*
29526 		 * Flush the queue.  In the common case, where the
29527 		 * ARP is already resolved,  it will go through the
29528 		 * while loop only once.
29529 		 */
29530 		while (mp != NULL) {
29531 
29532 			nxt_mp = mp->b_next;
29533 			mp->b_next = NULL;
29534 			ASSERT(mp->b_datap->db_type != M_CTL);
29535 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29536 			/*
29537 			 * This info is needed for IPQOS to do COS marking
29538 			 * in ip_wput_attach_llhdr->ip_process.
29539 			 */
29540 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29541 			mp->b_prev = NULL;
29542 
29543 			/* set up ill index for outbound qos processing */
29544 			out_ill = ire_to_ill(ire);
29545 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29546 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29547 			    ill_index, &ipha);
29548 			if (first_mp == NULL) {
29549 				xmit_drop = B_TRUE;
29550 				BUMP_MIB(out_ill->ill_ip_mib,
29551 				    ipIfStatsOutDiscards);
29552 				goto next_mp;
29553 			}
29554 
29555 			/* non-ipsec hw accel case */
29556 			if (io == NULL || !io->ipsec_out_accelerated) {
29557 				/* send it */
29558 				q = ire->ire_stq;
29559 				if (proc == IPP_FWD_OUT) {
29560 					UPDATE_IB_PKT_COUNT(ire);
29561 				} else {
29562 					UPDATE_OB_PKT_COUNT(ire);
29563 				}
29564 				ire->ire_last_used_time = lbolt;
29565 
29566 				if (flow_ctl_enabled || canputnext(q)) {
29567 					if (proc == IPP_FWD_OUT) {
29568 
29569 					BUMP_MIB(out_ill->ill_ip_mib,
29570 					    ipIfStatsHCOutForwDatagrams);
29571 
29572 					}
29573 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29574 					    pkt_len);
29575 
29576 					DTRACE_IP7(send, mblk_t *, first_mp,
29577 					    conn_t *, NULL, void_ip_t *, ipha,
29578 					    __dtrace_ipsr_ill_t *, out_ill,
29579 					    ipha_t *, ipha, ip6_t *, NULL, int,
29580 					    0);
29581 
29582 					ILL_SEND_TX(out_ill,
29583 					    ire, connp, first_mp, 0, connp);
29584 				} else {
29585 					BUMP_MIB(out_ill->ill_ip_mib,
29586 					    ipIfStatsOutDiscards);
29587 					xmit_drop = B_TRUE;
29588 					freemsg(first_mp);
29589 				}
29590 			} else {
29591 				/*
29592 				 * Safety Pup says: make sure this
29593 				 *  is going to the right interface!
29594 				 */
29595 				ill_t *ill1 =
29596 				    (ill_t *)ire->ire_stq->q_ptr;
29597 				int ifindex =
29598 				    ill1->ill_phyint->phyint_ifindex;
29599 				if (ifindex !=
29600 				    io->ipsec_out_capab_ill_index) {
29601 					xmit_drop = B_TRUE;
29602 					freemsg(mp);
29603 				} else {
29604 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29605 					    pkt_len);
29606 
29607 					DTRACE_IP7(send, mblk_t *, first_mp,
29608 					    conn_t *, NULL, void_ip_t *, ipha,
29609 					    __dtrace_ipsr_ill_t *, ill1,
29610 					    ipha_t *, ipha, ip6_t *, NULL,
29611 					    int, 0);
29612 
29613 					ipsec_hw_putnext(ire->ire_stq, mp);
29614 				}
29615 			}
29616 next_mp:
29617 			mp = nxt_mp;
29618 		} /* while (mp != NULL) */
29619 		if (xmit_drop)
29620 			return (SEND_FAILED);
29621 		else
29622 			return (SEND_PASSED);
29623 
29624 	case ND_INITIAL:
29625 	case ND_INCOMPLETE:
29626 
29627 		/*
29628 		 * While we do send off packets to dests that
29629 		 * use fully-resolved CGTP routes, we do not
29630 		 * handle unresolved CGTP routes.
29631 		 */
29632 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29633 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29634 
29635 		if (mp != NULL) {
29636 			/* queue the packet */
29637 			nce_queue_mp_common(arpce, mp, B_FALSE);
29638 		}
29639 
29640 		if (arpce->nce_state == ND_INCOMPLETE) {
29641 			mutex_exit(&arpce->nce_lock);
29642 			DTRACE_PROBE3(ip__xmit__incomplete,
29643 			    (ire_t *), ire, (mblk_t *), mp,
29644 			    (ipsec_out_t *), io);
29645 			return (LOOKUP_IN_PROGRESS);
29646 		}
29647 
29648 		arpce->nce_state = ND_INCOMPLETE;
29649 		mutex_exit(&arpce->nce_lock);
29650 
29651 		/*
29652 		 * Note that ire_add() (called from ire_forward())
29653 		 * holds a ref on the ire until ARP is completed.
29654 		 */
29655 		ire_arpresolve(ire);
29656 		return (LOOKUP_IN_PROGRESS);
29657 	default:
29658 		ASSERT(0);
29659 		mutex_exit(&arpce->nce_lock);
29660 		return (LLHDR_RESLV_FAILED);
29661 	}
29662 }
29663 
29664 #undef	UPDATE_IP_MIB_OB_COUNTERS
29665 
29666 /*
29667  * Return B_TRUE if the buffers differ in length or content.
29668  * This is used for comparing extension header buffers.
29669  * Note that an extension header would be declared different
29670  * even if all that changed was the next header value in that header i.e.
29671  * what really changed is the next extension header.
29672  */
29673 boolean_t
29674 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29675     uint_t blen)
29676 {
29677 	if (!b_valid)
29678 		blen = 0;
29679 
29680 	if (alen != blen)
29681 		return (B_TRUE);
29682 	if (alen == 0)
29683 		return (B_FALSE);	/* Both zero length */
29684 	return (bcmp(abuf, bbuf, alen));
29685 }
29686 
29687 /*
29688  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29689  * Return B_FALSE if memory allocation fails - don't change any state!
29690  */
29691 boolean_t
29692 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29693     const void *src, uint_t srclen)
29694 {
29695 	void *dst;
29696 
29697 	if (!src_valid)
29698 		srclen = 0;
29699 
29700 	ASSERT(*dstlenp == 0);
29701 	if (src != NULL && srclen != 0) {
29702 		dst = mi_alloc(srclen, BPRI_MED);
29703 		if (dst == NULL)
29704 			return (B_FALSE);
29705 	} else {
29706 		dst = NULL;
29707 	}
29708 	if (*dstp != NULL)
29709 		mi_free(*dstp);
29710 	*dstp = dst;
29711 	*dstlenp = dst == NULL ? 0 : srclen;
29712 	return (B_TRUE);
29713 }
29714 
29715 /*
29716  * Replace what is in *dst, *dstlen with the source.
29717  * Assumes ip_allocbuf has already been called.
29718  */
29719 void
29720 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29721     const void *src, uint_t srclen)
29722 {
29723 	if (!src_valid)
29724 		srclen = 0;
29725 
29726 	ASSERT(*dstlenp == srclen);
29727 	if (src != NULL && srclen != 0)
29728 		bcopy(src, *dstp, srclen);
29729 }
29730 
29731 /*
29732  * Free the storage pointed to by the members of an ip6_pkt_t.
29733  */
29734 void
29735 ip6_pkt_free(ip6_pkt_t *ipp)
29736 {
29737 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29738 
29739 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29740 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29741 		ipp->ipp_hopopts = NULL;
29742 		ipp->ipp_hopoptslen = 0;
29743 	}
29744 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29745 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29746 		ipp->ipp_rtdstopts = NULL;
29747 		ipp->ipp_rtdstoptslen = 0;
29748 	}
29749 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29750 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29751 		ipp->ipp_dstopts = NULL;
29752 		ipp->ipp_dstoptslen = 0;
29753 	}
29754 	if (ipp->ipp_fields & IPPF_RTHDR) {
29755 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29756 		ipp->ipp_rthdr = NULL;
29757 		ipp->ipp_rthdrlen = 0;
29758 	}
29759 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29760 	    IPPF_RTHDR);
29761 }
29762 
29763 zoneid_t
29764 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29765     zoneid_t lookup_zoneid)
29766 {
29767 	ire_t		*ire;
29768 	int		ire_flags = MATCH_IRE_TYPE;
29769 	zoneid_t	zoneid = ALL_ZONES;
29770 
29771 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29772 		return (ALL_ZONES);
29773 
29774 	if (lookup_zoneid != ALL_ZONES)
29775 		ire_flags |= MATCH_IRE_ZONEONLY;
29776 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29777 	    lookup_zoneid, NULL, ire_flags, ipst);
29778 	if (ire != NULL) {
29779 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29780 		ire_refrele(ire);
29781 	}
29782 	return (zoneid);
29783 }
29784 
29785 zoneid_t
29786 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29787     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29788 {
29789 	ire_t		*ire;
29790 	int		ire_flags = MATCH_IRE_TYPE;
29791 	zoneid_t	zoneid = ALL_ZONES;
29792 	ipif_t		*ipif_arg = NULL;
29793 
29794 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29795 		return (ALL_ZONES);
29796 
29797 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29798 		ire_flags |= MATCH_IRE_ILL;
29799 		ipif_arg = ill->ill_ipif;
29800 	}
29801 	if (lookup_zoneid != ALL_ZONES)
29802 		ire_flags |= MATCH_IRE_ZONEONLY;
29803 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29804 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29805 	if (ire != NULL) {
29806 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29807 		ire_refrele(ire);
29808 	}
29809 	return (zoneid);
29810 }
29811 
29812 /*
29813  * IP obserability hook support functions.
29814  */
29815 static void
29816 ipobs_init(ip_stack_t *ipst)
29817 {
29818 	netid_t id;
29819 
29820 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
29821 
29822 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
29823 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
29824 
29825 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
29826 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
29827 }
29828 
29829 static void
29830 ipobs_fini(ip_stack_t *ipst)
29831 {
29832 
29833 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
29834 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
29835 }
29836 
29837 /*
29838  * hook_pkt_observe_t is composed in network byte order so that the
29839  * entire mblk_t chain handed into hook_run can be used as-is.
29840  * The caveat is that use of the fields, such as the zone fields,
29841  * requires conversion into host byte order first.
29842  */
29843 void
29844 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
29845     const ill_t *ill, ip_stack_t *ipst)
29846 {
29847 	hook_pkt_observe_t *hdr;
29848 	uint64_t grifindex;
29849 	mblk_t *imp;
29850 
29851 	imp = allocb(sizeof (*hdr), BPRI_HI);
29852 	if (imp == NULL)
29853 		return;
29854 
29855 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
29856 	/*
29857 	 * b_wptr is set to make the apparent size of the data in the mblk_t
29858 	 * to exclude the pointers at the end of hook_pkt_observer_t.
29859 	 */
29860 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
29861 	imp->b_cont = mp;
29862 
29863 	ASSERT(DB_TYPE(mp) == M_DATA);
29864 
29865 	if (IS_UNDER_IPMP(ill))
29866 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
29867 	else
29868 		grifindex = 0;
29869 
29870 	hdr->hpo_version = 1;
29871 	hdr->hpo_htype = htype;
29872 	hdr->hpo_pktlen = htons((ushort_t)msgdsize(mp));
29873 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
29874 	hdr->hpo_grifindex = htonl(grifindex);
29875 	hdr->hpo_zsrc = htonl(zsrc);
29876 	hdr->hpo_zdst = htonl(zdst);
29877 	hdr->hpo_pkt = imp;
29878 	hdr->hpo_ctx = ipst->ips_netstack;
29879 
29880 	if (ill->ill_isv6) {
29881 		hdr->hpo_family = AF_INET6;
29882 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
29883 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
29884 	} else {
29885 		hdr->hpo_family = AF_INET;
29886 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
29887 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
29888 	}
29889 
29890 	imp->b_cont = NULL;
29891 	freemsg(imp);
29892 }
29893