xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision f275d02f08c70e13825071e2577d1481e8bba78e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_setqfull(conn_t *);
823 static void	conn_clrqfull(conn_t *);
824 
825 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
826 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
827 static void	ip_stack_fini(netstackid_t stackid, void *arg);
828 
829 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
830     zoneid_t);
831 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
832     void *dummy_arg);
833 
834 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
835 
836 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
837     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
838     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
839 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
840 
841 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
842 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
843     caddr_t, cred_t *);
844 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
845     cred_t *, boolean_t);
846 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
847     caddr_t cp, cred_t *cr);
848 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
849     cred_t *);
850 static int	ip_squeue_switch(int);
851 
852 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
853 static void	ip_kstat_fini(netstackid_t, kstat_t *);
854 static int	ip_kstat_update(kstat_t *kp, int rw);
855 static void	*icmp_kstat_init(netstackid_t);
856 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
857 static int	icmp_kstat_update(kstat_t *kp, int rw);
858 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
859 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
860 
861 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
862     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
863 
864 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
865     ipha_t *, ill_t *, boolean_t, boolean_t);
866 
867 static void ipobs_init(ip_stack_t *);
868 static void ipobs_fini(ip_stack_t *);
869 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
870 
871 /* How long, in seconds, we allow frags to hang around. */
872 #define	IP_FRAG_TIMEOUT		15
873 #define	IPV6_FRAG_TIMEOUT	60
874 
875 /*
876  * Threshold which determines whether MDT should be used when
877  * generating IP fragments; payload size must be greater than
878  * this threshold for MDT to take place.
879  */
880 #define	IP_WPUT_FRAG_MDT_MIN	32768
881 
882 /* Setable in /etc/system only */
883 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
884 
885 static long ip_rput_pullups;
886 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
887 
888 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
889 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
890 
891 int	ip_debug;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
901 
902 /*
903  * XXX following really should only be in a header. Would need more
904  * header and .c clean up first.
905  */
906 extern optdb_obj_t	ip_opt_obj;
907 
908 ulong_t ip_squeue_enter_unbound = 0;
909 
910 /*
911  * Named Dispatch Parameter Table.
912  * All of these are alterable, within the min/max values given, at run time.
913  */
914 static ipparam_t	lcl_param_arr[] = {
915 	/* min	max	value	name */
916 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
918 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp"},
920 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
921 	{  0,	1,	1,	"ip_send_redirects"},
922 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
923 	{  0,	10,	0,	"ip_mrtdebug"},
924 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
925 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
926 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
927 	{  1,	255,	255,	"ip_def_ttl" },
928 	{  0,	1,	0,	"ip_forward_src_routed"},
929 	{  0,	256,	32,	"ip_wroff_extra" },
930 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
931 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
932 	{  0,	1,	1,	"ip_path_mtu_discovery" },
933 	{  0,	240,	30,	"ip_ignore_delete_time" },
934 	{  0,	1,	0,	"ip_ignore_redirect" },
935 	{  0,	1,	1,	"ip_output_queue" },
936 	{  1,	254,	1,	"ip_broadcast_ttl" },
937 	{  0,	99999,	100,	"ip_icmp_err_interval" },
938 	{  1,	99999,	10,	"ip_icmp_err_burst" },
939 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
940 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
941 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
942 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
943 	{  0,	1,	1,	"icmp_accept_clear_messages" },
944 	{  0,	1,	1,	"igmp_accept_clear_messages" },
945 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
946 				"ip_ndp_delay_first_probe_time"},
947 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
948 				"ip_ndp_max_unicast_solicit"},
949 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
950 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
951 	{  0,	1,	0,	"ip6_forward_src_routed"},
952 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
953 	{  0,	1,	1,	"ip6_send_redirects"},
954 	{  0,	1,	0,	"ip6_ignore_redirect" },
955 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
956 
957 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
958 
959 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
960 
961 	{  0,	1,	1,	"pim_accept_clear_messages" },
962 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
963 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
964 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
965 	{  0,	15,	0,	"ip_policy_mask" },
966 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
967 	{  0,	255,	1,	"ip_multirt_ttl" },
968 	{  0,	1,	1,	"ip_multidata_outbound" },
969 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
970 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
971 	{  0,	1000,	1,	"ip_max_temp_defend" },
972 	{  0,	1000,	3,	"ip_max_defend" },
973 	{  0,	999999,	30,	"ip_defend_interval" },
974 	{  0,	3600000, 300000, "ip_dup_recovery" },
975 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
976 	{  0,	1,	1,	"ip_lso_outbound" },
977 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
978 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
979 	{ 68,	65535,	576,	"ip_pmtu_min" },
980 #ifdef DEBUG
981 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
982 #else
983 	{  0,	0,	0,	"" },
984 #endif
985 };
986 
987 /*
988  * Extended NDP table
989  * The addresses for the first two are filled in to be ips_ip_g_forward
990  * and ips_ipv6_forward at init time.
991  */
992 static ipndp_t	lcl_ndp_arr[] = {
993 	/* getf			setf		data			name */
994 #define	IPNDP_IP_FORWARDING_OFFSET	0
995 	{  ip_param_generic_get,	ip_forward_set,	NULL,
996 	    "ip_forwarding" },
997 #define	IPNDP_IP6_FORWARDING_OFFSET	1
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip6_forwarding" },
1000 	{ ip_param_generic_get, ip_input_proc_set,
1001 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1002 	{ ip_param_generic_get, ip_int_set,
1003 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1004 #define	IPNDP_CGTP_FILTER_OFFSET	4
1005 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1006 	    "ip_cgtp_filter" },
1007 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1008 	    "ip_debug" },
1009 };
1010 
1011 /*
1012  * Table of IP ioctls encoding the various properties of the ioctl and
1013  * indexed based on the last byte of the ioctl command. Occasionally there
1014  * is a clash, and there is more than 1 ioctl with the same last byte.
1015  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1016  * ioctls are encoded in the misc table. An entry in the ndx table is
1017  * retrieved by indexing on the last byte of the ioctl command and comparing
1018  * the ioctl command with the value in the ndx table. In the event of a
1019  * mismatch the misc table is then searched sequentially for the desired
1020  * ioctl command.
1021  *
1022  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1023  */
1024 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1025 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1037 			MISC_CMD, ip_siocaddrt, NULL },
1038 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1039 			MISC_CMD, ip_siocdelrt, NULL },
1040 
1041 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1042 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1043 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1044 			IF_CMD, ip_sioctl_get_addr, NULL },
1045 
1046 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1047 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1048 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1049 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1050 
1051 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1052 			IPI_PRIV | IPI_WR,
1053 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1054 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1055 			IPI_MODOK | IPI_GET_CMD,
1056 			IF_CMD, ip_sioctl_get_flags, NULL },
1057 
1058 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* copyin size cannot be coded for SIOCGIFCONF */
1062 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1063 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1064 
1065 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_mtu, NULL },
1067 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1068 			IF_CMD, ip_sioctl_get_mtu, NULL },
1069 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1070 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1071 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1072 			IF_CMD, ip_sioctl_brdaddr, NULL },
1073 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1074 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1075 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1076 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1077 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1078 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1079 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1080 			IF_CMD, ip_sioctl_metric, NULL },
1081 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* See 166-168 below for extended SIOC*XARP ioctls */
1084 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1085 			ARP_CMD, ip_sioctl_arp, NULL },
1086 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1087 			ARP_CMD, ip_sioctl_arp, NULL },
1088 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1089 			ARP_CMD, ip_sioctl_arp, NULL },
1090 
1091 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1114 			MISC_CMD, if_unitsel, if_unitsel_restart },
1115 
1116 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1136 			IPI_PRIV | IPI_WR | IPI_MODOK,
1137 			IF_CMD, ip_sioctl_sifname, NULL },
1138 
1139 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 
1153 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1154 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1155 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1156 			IF_CMD, ip_sioctl_get_muxid, NULL },
1157 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1158 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1159 
1160 	/* Both if and lif variants share same func */
1161 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1162 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1163 	/* Both if and lif variants share same func */
1164 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1165 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1166 
1167 	/* copyin size cannot be coded for SIOCGIFCONF */
1168 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1169 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1170 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1190 			ip_sioctl_removeif_restart },
1191 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_addif, NULL },
1194 #define	SIOCLIFADDR_NDX 112
1195 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1197 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1198 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1199 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1201 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1202 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1203 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1204 			IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1206 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1207 			IPI_GET_CMD | IPI_MODOK,
1208 			LIF_CMD, ip_sioctl_get_flags, NULL },
1209 
1210 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 
1213 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1214 			ip_sioctl_get_lifconf, NULL },
1215 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1216 			LIF_CMD, ip_sioctl_mtu, NULL },
1217 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1218 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1219 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1220 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1221 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1222 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1223 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1224 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1225 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1227 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1228 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1229 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_metric, NULL },
1231 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR | IPI_MODOK,
1233 			LIF_CMD, ip_sioctl_slifname,
1234 			ip_sioctl_slifname_restart },
1235 
1236 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1237 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1238 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1239 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1240 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1241 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1242 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1244 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1246 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 			LIF_CMD, ip_sioctl_token, NULL },
1248 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1249 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1250 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1251 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1252 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1253 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1254 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1256 
1257 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1258 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1259 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1260 			LIF_CMD, ip_siocdelndp_v6, NULL },
1261 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1262 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1263 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1264 			LIF_CMD, ip_siocsetndp_v6, NULL },
1265 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1266 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1267 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1268 			MISC_CMD, ip_sioctl_tonlink, NULL },
1269 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1270 			MISC_CMD, ip_sioctl_tmysite, NULL },
1271 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1272 			TUN_CMD, ip_sioctl_tunparam, NULL },
1273 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1274 		    IPI_PRIV | IPI_WR,
1275 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1276 
1277 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1278 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1279 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1280 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1281 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1282 
1283 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1284 
1285 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1286 			LIF_CMD, ip_sioctl_get_binding, NULL },
1287 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1288 			IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1290 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1291 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1292 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1293 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1294 
1295 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1296 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1299 
1300 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 
1302 	/* These are handled in ip_sioctl_copyin_setup itself */
1303 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1304 			MISC_CMD, NULL, NULL },
1305 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1306 			MISC_CMD, NULL, NULL },
1307 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1308 
1309 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1310 			ip_sioctl_get_lifconf, NULL },
1311 
1312 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1313 			XARP_CMD, ip_sioctl_arp, NULL },
1314 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1315 			XARP_CMD, ip_sioctl_arp, NULL },
1316 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1317 			XARP_CMD, ip_sioctl_arp, NULL },
1318 
1319 	/* SIOCPOPSOCKFS is not handled by IP */
1320 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1321 
1322 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1323 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1324 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1325 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1326 			ip_sioctl_slifzone_restart },
1327 	/* 172-174 are SCTP ioctls and not handled by IP */
1328 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1329 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1330 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1331 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1332 			IPI_GET_CMD, LIF_CMD,
1333 			ip_sioctl_get_lifusesrc, 0 },
1334 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1335 			IPI_PRIV | IPI_WR,
1336 			LIF_CMD, ip_sioctl_slifusesrc,
1337 			NULL },
1338 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1339 			ip_sioctl_get_lifsrcof, NULL },
1340 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1341 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1342 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1343 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1344 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1345 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1346 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1347 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1348 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1349 	/* SIOCSENABLESDP is handled by SDP */
1350 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1351 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1352 };
1353 
1354 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1355 
1356 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1357 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1358 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1359 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1360 		TUN_CMD, ip_sioctl_tunparam, NULL },
1361 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1362 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1363 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1364 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1365 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1366 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1367 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1368 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1369 		MISC_CMD, mrt_ioctl},
1370 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1371 		MISC_CMD, mrt_ioctl},
1372 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1373 		MISC_CMD, mrt_ioctl}
1374 };
1375 
1376 int ip_misc_ioctl_count =
1377     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1378 
1379 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1380 					/* Settable in /etc/system */
1381 /* Defined in ip_ire.c */
1382 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1383 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1384 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1385 
1386 static nv_t	ire_nv_arr[] = {
1387 	{ IRE_BROADCAST, "BROADCAST" },
1388 	{ IRE_LOCAL, "LOCAL" },
1389 	{ IRE_LOOPBACK, "LOOPBACK" },
1390 	{ IRE_CACHE, "CACHE" },
1391 	{ IRE_DEFAULT, "DEFAULT" },
1392 	{ IRE_PREFIX, "PREFIX" },
1393 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1394 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1395 	{ IRE_HOST, "HOST" },
1396 	{ 0 }
1397 };
1398 
1399 nv_t	*ire_nv_tbl = ire_nv_arr;
1400 
1401 /* Simple ICMP IP Header Template */
1402 static ipha_t icmp_ipha = {
1403 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1404 };
1405 
1406 struct module_info ip_mod_info = {
1407 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1408 	IP_MOD_LOWAT
1409 };
1410 
1411 /*
1412  * Duplicate static symbols within a module confuses mdb; so we avoid the
1413  * problem by making the symbols here distinct from those in udp.c.
1414  */
1415 
1416 /*
1417  * Entry points for IP as a device and as a module.
1418  * FIXME: down the road we might want a separate module and driver qinit.
1419  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1420  */
1421 static struct qinit iprinitv4 = {
1422 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1423 	&ip_mod_info
1424 };
1425 
1426 struct qinit iprinitv6 = {
1427 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1428 	&ip_mod_info
1429 };
1430 
1431 static struct qinit ipwinitv4 = {
1432 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1433 	&ip_mod_info
1434 };
1435 
1436 struct qinit ipwinitv6 = {
1437 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1438 	&ip_mod_info
1439 };
1440 
1441 static struct qinit iplrinit = {
1442 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1443 	&ip_mod_info
1444 };
1445 
1446 static struct qinit iplwinit = {
1447 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1448 	&ip_mod_info
1449 };
1450 
1451 /* For AF_INET aka /dev/ip */
1452 struct streamtab ipinfov4 = {
1453 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1454 };
1455 
1456 /* For AF_INET6 aka /dev/ip6 */
1457 struct streamtab ipinfov6 = {
1458 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1459 };
1460 
1461 #ifdef	DEBUG
1462 static boolean_t skip_sctp_cksum = B_FALSE;
1463 #endif
1464 
1465 /*
1466  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1467  * ip_rput_v6(), ip_output(), etc.  If the message
1468  * block already has a M_CTL at the front of it, then simply set the zoneid
1469  * appropriately.
1470  */
1471 mblk_t *
1472 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1473 {
1474 	mblk_t		*first_mp;
1475 	ipsec_out_t	*io;
1476 
1477 	ASSERT(zoneid != ALL_ZONES);
1478 	if (mp->b_datap->db_type == M_CTL) {
1479 		io = (ipsec_out_t *)mp->b_rptr;
1480 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1481 		io->ipsec_out_zoneid = zoneid;
1482 		return (mp);
1483 	}
1484 
1485 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1486 	if (first_mp == NULL)
1487 		return (NULL);
1488 	io = (ipsec_out_t *)first_mp->b_rptr;
1489 	/* This is not a secure packet */
1490 	io->ipsec_out_secure = B_FALSE;
1491 	io->ipsec_out_zoneid = zoneid;
1492 	first_mp->b_cont = mp;
1493 	return (first_mp);
1494 }
1495 
1496 /*
1497  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1498  */
1499 mblk_t *
1500 ip_copymsg(mblk_t *mp)
1501 {
1502 	mblk_t *nmp;
1503 	ipsec_info_t *in;
1504 
1505 	if (mp->b_datap->db_type != M_CTL)
1506 		return (copymsg(mp));
1507 
1508 	in = (ipsec_info_t *)mp->b_rptr;
1509 
1510 	/*
1511 	 * Note that M_CTL is also used for delivering ICMP error messages
1512 	 * upstream to transport layers.
1513 	 */
1514 	if (in->ipsec_info_type != IPSEC_OUT &&
1515 	    in->ipsec_info_type != IPSEC_IN)
1516 		return (copymsg(mp));
1517 
1518 	nmp = copymsg(mp->b_cont);
1519 
1520 	if (in->ipsec_info_type == IPSEC_OUT) {
1521 		return (ipsec_out_tag(mp, nmp,
1522 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1523 	} else {
1524 		return (ipsec_in_tag(mp, nmp,
1525 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1526 	}
1527 }
1528 
1529 /* Generate an ICMP fragmentation needed message. */
1530 static void
1531 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1532     ip_stack_t *ipst)
1533 {
1534 	icmph_t	icmph;
1535 	mblk_t *first_mp;
1536 	boolean_t mctl_present;
1537 
1538 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1539 
1540 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1541 		if (mctl_present)
1542 			freeb(first_mp);
1543 		return;
1544 	}
1545 
1546 	bzero(&icmph, sizeof (icmph_t));
1547 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1548 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1549 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1550 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1551 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1552 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1553 	    ipst);
1554 }
1555 
1556 /*
1557  * icmp_inbound deals with ICMP messages in the following ways.
1558  *
1559  * 1) It needs to send a reply back and possibly delivering it
1560  *    to the "interested" upper clients.
1561  * 2) It needs to send it to the upper clients only.
1562  * 3) It needs to change some values in IP only.
1563  * 4) It needs to change some values in IP and upper layers e.g TCP.
1564  *
1565  * We need to accomodate icmp messages coming in clear until we get
1566  * everything secure from the wire. If icmp_accept_clear_messages
1567  * is zero we check with the global policy and act accordingly. If
1568  * it is non-zero, we accept the message without any checks. But
1569  * *this does not mean* that this will be delivered to the upper
1570  * clients. By accepting we might send replies back, change our MTU
1571  * value etc. but delivery to the ULP/clients depends on their policy
1572  * dispositions.
1573  *
1574  * We handle the above 4 cases in the context of IPsec in the
1575  * following way :
1576  *
1577  * 1) Send the reply back in the same way as the request came in.
1578  *    If it came in encrypted, it goes out encrypted. If it came in
1579  *    clear, it goes out in clear. Thus, this will prevent chosen
1580  *    plain text attack.
1581  * 2) The client may or may not expect things to come in secure.
1582  *    If it comes in secure, the policy constraints are checked
1583  *    before delivering it to the upper layers. If it comes in
1584  *    clear, ipsec_inbound_accept_clear will decide whether to
1585  *    accept this in clear or not. In both the cases, if the returned
1586  *    message (IP header + 8 bytes) that caused the icmp message has
1587  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1588  *    sending up. If there are only 8 bytes of returned message, then
1589  *    upper client will not be notified.
1590  * 3) Check with global policy to see whether it matches the constaints.
1591  *    But this will be done only if icmp_accept_messages_in_clear is
1592  *    zero.
1593  * 4) If we need to change both in IP and ULP, then the decision taken
1594  *    while affecting the values in IP and while delivering up to TCP
1595  *    should be the same.
1596  *
1597  * 	There are two cases.
1598  *
1599  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1600  *	   failed), we will not deliver it to the ULP, even though they
1601  *	   are *willing* to accept in *clear*. This is fine as our global
1602  *	   disposition to icmp messages asks us reject the datagram.
1603  *
1604  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1605  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1606  *	   to deliver it to ULP (policy failed), it can lead to
1607  *	   consistency problems. The cases known at this time are
1608  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1609  *	   values :
1610  *
1611  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1612  *	     and Upper layer rejects. Then the communication will
1613  *	     come to a stop. This is solved by making similar decisions
1614  *	     at both levels. Currently, when we are unable to deliver
1615  *	     to the Upper Layer (due to policy failures) while IP has
1616  *	     adjusted ire_max_frag, the next outbound datagram would
1617  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1618  *	     will be with the right level of protection. Thus the right
1619  *	     value will be communicated even if we are not able to
1620  *	     communicate when we get from the wire initially. But this
1621  *	     assumes there would be at least one outbound datagram after
1622  *	     IP has adjusted its ire_max_frag value. To make things
1623  *	     simpler, we accept in clear after the validation of
1624  *	     AH/ESP headers.
1625  *
1626  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1627  *	     upper layer depending on the level of protection the upper
1628  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1629  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1630  *	     should be accepted in clear when the Upper layer expects secure.
1631  *	     Thus the communication may get aborted by some bad ICMP
1632  *	     packets.
1633  *
1634  * IPQoS Notes:
1635  * The only instance when a packet is sent for processing is when there
1636  * isn't an ICMP client and if we are interested in it.
1637  * If there is a client, IPPF processing will take place in the
1638  * ip_fanout_proto routine.
1639  *
1640  * Zones notes:
1641  * The packet is only processed in the context of the specified zone: typically
1642  * only this zone will reply to an echo request, and only interested clients in
1643  * this zone will receive a copy of the packet. This means that the caller must
1644  * call icmp_inbound() for each relevant zone.
1645  */
1646 static void
1647 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1648     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1649     ill_t *recv_ill, zoneid_t zoneid)
1650 {
1651 	icmph_t	*icmph;
1652 	ipha_t	*ipha;
1653 	int	iph_hdr_length;
1654 	int	hdr_length;
1655 	boolean_t	interested;
1656 	uint32_t	ts;
1657 	uchar_t	*wptr;
1658 	ipif_t	*ipif;
1659 	mblk_t *first_mp;
1660 	ipsec_in_t *ii;
1661 	timestruc_t now;
1662 	uint32_t ill_index;
1663 	ip_stack_t *ipst;
1664 
1665 	ASSERT(ill != NULL);
1666 	ipst = ill->ill_ipst;
1667 
1668 	first_mp = mp;
1669 	if (mctl_present) {
1670 		mp = first_mp->b_cont;
1671 		ASSERT(mp != NULL);
1672 	}
1673 
1674 	ipha = (ipha_t *)mp->b_rptr;
1675 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1676 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1677 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1678 		if (first_mp == NULL)
1679 			return;
1680 	}
1681 
1682 	/*
1683 	 * On a labeled system, we have to check whether the zone itself is
1684 	 * permitted to receive raw traffic.
1685 	 */
1686 	if (is_system_labeled()) {
1687 		if (zoneid == ALL_ZONES)
1688 			zoneid = tsol_packet_to_zoneid(mp);
1689 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1690 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1691 			    zoneid));
1692 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1693 			freemsg(first_mp);
1694 			return;
1695 		}
1696 	}
1697 
1698 	/*
1699 	 * We have accepted the ICMP message. It means that we will
1700 	 * respond to the packet if needed. It may not be delivered
1701 	 * to the upper client depending on the policy constraints
1702 	 * and the disposition in ipsec_inbound_accept_clear.
1703 	 */
1704 
1705 	ASSERT(ill != NULL);
1706 
1707 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1708 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1709 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1710 		/* Last chance to get real. */
1711 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1712 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1713 			freemsg(first_mp);
1714 			return;
1715 		}
1716 		/* Refresh iph following the pullup. */
1717 		ipha = (ipha_t *)mp->b_rptr;
1718 	}
1719 	/* ICMP header checksum, including checksum field, should be zero. */
1720 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1721 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1723 		freemsg(first_mp);
1724 		return;
1725 	}
1726 	/* The IP header will always be a multiple of four bytes */
1727 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1728 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1729 	    icmph->icmph_code));
1730 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1731 	/* We will set "interested" to "true" if we want a copy */
1732 	interested = B_FALSE;
1733 	switch (icmph->icmph_type) {
1734 	case ICMP_ECHO_REPLY:
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1736 		break;
1737 	case ICMP_DEST_UNREACHABLE:
1738 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1739 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1740 		interested = B_TRUE;	/* Pass up to transport */
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1742 		break;
1743 	case ICMP_SOURCE_QUENCH:
1744 		interested = B_TRUE;	/* Pass up to transport */
1745 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1746 		break;
1747 	case ICMP_REDIRECT:
1748 		if (!ipst->ips_ip_ignore_redirect)
1749 			interested = B_TRUE;
1750 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1751 		break;
1752 	case ICMP_ECHO_REQUEST:
1753 		/*
1754 		 * Whether to respond to echo requests that come in as IP
1755 		 * broadcasts or as IP multicast is subject to debate
1756 		 * (what isn't?).  We aim to please, you pick it.
1757 		 * Default is do it.
1758 		 */
1759 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1760 			/* unicast: always respond */
1761 			interested = B_TRUE;
1762 		} else if (CLASSD(ipha->ipha_dst)) {
1763 			/* multicast: respond based on tunable */
1764 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1765 		} else if (broadcast) {
1766 			/* broadcast: respond based on tunable */
1767 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1768 		}
1769 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1770 		break;
1771 	case ICMP_ROUTER_ADVERTISEMENT:
1772 	case ICMP_ROUTER_SOLICITATION:
1773 		break;
1774 	case ICMP_TIME_EXCEEDED:
1775 		interested = B_TRUE;	/* Pass up to transport */
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1777 		break;
1778 	case ICMP_PARAM_PROBLEM:
1779 		interested = B_TRUE;	/* Pass up to transport */
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1781 		break;
1782 	case ICMP_TIME_STAMP_REQUEST:
1783 		/* Response to Time Stamp Requests is local policy. */
1784 		if (ipst->ips_ip_g_resp_to_timestamp &&
1785 		    /* So is whether to respond if it was an IP broadcast. */
1786 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1787 			int tstamp_len = 3 * sizeof (uint32_t);
1788 
1789 			if (wptr +  tstamp_len > mp->b_wptr) {
1790 				if (!pullupmsg(mp, wptr + tstamp_len -
1791 				    mp->b_rptr)) {
1792 					BUMP_MIB(ill->ill_ip_mib,
1793 					    ipIfStatsInDiscards);
1794 					freemsg(first_mp);
1795 					return;
1796 				}
1797 				/* Refresh ipha following the pullup. */
1798 				ipha = (ipha_t *)mp->b_rptr;
1799 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1800 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1801 			}
1802 			interested = B_TRUE;
1803 		}
1804 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1805 		break;
1806 	case ICMP_TIME_STAMP_REPLY:
1807 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1808 		break;
1809 	case ICMP_INFO_REQUEST:
1810 		/* Per RFC 1122 3.2.2.7, ignore this. */
1811 	case ICMP_INFO_REPLY:
1812 		break;
1813 	case ICMP_ADDRESS_MASK_REQUEST:
1814 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1815 		    !broadcast) &&
1816 		    /* TODO m_pullup of complete header? */
1817 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1818 			interested = B_TRUE;
1819 		}
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1821 		break;
1822 	case ICMP_ADDRESS_MASK_REPLY:
1823 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1824 		break;
1825 	default:
1826 		interested = B_TRUE;	/* Pass up to transport */
1827 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1828 		break;
1829 	}
1830 	/* See if there is an ICMP client. */
1831 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1832 		/* If there is an ICMP client and we want one too, copy it. */
1833 		mblk_t *first_mp1;
1834 
1835 		if (!interested) {
1836 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1837 			    ip_policy, recv_ill, zoneid);
1838 			return;
1839 		}
1840 		first_mp1 = ip_copymsg(first_mp);
1841 		if (first_mp1 != NULL) {
1842 			ip_fanout_proto(q, first_mp1, ill, ipha,
1843 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1844 		}
1845 	} else if (!interested) {
1846 		freemsg(first_mp);
1847 		return;
1848 	} else {
1849 		/*
1850 		 * Initiate policy processing for this packet if ip_policy
1851 		 * is true.
1852 		 */
1853 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1854 			ill_index = ill->ill_phyint->phyint_ifindex;
1855 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1856 			if (mp == NULL) {
1857 				if (mctl_present) {
1858 					freeb(first_mp);
1859 				}
1860 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1861 				return;
1862 			}
1863 		}
1864 	}
1865 	/* We want to do something with it. */
1866 	/* Check db_ref to make sure we can modify the packet. */
1867 	if (mp->b_datap->db_ref > 1) {
1868 		mblk_t	*first_mp1;
1869 
1870 		first_mp1 = ip_copymsg(first_mp);
1871 		freemsg(first_mp);
1872 		if (!first_mp1) {
1873 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1874 			return;
1875 		}
1876 		first_mp = first_mp1;
1877 		if (mctl_present) {
1878 			mp = first_mp->b_cont;
1879 			ASSERT(mp != NULL);
1880 		} else {
1881 			mp = first_mp;
1882 		}
1883 		ipha = (ipha_t *)mp->b_rptr;
1884 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1885 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1886 	}
1887 	switch (icmph->icmph_type) {
1888 	case ICMP_ADDRESS_MASK_REQUEST:
1889 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1890 		if (ipif == NULL) {
1891 			freemsg(first_mp);
1892 			return;
1893 		}
1894 		/*
1895 		 * outging interface must be IPv4
1896 		 */
1897 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1898 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1899 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1900 		ipif_refrele(ipif);
1901 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1902 		break;
1903 	case ICMP_ECHO_REQUEST:
1904 		icmph->icmph_type = ICMP_ECHO_REPLY;
1905 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1906 		break;
1907 	case ICMP_TIME_STAMP_REQUEST: {
1908 		uint32_t *tsp;
1909 
1910 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1911 		tsp = (uint32_t *)wptr;
1912 		tsp++;		/* Skip past 'originate time' */
1913 		/* Compute # of milliseconds since midnight */
1914 		gethrestime(&now);
1915 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1916 		    now.tv_nsec / (NANOSEC / MILLISEC);
1917 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1918 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1919 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1920 		break;
1921 	}
1922 	default:
1923 		ipha = (ipha_t *)&icmph[1];
1924 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1925 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1926 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1927 				freemsg(first_mp);
1928 				return;
1929 			}
1930 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1931 			ipha = (ipha_t *)&icmph[1];
1932 		}
1933 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1934 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1935 			freemsg(first_mp);
1936 			return;
1937 		}
1938 		hdr_length = IPH_HDR_LENGTH(ipha);
1939 		if (hdr_length < sizeof (ipha_t)) {
1940 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1941 			freemsg(first_mp);
1942 			return;
1943 		}
1944 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1945 			if (!pullupmsg(mp,
1946 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1947 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1948 				freemsg(first_mp);
1949 				return;
1950 			}
1951 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1952 			ipha = (ipha_t *)&icmph[1];
1953 		}
1954 		switch (icmph->icmph_type) {
1955 		case ICMP_REDIRECT:
1956 			/*
1957 			 * As there is no upper client to deliver, we don't
1958 			 * need the first_mp any more.
1959 			 */
1960 			if (mctl_present) {
1961 				freeb(first_mp);
1962 			}
1963 			icmp_redirect(ill, mp);
1964 			return;
1965 		case ICMP_DEST_UNREACHABLE:
1966 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1967 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1968 				    zoneid, mp, iph_hdr_length, ipst)) {
1969 					freemsg(first_mp);
1970 					return;
1971 				}
1972 				/*
1973 				 * icmp_inbound_too_big() may alter mp.
1974 				 * Resynch ipha and icmph accordingly.
1975 				 */
1976 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1977 				ipha = (ipha_t *)&icmph[1];
1978 			}
1979 			/* FALLTHRU */
1980 		default :
1981 			/*
1982 			 * IPQoS notes: Since we have already done IPQoS
1983 			 * processing we don't want to do it again in
1984 			 * the fanout routines called by
1985 			 * icmp_inbound_error_fanout, hence the last
1986 			 * argument, ip_policy, is B_FALSE.
1987 			 */
1988 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1989 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1990 			    B_FALSE, recv_ill, zoneid);
1991 		}
1992 		return;
1993 	}
1994 	/* Send out an ICMP packet */
1995 	icmph->icmph_checksum = 0;
1996 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1997 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1998 		ipif_t	*ipif_chosen;
1999 		/*
2000 		 * Make it look like it was directed to us, so we don't look
2001 		 * like a fool with a broadcast or multicast source address.
2002 		 */
2003 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2004 		/*
2005 		 * Make sure that we haven't grabbed an interface that's DOWN.
2006 		 */
2007 		if (ipif != NULL) {
2008 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2009 			    ipha->ipha_src, zoneid);
2010 			if (ipif_chosen != NULL) {
2011 				ipif_refrele(ipif);
2012 				ipif = ipif_chosen;
2013 			}
2014 		}
2015 		if (ipif == NULL) {
2016 			ip0dbg(("icmp_inbound: "
2017 			    "No source for broadcast/multicast:\n"
2018 			    "\tsrc 0x%x dst 0x%x ill %p "
2019 			    "ipif_lcl_addr 0x%x\n",
2020 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2021 			    (void *)ill,
2022 			    ill->ill_ipif->ipif_lcl_addr));
2023 			freemsg(first_mp);
2024 			return;
2025 		}
2026 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2027 		ipha->ipha_dst = ipif->ipif_src_addr;
2028 		ipif_refrele(ipif);
2029 	}
2030 	/* Reset time to live. */
2031 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2032 	{
2033 		/* Swap source and destination addresses */
2034 		ipaddr_t tmp;
2035 
2036 		tmp = ipha->ipha_src;
2037 		ipha->ipha_src = ipha->ipha_dst;
2038 		ipha->ipha_dst = tmp;
2039 	}
2040 	ipha->ipha_ident = 0;
2041 	if (!IS_SIMPLE_IPH(ipha))
2042 		icmp_options_update(ipha);
2043 
2044 	if (!mctl_present) {
2045 		/*
2046 		 * This packet should go out the same way as it
2047 		 * came in i.e in clear. To make sure that global
2048 		 * policy will not be applied to this in ip_wput_ire,
2049 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2050 		 */
2051 		ASSERT(first_mp == mp);
2052 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2053 		if (first_mp == NULL) {
2054 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 			freemsg(mp);
2056 			return;
2057 		}
2058 		ii = (ipsec_in_t *)first_mp->b_rptr;
2059 
2060 		/* This is not a secure packet */
2061 		ii->ipsec_in_secure = B_FALSE;
2062 		first_mp->b_cont = mp;
2063 	} else {
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2066 	}
2067 	ii->ipsec_in_zoneid = zoneid;
2068 	ASSERT(zoneid != ALL_ZONES);
2069 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2070 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2071 		return;
2072 	}
2073 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2074 	put(WR(q), first_mp);
2075 }
2076 
2077 static ipaddr_t
2078 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2079 {
2080 	conn_t *connp;
2081 	connf_t *connfp;
2082 	ipaddr_t nexthop_addr = INADDR_ANY;
2083 	int hdr_length = IPH_HDR_LENGTH(ipha);
2084 	uint16_t *up;
2085 	uint32_t ports;
2086 	ip_stack_t *ipst = ill->ill_ipst;
2087 
2088 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2089 	switch (ipha->ipha_protocol) {
2090 		case IPPROTO_TCP:
2091 		{
2092 			tcph_t *tcph;
2093 
2094 			/* do a reverse lookup */
2095 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2096 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2097 			    TCPS_LISTEN, ipst);
2098 			break;
2099 		}
2100 		case IPPROTO_UDP:
2101 		{
2102 			uint32_t dstport, srcport;
2103 
2104 			((uint16_t *)&ports)[0] = up[1];
2105 			((uint16_t *)&ports)[1] = up[0];
2106 
2107 			/* Extract ports in net byte order */
2108 			dstport = htons(ntohl(ports) & 0xFFFF);
2109 			srcport = htons(ntohl(ports) >> 16);
2110 
2111 			connfp = &ipst->ips_ipcl_udp_fanout[
2112 			    IPCL_UDP_HASH(dstport, ipst)];
2113 			mutex_enter(&connfp->connf_lock);
2114 			connp = connfp->connf_head;
2115 
2116 			/* do a reverse lookup */
2117 			while ((connp != NULL) &&
2118 			    (!IPCL_UDP_MATCH(connp, dstport,
2119 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2120 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2121 				connp = connp->conn_next;
2122 			}
2123 			if (connp != NULL)
2124 				CONN_INC_REF(connp);
2125 			mutex_exit(&connfp->connf_lock);
2126 			break;
2127 		}
2128 		case IPPROTO_SCTP:
2129 		{
2130 			in6_addr_t map_src, map_dst;
2131 
2132 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2133 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2134 			((uint16_t *)&ports)[0] = up[1];
2135 			((uint16_t *)&ports)[1] = up[0];
2136 
2137 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2138 			    zoneid, ipst->ips_netstack->netstack_sctp);
2139 			if (connp == NULL) {
2140 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2141 				    zoneid, ports, ipha, ipst);
2142 			} else {
2143 				CONN_INC_REF(connp);
2144 				SCTP_REFRELE(CONN2SCTP(connp));
2145 			}
2146 			break;
2147 		}
2148 		default:
2149 		{
2150 			ipha_t ripha;
2151 
2152 			ripha.ipha_src = ipha->ipha_dst;
2153 			ripha.ipha_dst = ipha->ipha_src;
2154 			ripha.ipha_protocol = ipha->ipha_protocol;
2155 
2156 			connfp = &ipst->ips_ipcl_proto_fanout[
2157 			    ipha->ipha_protocol];
2158 			mutex_enter(&connfp->connf_lock);
2159 			connp = connfp->connf_head;
2160 			for (connp = connfp->connf_head; connp != NULL;
2161 			    connp = connp->conn_next) {
2162 				if (IPCL_PROTO_MATCH(connp,
2163 				    ipha->ipha_protocol, &ripha, ill,
2164 				    0, zoneid)) {
2165 					CONN_INC_REF(connp);
2166 					break;
2167 				}
2168 			}
2169 			mutex_exit(&connfp->connf_lock);
2170 		}
2171 	}
2172 	if (connp != NULL) {
2173 		if (connp->conn_nexthop_set)
2174 			nexthop_addr = connp->conn_nexthop_v4;
2175 		CONN_DEC_REF(connp);
2176 	}
2177 	return (nexthop_addr);
2178 }
2179 
2180 /* Table from RFC 1191 */
2181 static int icmp_frag_size_table[] =
2182 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2183 
2184 /*
2185  * Process received ICMP Packet too big.
2186  * After updating any IRE it does the fanout to any matching transport streams.
2187  * Assumes the message has been pulled up till the IP header that caused
2188  * the error.
2189  *
2190  * Returns B_FALSE on failure and B_TRUE on success.
2191  */
2192 static boolean_t
2193 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2194     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2195     ip_stack_t *ipst)
2196 {
2197 	ire_t	*ire, *first_ire;
2198 	int	mtu, orig_mtu;
2199 	int	hdr_length;
2200 	ipaddr_t nexthop_addr;
2201 	boolean_t disable_pmtud;
2202 
2203 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2204 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2205 	ASSERT(ill != NULL);
2206 
2207 	hdr_length = IPH_HDR_LENGTH(ipha);
2208 
2209 	/* Drop if the original packet contained a source route */
2210 	if (ip_source_route_included(ipha)) {
2211 		return (B_FALSE);
2212 	}
2213 	/*
2214 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2215 	 * header.
2216 	 */
2217 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2218 	    mp->b_wptr) {
2219 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2220 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2222 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2223 			return (B_FALSE);
2224 		}
2225 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2226 		ipha = (ipha_t *)&icmph[1];
2227 	}
2228 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2229 	if (nexthop_addr != INADDR_ANY) {
2230 		/* nexthop set */
2231 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2232 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2233 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2234 	} else {
2235 		/* nexthop not set */
2236 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2237 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2238 	}
2239 
2240 	if (!first_ire) {
2241 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2242 		    ntohl(ipha->ipha_dst)));
2243 		return (B_FALSE);
2244 	}
2245 
2246 	/* Check for MTU discovery advice as described in RFC 1191 */
2247 	mtu = ntohs(icmph->icmph_du_mtu);
2248 	orig_mtu = mtu;
2249 	disable_pmtud = B_FALSE;
2250 
2251 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2252 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2253 	    ire = ire->ire_next) {
2254 		/*
2255 		 * Look for the connection to which this ICMP message is
2256 		 * directed. If it has the IP_NEXTHOP option set, then the
2257 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2258 		 * option. Else the search is limited to regular IREs.
2259 		 */
2260 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2262 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2263 		    (nexthop_addr != INADDR_ANY)))
2264 			continue;
2265 
2266 		mutex_enter(&ire->ire_lock);
2267 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2268 			uint32_t length;
2269 			int	i;
2270 
2271 			/*
2272 			 * Use the table from RFC 1191 to figure out
2273 			 * the next "plateau" based on the length in
2274 			 * the original IP packet.
2275 			 */
2276 			length = ntohs(ipha->ipha_length);
2277 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2278 			    uint32_t, length);
2279 			if (ire->ire_max_frag <= length &&
2280 			    ire->ire_max_frag >= length - hdr_length) {
2281 				/*
2282 				 * Handle broken BSD 4.2 systems that
2283 				 * return the wrong iph_length in ICMP
2284 				 * errors.
2285 				 */
2286 				length -= hdr_length;
2287 			}
2288 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2289 				if (length > icmp_frag_size_table[i])
2290 					break;
2291 			}
2292 			if (i == A_CNT(icmp_frag_size_table)) {
2293 				/* Smaller than 68! */
2294 				disable_pmtud = B_TRUE;
2295 				mtu = ipst->ips_ip_pmtu_min;
2296 			} else {
2297 				mtu = icmp_frag_size_table[i];
2298 				if (mtu < ipst->ips_ip_pmtu_min) {
2299 					mtu = ipst->ips_ip_pmtu_min;
2300 					disable_pmtud = B_TRUE;
2301 				}
2302 			}
2303 			/* Fool the ULP into believing our guessed PMTU. */
2304 			icmph->icmph_du_zero = 0;
2305 			icmph->icmph_du_mtu = htons(mtu);
2306 		}
2307 		if (disable_pmtud)
2308 			ire->ire_frag_flag = 0;
2309 		/* Reduce the IRE max frag value as advised. */
2310 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2311 		if (ire->ire_max_frag == mtu) {
2312 			/* Decreased it */
2313 			ire->ire_marks |= IRE_MARK_PMTU;
2314 		}
2315 		mutex_exit(&ire->ire_lock);
2316 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2317 		    ire, int, orig_mtu, int, mtu);
2318 	}
2319 	rw_exit(&first_ire->ire_bucket->irb_lock);
2320 	ire_refrele(first_ire);
2321 	return (B_TRUE);
2322 }
2323 
2324 /*
2325  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2326  * calls this function.
2327  */
2328 static mblk_t *
2329 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2330 {
2331 	ipha_t *ipha;
2332 	icmph_t *icmph;
2333 	ipha_t *in_ipha;
2334 	int length;
2335 
2336 	ASSERT(mp->b_datap->db_type == M_DATA);
2337 
2338 	/*
2339 	 * For Self-encapsulated packets, we added an extra IP header
2340 	 * without the options. Inner IP header is the one from which
2341 	 * the outer IP header was formed. Thus, we need to remove the
2342 	 * outer IP header. To do this, we pullup the whole message
2343 	 * and overlay whatever follows the outer IP header over the
2344 	 * outer IP header.
2345 	 */
2346 
2347 	if (!pullupmsg(mp, -1))
2348 		return (NULL);
2349 
2350 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2351 	ipha = (ipha_t *)&icmph[1];
2352 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2353 
2354 	/*
2355 	 * The length that we want to overlay is following the inner
2356 	 * IP header. Subtracting the IP header + icmp header + outer
2357 	 * IP header's length should give us the length that we want to
2358 	 * overlay.
2359 	 */
2360 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2361 	    hdr_length;
2362 	/*
2363 	 * Overlay whatever follows the inner header over the
2364 	 * outer header.
2365 	 */
2366 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2367 
2368 	/* Set the wptr to account for the outer header */
2369 	mp->b_wptr -= hdr_length;
2370 	return (mp);
2371 }
2372 
2373 /*
2374  * Try to pass the ICMP message upstream in case the ULP cares.
2375  *
2376  * If the packet that caused the ICMP error is secure, we send
2377  * it to AH/ESP to make sure that the attached packet has a
2378  * valid association. ipha in the code below points to the
2379  * IP header of the packet that caused the error.
2380  *
2381  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2382  * in the context of IPsec. Normally we tell the upper layer
2383  * whenever we send the ire (including ip_bind), the IPsec header
2384  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2385  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2386  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2387  * same thing. As TCP has the IPsec options size that needs to be
2388  * adjusted, we just pass the MTU unchanged.
2389  *
2390  * IFN could have been generated locally or by some router.
2391  *
2392  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2393  *	    This happens because IP adjusted its value of MTU on an
2394  *	    earlier IFN message and could not tell the upper layer,
2395  *	    the new adjusted value of MTU e.g. Packet was encrypted
2396  *	    or there was not enough information to fanout to upper
2397  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2398  *	    generates the IFN, where IPsec processing has *not* been
2399  *	    done.
2400  *
2401  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2402  *	    could have generated this. This happens because ire_max_frag
2403  *	    value in IP was set to a new value, while the IPsec processing
2404  *	    was being done and after we made the fragmentation check in
2405  *	    ip_wput_ire. Thus on return from IPsec processing,
2406  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2407  *	    and generates the IFN. As IPsec processing is over, we fanout
2408  *	    to AH/ESP to remove the header.
2409  *
2410  *	    In both these cases, ipsec_in_loopback will be set indicating
2411  *	    that IFN was generated locally.
2412  *
2413  * ROUTER : IFN could be secure or non-secure.
2414  *
2415  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2416  *	      packet in error has AH/ESP headers to validate the AH/ESP
2417  *	      headers. AH/ESP will verify whether there is a valid SA or
2418  *	      not and send it back. We will fanout again if we have more
2419  *	      data in the packet.
2420  *
2421  *	      If the packet in error does not have AH/ESP, we handle it
2422  *	      like any other case.
2423  *
2424  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2425  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2426  *	      for validation. AH/ESP will verify whether there is a
2427  *	      valid SA or not and send it back. We will fanout again if
2428  *	      we have more data in the packet.
2429  *
2430  *	      If the packet in error does not have AH/ESP, we handle it
2431  *	      like any other case.
2432  */
2433 static void
2434 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2435     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2436     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2437     zoneid_t zoneid)
2438 {
2439 	uint16_t *up;	/* Pointer to ports in ULP header */
2440 	uint32_t ports;	/* reversed ports for fanout */
2441 	ipha_t ripha;	/* With reversed addresses */
2442 	mblk_t *first_mp;
2443 	ipsec_in_t *ii;
2444 	tcph_t	*tcph;
2445 	conn_t	*connp;
2446 	ip_stack_t *ipst;
2447 
2448 	ASSERT(ill != NULL);
2449 
2450 	ASSERT(recv_ill != NULL);
2451 	ipst = recv_ill->ill_ipst;
2452 
2453 	first_mp = mp;
2454 	if (mctl_present) {
2455 		mp = first_mp->b_cont;
2456 		ASSERT(mp != NULL);
2457 
2458 		ii = (ipsec_in_t *)first_mp->b_rptr;
2459 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2460 	} else {
2461 		ii = NULL;
2462 	}
2463 
2464 	switch (ipha->ipha_protocol) {
2465 	case IPPROTO_UDP:
2466 		/*
2467 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2468 		 * transport header.
2469 		 */
2470 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2471 		    mp->b_wptr) {
2472 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2473 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2474 				goto discard_pkt;
2475 			}
2476 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2477 			ipha = (ipha_t *)&icmph[1];
2478 		}
2479 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2480 
2481 		/*
2482 		 * Attempt to find a client stream based on port.
2483 		 * Note that we do a reverse lookup since the header is
2484 		 * in the form we sent it out.
2485 		 * The ripha header is only used for the IP_UDP_MATCH and we
2486 		 * only set the src and dst addresses and protocol.
2487 		 */
2488 		ripha.ipha_src = ipha->ipha_dst;
2489 		ripha.ipha_dst = ipha->ipha_src;
2490 		ripha.ipha_protocol = ipha->ipha_protocol;
2491 		((uint16_t *)&ports)[0] = up[1];
2492 		((uint16_t *)&ports)[1] = up[0];
2493 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2494 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2495 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2496 		    icmph->icmph_type, icmph->icmph_code));
2497 
2498 		/* Have to change db_type after any pullupmsg */
2499 		DB_TYPE(mp) = M_CTL;
2500 
2501 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2502 		    mctl_present, ip_policy, recv_ill, zoneid);
2503 		return;
2504 
2505 	case IPPROTO_TCP:
2506 		/*
2507 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2508 		 * transport header.
2509 		 */
2510 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2511 		    mp->b_wptr) {
2512 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2513 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2514 				goto discard_pkt;
2515 			}
2516 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2517 			ipha = (ipha_t *)&icmph[1];
2518 		}
2519 		/*
2520 		 * Find a TCP client stream for this packet.
2521 		 * Note that we do a reverse lookup since the header is
2522 		 * in the form we sent it out.
2523 		 */
2524 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2525 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2526 		    ipst);
2527 		if (connp == NULL)
2528 			goto discard_pkt;
2529 
2530 		/* Have to change db_type after any pullupmsg */
2531 		DB_TYPE(mp) = M_CTL;
2532 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2533 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2534 		return;
2535 
2536 	case IPPROTO_SCTP:
2537 		/*
2538 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2539 		 * transport header.
2540 		 */
2541 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2542 		    mp->b_wptr) {
2543 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2544 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2545 				goto discard_pkt;
2546 			}
2547 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2548 			ipha = (ipha_t *)&icmph[1];
2549 		}
2550 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2551 		/*
2552 		 * Find a SCTP client stream for this packet.
2553 		 * Note that we do a reverse lookup since the header is
2554 		 * in the form we sent it out.
2555 		 * The ripha header is only used for the matching and we
2556 		 * only set the src and dst addresses, protocol, and version.
2557 		 */
2558 		ripha.ipha_src = ipha->ipha_dst;
2559 		ripha.ipha_dst = ipha->ipha_src;
2560 		ripha.ipha_protocol = ipha->ipha_protocol;
2561 		ripha.ipha_version_and_hdr_length =
2562 		    ipha->ipha_version_and_hdr_length;
2563 		((uint16_t *)&ports)[0] = up[1];
2564 		((uint16_t *)&ports)[1] = up[0];
2565 
2566 		/* Have to change db_type after any pullupmsg */
2567 		DB_TYPE(mp) = M_CTL;
2568 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2569 		    mctl_present, ip_policy, zoneid);
2570 		return;
2571 
2572 	case IPPROTO_ESP:
2573 	case IPPROTO_AH: {
2574 		int ipsec_rc;
2575 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2576 
2577 		/*
2578 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2579 		 * We will re-use the IPSEC_IN if it is already present as
2580 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2581 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2582 		 * one and attach it in the front.
2583 		 */
2584 		if (ii != NULL) {
2585 			/*
2586 			 * ip_fanout_proto_again converts the ICMP errors
2587 			 * that come back from AH/ESP to M_DATA so that
2588 			 * if it is non-AH/ESP and we do a pullupmsg in
2589 			 * this function, it would work. Convert it back
2590 			 * to M_CTL before we send up as this is a ICMP
2591 			 * error. This could have been generated locally or
2592 			 * by some router. Validate the inner IPsec
2593 			 * headers.
2594 			 *
2595 			 * NOTE : ill_index is used by ip_fanout_proto_again
2596 			 * to locate the ill.
2597 			 */
2598 			ASSERT(ill != NULL);
2599 			ii->ipsec_in_ill_index =
2600 			    ill->ill_phyint->phyint_ifindex;
2601 			ii->ipsec_in_rill_index =
2602 			    recv_ill->ill_phyint->phyint_ifindex;
2603 			DB_TYPE(first_mp->b_cont) = M_CTL;
2604 		} else {
2605 			/*
2606 			 * IPSEC_IN is not present. We attach a ipsec_in
2607 			 * message and send up to IPsec for validating
2608 			 * and removing the IPsec headers. Clear
2609 			 * ipsec_in_secure so that when we return
2610 			 * from IPsec, we don't mistakenly think that this
2611 			 * is a secure packet came from the network.
2612 			 *
2613 			 * NOTE : ill_index is used by ip_fanout_proto_again
2614 			 * to locate the ill.
2615 			 */
2616 			ASSERT(first_mp == mp);
2617 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2618 			if (first_mp == NULL) {
2619 				freemsg(mp);
2620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2621 				return;
2622 			}
2623 			ii = (ipsec_in_t *)first_mp->b_rptr;
2624 
2625 			/* This is not a secure packet */
2626 			ii->ipsec_in_secure = B_FALSE;
2627 			first_mp->b_cont = mp;
2628 			DB_TYPE(mp) = M_CTL;
2629 			ASSERT(ill != NULL);
2630 			ii->ipsec_in_ill_index =
2631 			    ill->ill_phyint->phyint_ifindex;
2632 			ii->ipsec_in_rill_index =
2633 			    recv_ill->ill_phyint->phyint_ifindex;
2634 		}
2635 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2636 
2637 		if (!ipsec_loaded(ipss)) {
2638 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2639 			return;
2640 		}
2641 
2642 		if (ipha->ipha_protocol == IPPROTO_ESP)
2643 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2644 		else
2645 			ipsec_rc = ipsecah_icmp_error(first_mp);
2646 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2647 			return;
2648 
2649 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2650 		return;
2651 	}
2652 	default:
2653 		/*
2654 		 * The ripha header is only used for the lookup and we
2655 		 * only set the src and dst addresses and protocol.
2656 		 */
2657 		ripha.ipha_src = ipha->ipha_dst;
2658 		ripha.ipha_dst = ipha->ipha_src;
2659 		ripha.ipha_protocol = ipha->ipha_protocol;
2660 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2661 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2662 		    ntohl(ipha->ipha_dst),
2663 		    icmph->icmph_type, icmph->icmph_code));
2664 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2665 			ipha_t *in_ipha;
2666 
2667 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2668 			    mp->b_wptr) {
2669 				if (!pullupmsg(mp, (uchar_t *)ipha +
2670 				    hdr_length + sizeof (ipha_t) -
2671 				    mp->b_rptr)) {
2672 					goto discard_pkt;
2673 				}
2674 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2675 				ipha = (ipha_t *)&icmph[1];
2676 			}
2677 			/*
2678 			 * Caller has verified that length has to be
2679 			 * at least the size of IP header.
2680 			 */
2681 			ASSERT(hdr_length >= sizeof (ipha_t));
2682 			/*
2683 			 * Check the sanity of the inner IP header like
2684 			 * we did for the outer header.
2685 			 */
2686 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2687 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2688 				goto discard_pkt;
2689 			}
2690 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2691 				goto discard_pkt;
2692 			}
2693 			/* Check for Self-encapsulated tunnels */
2694 			if (in_ipha->ipha_src == ipha->ipha_src &&
2695 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2696 
2697 				mp = icmp_inbound_self_encap_error(mp,
2698 				    iph_hdr_length, hdr_length);
2699 				if (mp == NULL)
2700 					goto discard_pkt;
2701 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2702 				ipha = (ipha_t *)&icmph[1];
2703 				hdr_length = IPH_HDR_LENGTH(ipha);
2704 				/*
2705 				 * The packet in error is self-encapsualted.
2706 				 * And we are finding it further encapsulated
2707 				 * which we could not have possibly generated.
2708 				 */
2709 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2710 					goto discard_pkt;
2711 				}
2712 				icmp_inbound_error_fanout(q, ill, first_mp,
2713 				    icmph, ipha, iph_hdr_length, hdr_length,
2714 				    mctl_present, ip_policy, recv_ill, zoneid);
2715 				return;
2716 			}
2717 		}
2718 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2719 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2720 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2721 		    ii != NULL &&
2722 		    ii->ipsec_in_loopback &&
2723 		    ii->ipsec_in_secure) {
2724 			/*
2725 			 * For IP tunnels that get a looped-back
2726 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2727 			 * reported new MTU to take into account the IPsec
2728 			 * headers protecting this configured tunnel.
2729 			 *
2730 			 * This allows the tunnel module (tun.c) to blindly
2731 			 * accept the MTU reported in an ICMP "too big"
2732 			 * message.
2733 			 *
2734 			 * Non-looped back ICMP messages will just be
2735 			 * handled by the security protocols (if needed),
2736 			 * and the first subsequent packet will hit this
2737 			 * path.
2738 			 */
2739 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2740 			    ipsec_in_extra_length(first_mp));
2741 		}
2742 		/* Have to change db_type after any pullupmsg */
2743 		DB_TYPE(mp) = M_CTL;
2744 
2745 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2746 		    ip_policy, recv_ill, zoneid);
2747 		return;
2748 	}
2749 	/* NOTREACHED */
2750 discard_pkt:
2751 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2752 drop_pkt:;
2753 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2754 	freemsg(first_mp);
2755 }
2756 
2757 /*
2758  * Common IP options parser.
2759  *
2760  * Setup routine: fill in *optp with options-parsing state, then
2761  * tail-call ipoptp_next to return the first option.
2762  */
2763 uint8_t
2764 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2765 {
2766 	uint32_t totallen; /* total length of all options */
2767 
2768 	totallen = ipha->ipha_version_and_hdr_length -
2769 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2770 	totallen <<= 2;
2771 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2772 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2773 	optp->ipoptp_flags = 0;
2774 	return (ipoptp_next(optp));
2775 }
2776 
2777 /*
2778  * Common IP options parser: extract next option.
2779  */
2780 uint8_t
2781 ipoptp_next(ipoptp_t *optp)
2782 {
2783 	uint8_t *end = optp->ipoptp_end;
2784 	uint8_t *cur = optp->ipoptp_next;
2785 	uint8_t opt, len, pointer;
2786 
2787 	/*
2788 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2789 	 * has been corrupted.
2790 	 */
2791 	ASSERT(cur <= end);
2792 
2793 	if (cur == end)
2794 		return (IPOPT_EOL);
2795 
2796 	opt = cur[IPOPT_OPTVAL];
2797 
2798 	/*
2799 	 * Skip any NOP options.
2800 	 */
2801 	while (opt == IPOPT_NOP) {
2802 		cur++;
2803 		if (cur == end)
2804 			return (IPOPT_EOL);
2805 		opt = cur[IPOPT_OPTVAL];
2806 	}
2807 
2808 	if (opt == IPOPT_EOL)
2809 		return (IPOPT_EOL);
2810 
2811 	/*
2812 	 * Option requiring a length.
2813 	 */
2814 	if ((cur + 1) >= end) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 	len = cur[IPOPT_OLEN];
2819 	if (len < 2) {
2820 		optp->ipoptp_flags |= IPOPTP_ERROR;
2821 		return (IPOPT_EOL);
2822 	}
2823 	optp->ipoptp_cur = cur;
2824 	optp->ipoptp_len = len;
2825 	optp->ipoptp_next = cur + len;
2826 	if (cur + len > end) {
2827 		optp->ipoptp_flags |= IPOPTP_ERROR;
2828 		return (IPOPT_EOL);
2829 	}
2830 
2831 	/*
2832 	 * For the options which require a pointer field, make sure
2833 	 * its there, and make sure it points to either something
2834 	 * inside this option, or the end of the option.
2835 	 */
2836 	switch (opt) {
2837 	case IPOPT_RR:
2838 	case IPOPT_TS:
2839 	case IPOPT_LSRR:
2840 	case IPOPT_SSRR:
2841 		if (len <= IPOPT_OFFSET) {
2842 			optp->ipoptp_flags |= IPOPTP_ERROR;
2843 			return (opt);
2844 		}
2845 		pointer = cur[IPOPT_OFFSET];
2846 		if (pointer - 1 > len) {
2847 			optp->ipoptp_flags |= IPOPTP_ERROR;
2848 			return (opt);
2849 		}
2850 		break;
2851 	}
2852 
2853 	/*
2854 	 * Sanity check the pointer field based on the type of the
2855 	 * option.
2856 	 */
2857 	switch (opt) {
2858 	case IPOPT_RR:
2859 	case IPOPT_SSRR:
2860 	case IPOPT_LSRR:
2861 		if (pointer < IPOPT_MINOFF_SR)
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		break;
2864 	case IPOPT_TS:
2865 		if (pointer < IPOPT_MINOFF_IT)
2866 			optp->ipoptp_flags |= IPOPTP_ERROR;
2867 		/*
2868 		 * Note that the Internet Timestamp option also
2869 		 * contains two four bit fields (the Overflow field,
2870 		 * and the Flag field), which follow the pointer
2871 		 * field.  We don't need to check that these fields
2872 		 * fall within the length of the option because this
2873 		 * was implicitely done above.  We've checked that the
2874 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2875 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2876 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2877 		 */
2878 		ASSERT(len > IPOPT_POS_OV_FLG);
2879 		break;
2880 	}
2881 
2882 	return (opt);
2883 }
2884 
2885 /*
2886  * Use the outgoing IP header to create an IP_OPTIONS option the way
2887  * it was passed down from the application.
2888  */
2889 int
2890 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2891 {
2892 	ipoptp_t	opts;
2893 	const uchar_t	*opt;
2894 	uint8_t		optval;
2895 	uint8_t		optlen;
2896 	uint32_t	len = 0;
2897 	uchar_t	*buf1 = buf;
2898 
2899 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2900 	len += IP_ADDR_LEN;
2901 	bzero(buf1, IP_ADDR_LEN);
2902 
2903 	/*
2904 	 * OK to cast away const here, as we don't store through the returned
2905 	 * opts.ipoptp_cur pointer.
2906 	 */
2907 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2908 	    optval != IPOPT_EOL;
2909 	    optval = ipoptp_next(&opts)) {
2910 		int	off;
2911 
2912 		opt = opts.ipoptp_cur;
2913 		optlen = opts.ipoptp_len;
2914 		switch (optval) {
2915 		case IPOPT_SSRR:
2916 		case IPOPT_LSRR:
2917 
2918 			/*
2919 			 * Insert ipha_dst as the first entry in the source
2920 			 * route and move down the entries on step.
2921 			 * The last entry gets placed at buf1.
2922 			 */
2923 			buf[IPOPT_OPTVAL] = optval;
2924 			buf[IPOPT_OLEN] = optlen;
2925 			buf[IPOPT_OFFSET] = optlen;
2926 
2927 			off = optlen - IP_ADDR_LEN;
2928 			if (off < 0) {
2929 				/* No entries in source route */
2930 				break;
2931 			}
2932 			/* Last entry in source route */
2933 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2934 			off -= IP_ADDR_LEN;
2935 
2936 			while (off > 0) {
2937 				bcopy(opt + off,
2938 				    buf + off + IP_ADDR_LEN,
2939 				    IP_ADDR_LEN);
2940 				off -= IP_ADDR_LEN;
2941 			}
2942 			/* ipha_dst into first slot */
2943 			bcopy(&ipha->ipha_dst,
2944 			    buf + off + IP_ADDR_LEN,
2945 			    IP_ADDR_LEN);
2946 			buf += optlen;
2947 			len += optlen;
2948 			break;
2949 
2950 		case IPOPT_COMSEC:
2951 		case IPOPT_SECURITY:
2952 			/* if passing up a label is not ok, then remove */
2953 			if (is_system_labeled())
2954 				break;
2955 			/* FALLTHROUGH */
2956 		default:
2957 			bcopy(opt, buf, optlen);
2958 			buf += optlen;
2959 			len += optlen;
2960 			break;
2961 		}
2962 	}
2963 done:
2964 	/* Pad the resulting options */
2965 	while (len & 0x3) {
2966 		*buf++ = IPOPT_EOL;
2967 		len++;
2968 	}
2969 	return (len);
2970 }
2971 
2972 /*
2973  * Update any record route or timestamp options to include this host.
2974  * Reverse any source route option.
2975  * This routine assumes that the options are well formed i.e. that they
2976  * have already been checked.
2977  */
2978 static void
2979 icmp_options_update(ipha_t *ipha)
2980 {
2981 	ipoptp_t	opts;
2982 	uchar_t		*opt;
2983 	uint8_t		optval;
2984 	ipaddr_t	src;		/* Our local address */
2985 	ipaddr_t	dst;
2986 
2987 	ip2dbg(("icmp_options_update\n"));
2988 	src = ipha->ipha_src;
2989 	dst = ipha->ipha_dst;
2990 
2991 	for (optval = ipoptp_first(&opts, ipha);
2992 	    optval != IPOPT_EOL;
2993 	    optval = ipoptp_next(&opts)) {
2994 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2995 		opt = opts.ipoptp_cur;
2996 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2997 		    optval, opts.ipoptp_len));
2998 		switch (optval) {
2999 			int off1, off2;
3000 		case IPOPT_SSRR:
3001 		case IPOPT_LSRR:
3002 			/*
3003 			 * Reverse the source route.  The first entry
3004 			 * should be the next to last one in the current
3005 			 * source route (the last entry is our address).
3006 			 * The last entry should be the final destination.
3007 			 */
3008 			off1 = IPOPT_MINOFF_SR - 1;
3009 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3010 			if (off2 < 0) {
3011 				/* No entries in source route */
3012 				ip1dbg((
3013 				    "icmp_options_update: bad src route\n"));
3014 				break;
3015 			}
3016 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3017 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3018 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3019 			off2 -= IP_ADDR_LEN;
3020 
3021 			while (off1 < off2) {
3022 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3023 				bcopy((char *)opt + off2, (char *)opt + off1,
3024 				    IP_ADDR_LEN);
3025 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3026 				off1 += IP_ADDR_LEN;
3027 				off2 -= IP_ADDR_LEN;
3028 			}
3029 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3030 			break;
3031 		}
3032 	}
3033 }
3034 
3035 /*
3036  * Process received ICMP Redirect messages.
3037  */
3038 static void
3039 icmp_redirect(ill_t *ill, mblk_t *mp)
3040 {
3041 	ipha_t	*ipha;
3042 	int	iph_hdr_length;
3043 	icmph_t	*icmph;
3044 	ipha_t	*ipha_err;
3045 	ire_t	*ire;
3046 	ire_t	*prev_ire;
3047 	ire_t	*save_ire;
3048 	ipaddr_t  src, dst, gateway;
3049 	iulp_t	ulp_info = { 0 };
3050 	int	error;
3051 	ip_stack_t *ipst;
3052 
3053 	ASSERT(ill != NULL);
3054 	ipst = ill->ill_ipst;
3055 
3056 	ipha = (ipha_t *)mp->b_rptr;
3057 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3058 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3059 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3060 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3061 		freemsg(mp);
3062 		return;
3063 	}
3064 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3065 	ipha_err = (ipha_t *)&icmph[1];
3066 	src = ipha->ipha_src;
3067 	dst = ipha_err->ipha_dst;
3068 	gateway = icmph->icmph_rd_gateway;
3069 	/* Make sure the new gateway is reachable somehow. */
3070 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3071 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3072 	/*
3073 	 * Make sure we had a route for the dest in question and that
3074 	 * that route was pointing to the old gateway (the source of the
3075 	 * redirect packet.)
3076 	 */
3077 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3078 	    NULL, MATCH_IRE_GW, ipst);
3079 	/*
3080 	 * Check that
3081 	 *	the redirect was not from ourselves
3082 	 *	the new gateway and the old gateway are directly reachable
3083 	 */
3084 	if (!prev_ire ||
3085 	    !ire ||
3086 	    ire->ire_type == IRE_LOCAL) {
3087 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3088 		freemsg(mp);
3089 		if (ire != NULL)
3090 			ire_refrele(ire);
3091 		if (prev_ire != NULL)
3092 			ire_refrele(prev_ire);
3093 		return;
3094 	}
3095 
3096 	/*
3097 	 * Should we use the old ULP info to create the new gateway?  From
3098 	 * a user's perspective, we should inherit the info so that it
3099 	 * is a "smooth" transition.  If we do not do that, then new
3100 	 * connections going thru the new gateway will have no route metrics,
3101 	 * which is counter-intuitive to user.  From a network point of
3102 	 * view, this may or may not make sense even though the new gateway
3103 	 * is still directly connected to us so the route metrics should not
3104 	 * change much.
3105 	 *
3106 	 * But if the old ire_uinfo is not initialized, we do another
3107 	 * recursive lookup on the dest using the new gateway.  There may
3108 	 * be a route to that.  If so, use it to initialize the redirect
3109 	 * route.
3110 	 */
3111 	if (prev_ire->ire_uinfo.iulp_set) {
3112 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3113 	} else {
3114 		ire_t *tmp_ire;
3115 		ire_t *sire;
3116 
3117 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3118 		    ALL_ZONES, 0, NULL,
3119 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3120 		    ipst);
3121 		if (sire != NULL) {
3122 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3123 			/*
3124 			 * If sire != NULL, ire_ftable_lookup() should not
3125 			 * return a NULL value.
3126 			 */
3127 			ASSERT(tmp_ire != NULL);
3128 			ire_refrele(tmp_ire);
3129 			ire_refrele(sire);
3130 		} else if (tmp_ire != NULL) {
3131 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3132 			    sizeof (iulp_t));
3133 			ire_refrele(tmp_ire);
3134 		}
3135 	}
3136 	if (prev_ire->ire_type == IRE_CACHE)
3137 		ire_delete(prev_ire);
3138 	ire_refrele(prev_ire);
3139 	/*
3140 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3141 	 * require TOS routing
3142 	 */
3143 	switch (icmph->icmph_code) {
3144 	case 0:
3145 	case 1:
3146 		/* TODO: TOS specificity for cases 2 and 3 */
3147 	case 2:
3148 	case 3:
3149 		break;
3150 	default:
3151 		freemsg(mp);
3152 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3153 		ire_refrele(ire);
3154 		return;
3155 	}
3156 	/*
3157 	 * Create a Route Association.  This will allow us to remember that
3158 	 * someone we believe told us to use the particular gateway.
3159 	 */
3160 	save_ire = ire;
3161 	ire = ire_create(
3162 	    (uchar_t *)&dst,			/* dest addr */
3163 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3164 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3165 	    (uchar_t *)&gateway,		/* gateway addr */
3166 	    &save_ire->ire_max_frag,		/* max frag */
3167 	    NULL,				/* no src nce */
3168 	    NULL,				/* no rfq */
3169 	    NULL,				/* no stq */
3170 	    IRE_HOST,
3171 	    NULL,				/* ipif */
3172 	    0,					/* cmask */
3173 	    0,					/* phandle */
3174 	    0,					/* ihandle */
3175 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3176 	    &ulp_info,
3177 	    NULL,				/* tsol_gc_t */
3178 	    NULL,				/* gcgrp */
3179 	    ipst);
3180 
3181 	if (ire == NULL) {
3182 		freemsg(mp);
3183 		ire_refrele(save_ire);
3184 		return;
3185 	}
3186 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3187 	ire_refrele(save_ire);
3188 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3189 
3190 	if (error == 0) {
3191 		ire_refrele(ire);		/* Held in ire_add_v4 */
3192 		/* tell routing sockets that we received a redirect */
3193 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3194 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3195 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3196 	}
3197 
3198 	/*
3199 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3200 	 * This together with the added IRE has the effect of
3201 	 * modifying an existing redirect.
3202 	 */
3203 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3204 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3205 	if (prev_ire != NULL) {
3206 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3207 			ire_delete(prev_ire);
3208 		ire_refrele(prev_ire);
3209 	}
3210 
3211 	freemsg(mp);
3212 }
3213 
3214 /*
3215  * Generate an ICMP parameter problem message.
3216  */
3217 static void
3218 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3219 	ip_stack_t *ipst)
3220 {
3221 	icmph_t	icmph;
3222 	boolean_t mctl_present;
3223 	mblk_t *first_mp;
3224 
3225 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3226 
3227 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3228 		if (mctl_present)
3229 			freeb(first_mp);
3230 		return;
3231 	}
3232 
3233 	bzero(&icmph, sizeof (icmph_t));
3234 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3235 	icmph.icmph_pp_ptr = ptr;
3236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3237 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3238 	    ipst);
3239 }
3240 
3241 /*
3242  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3243  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3244  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3245  * an icmp error packet can be sent.
3246  * Assigns an appropriate source address to the packet. If ipha_dst is
3247  * one of our addresses use it for source. Otherwise pick a source based
3248  * on a route lookup back to ipha_src.
3249  * Note that ipha_src must be set here since the
3250  * packet is likely to arrive on an ill queue in ip_wput() which will
3251  * not set a source address.
3252  */
3253 static void
3254 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3255     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3256 {
3257 	ipaddr_t dst;
3258 	icmph_t	*icmph;
3259 	ipha_t	*ipha;
3260 	uint_t	len_needed;
3261 	size_t	msg_len;
3262 	mblk_t	*mp1;
3263 	ipaddr_t src;
3264 	ire_t	*ire;
3265 	mblk_t *ipsec_mp;
3266 	ipsec_out_t	*io = NULL;
3267 
3268 	if (mctl_present) {
3269 		/*
3270 		 * If it is :
3271 		 *
3272 		 * 1) a IPSEC_OUT, then this is caused by outbound
3273 		 *    datagram originating on this host. IPsec processing
3274 		 *    may or may not have been done. Refer to comments above
3275 		 *    icmp_inbound_error_fanout for details.
3276 		 *
3277 		 * 2) a IPSEC_IN if we are generating a icmp_message
3278 		 *    for an incoming datagram destined for us i.e called
3279 		 *    from ip_fanout_send_icmp.
3280 		 */
3281 		ipsec_info_t *in;
3282 		ipsec_mp = mp;
3283 		mp = ipsec_mp->b_cont;
3284 
3285 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3286 		ipha = (ipha_t *)mp->b_rptr;
3287 
3288 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3289 		    in->ipsec_info_type == IPSEC_IN);
3290 
3291 		if (in->ipsec_info_type == IPSEC_IN) {
3292 			/*
3293 			 * Convert the IPSEC_IN to IPSEC_OUT.
3294 			 */
3295 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3296 				BUMP_MIB(&ipst->ips_ip_mib,
3297 				    ipIfStatsOutDiscards);
3298 				return;
3299 			}
3300 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3301 		} else {
3302 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3303 			io = (ipsec_out_t *)in;
3304 			/*
3305 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3306 			 * ire lookup.
3307 			 */
3308 			io->ipsec_out_proc_begin = B_FALSE;
3309 		}
3310 		ASSERT(zoneid != ALL_ZONES);
3311 		/*
3312 		 * The IPSEC_IN (now an IPSEC_OUT) didn't have its zoneid
3313 		 * initialized.  We need to do that now.
3314 		 */
3315 		io->ipsec_out_zoneid = zoneid;
3316 	} else {
3317 		/*
3318 		 * This is in clear. The icmp message we are building
3319 		 * here should go out in clear.
3320 		 *
3321 		 * Pardon the convolution of it all, but it's easier to
3322 		 * allocate a "use cleartext" IPSEC_IN message and convert
3323 		 * it than it is to allocate a new one.
3324 		 */
3325 		ipsec_in_t *ii;
3326 		ASSERT(DB_TYPE(mp) == M_DATA);
3327 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3328 		if (ipsec_mp == NULL) {
3329 			freemsg(mp);
3330 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3331 			return;
3332 		}
3333 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3334 
3335 		/* This is not a secure packet */
3336 		ii->ipsec_in_secure = B_FALSE;
3337 		/*
3338 		 * For trusted extensions using a shared IP address we can
3339 		 * send using any zoneid.
3340 		 */
3341 		if (zoneid == ALL_ZONES)
3342 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3343 		else
3344 			ii->ipsec_in_zoneid = zoneid;
3345 		ipsec_mp->b_cont = mp;
3346 		ipha = (ipha_t *)mp->b_rptr;
3347 		/*
3348 		 * Convert the IPSEC_IN to IPSEC_OUT.
3349 		 */
3350 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3351 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3352 			return;
3353 		}
3354 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3355 	}
3356 
3357 	/* Remember our eventual destination */
3358 	dst = ipha->ipha_src;
3359 
3360 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3361 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3362 	if (ire != NULL &&
3363 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3364 		src = ipha->ipha_dst;
3365 	} else {
3366 		if (ire != NULL)
3367 			ire_refrele(ire);
3368 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3369 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3370 		    ipst);
3371 		if (ire == NULL) {
3372 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3373 			freemsg(ipsec_mp);
3374 			return;
3375 		}
3376 		src = ire->ire_src_addr;
3377 	}
3378 
3379 	if (ire != NULL)
3380 		ire_refrele(ire);
3381 
3382 	/*
3383 	 * Check if we can send back more then 8 bytes in addition to
3384 	 * the IP header.  We try to send 64 bytes of data and the internal
3385 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3386 	 */
3387 	len_needed = IPH_HDR_LENGTH(ipha);
3388 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3389 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3390 
3391 		if (!pullupmsg(mp, -1)) {
3392 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3393 			freemsg(ipsec_mp);
3394 			return;
3395 		}
3396 		ipha = (ipha_t *)mp->b_rptr;
3397 
3398 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3399 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3400 			    len_needed));
3401 		} else {
3402 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3403 
3404 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3405 			len_needed += ip_hdr_length_v6(mp, ip6h);
3406 		}
3407 	}
3408 	len_needed += ipst->ips_ip_icmp_return;
3409 	msg_len = msgdsize(mp);
3410 	if (msg_len > len_needed) {
3411 		(void) adjmsg(mp, len_needed - msg_len);
3412 		msg_len = len_needed;
3413 	}
3414 	/* Make sure we propagate the cred/label for TX */
3415 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3416 	if (mp1 == NULL) {
3417 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3418 		freemsg(ipsec_mp);
3419 		return;
3420 	}
3421 	mp1->b_cont = mp;
3422 	mp = mp1;
3423 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3424 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3425 	    io->ipsec_out_type == IPSEC_OUT);
3426 	ipsec_mp->b_cont = mp;
3427 
3428 	/*
3429 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3430 	 * node generates be accepted in peace by all on-host destinations.
3431 	 * If we do NOT assume that all on-host destinations trust
3432 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3433 	 * (Look for ipsec_out_icmp_loopback).
3434 	 */
3435 	io->ipsec_out_icmp_loopback = B_TRUE;
3436 
3437 	ipha = (ipha_t *)mp->b_rptr;
3438 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3439 	*ipha = icmp_ipha;
3440 	ipha->ipha_src = src;
3441 	ipha->ipha_dst = dst;
3442 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3443 	msg_len += sizeof (icmp_ipha) + len;
3444 	if (msg_len > IP_MAXPACKET) {
3445 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3446 		msg_len = IP_MAXPACKET;
3447 	}
3448 	ipha->ipha_length = htons((uint16_t)msg_len);
3449 	icmph = (icmph_t *)&ipha[1];
3450 	bcopy(stuff, icmph, len);
3451 	icmph->icmph_checksum = 0;
3452 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3453 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3454 	put(q, ipsec_mp);
3455 }
3456 
3457 /*
3458  * Determine if an ICMP error packet can be sent given the rate limit.
3459  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3460  * in milliseconds) and a burst size. Burst size number of packets can
3461  * be sent arbitrarely closely spaced.
3462  * The state is tracked using two variables to implement an approximate
3463  * token bucket filter:
3464  *	icmp_pkt_err_last - lbolt value when the last burst started
3465  *	icmp_pkt_err_sent - number of packets sent in current burst
3466  */
3467 boolean_t
3468 icmp_err_rate_limit(ip_stack_t *ipst)
3469 {
3470 	clock_t now = TICK_TO_MSEC(lbolt);
3471 	uint_t refilled; /* Number of packets refilled in tbf since last */
3472 	/* Guard against changes by loading into local variable */
3473 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3474 
3475 	if (err_interval == 0)
3476 		return (B_FALSE);
3477 
3478 	if (ipst->ips_icmp_pkt_err_last > now) {
3479 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3480 		ipst->ips_icmp_pkt_err_last = 0;
3481 		ipst->ips_icmp_pkt_err_sent = 0;
3482 	}
3483 	/*
3484 	 * If we are in a burst update the token bucket filter.
3485 	 * Update the "last" time to be close to "now" but make sure
3486 	 * we don't loose precision.
3487 	 */
3488 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3489 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3490 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3491 			ipst->ips_icmp_pkt_err_sent = 0;
3492 		} else {
3493 			ipst->ips_icmp_pkt_err_sent -= refilled;
3494 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3495 		}
3496 	}
3497 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3498 		/* Start of new burst */
3499 		ipst->ips_icmp_pkt_err_last = now;
3500 	}
3501 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3502 		ipst->ips_icmp_pkt_err_sent++;
3503 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3504 		    ipst->ips_icmp_pkt_err_sent));
3505 		return (B_FALSE);
3506 	}
3507 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3508 	return (B_TRUE);
3509 }
3510 
3511 /*
3512  * Check if it is ok to send an IPv4 ICMP error packet in
3513  * response to the IPv4 packet in mp.
3514  * Free the message and return null if no
3515  * ICMP error packet should be sent.
3516  */
3517 static mblk_t *
3518 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3519 {
3520 	icmph_t	*icmph;
3521 	ipha_t	*ipha;
3522 	uint_t	len_needed;
3523 	ire_t	*src_ire;
3524 	ire_t	*dst_ire;
3525 
3526 	if (!mp)
3527 		return (NULL);
3528 	ipha = (ipha_t *)mp->b_rptr;
3529 	if (ip_csum_hdr(ipha)) {
3530 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3531 		freemsg(mp);
3532 		return (NULL);
3533 	}
3534 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3535 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3536 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3537 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3538 	if (src_ire != NULL || dst_ire != NULL ||
3539 	    CLASSD(ipha->ipha_dst) ||
3540 	    CLASSD(ipha->ipha_src) ||
3541 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3542 		/* Note: only errors to the fragment with offset 0 */
3543 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3544 		freemsg(mp);
3545 		if (src_ire != NULL)
3546 			ire_refrele(src_ire);
3547 		if (dst_ire != NULL)
3548 			ire_refrele(dst_ire);
3549 		return (NULL);
3550 	}
3551 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3552 		/*
3553 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3554 		 * errors in response to any ICMP errors.
3555 		 */
3556 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3557 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3558 			if (!pullupmsg(mp, len_needed)) {
3559 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3560 				freemsg(mp);
3561 				return (NULL);
3562 			}
3563 			ipha = (ipha_t *)mp->b_rptr;
3564 		}
3565 		icmph = (icmph_t *)
3566 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3567 		switch (icmph->icmph_type) {
3568 		case ICMP_DEST_UNREACHABLE:
3569 		case ICMP_SOURCE_QUENCH:
3570 		case ICMP_TIME_EXCEEDED:
3571 		case ICMP_PARAM_PROBLEM:
3572 		case ICMP_REDIRECT:
3573 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3574 			freemsg(mp);
3575 			return (NULL);
3576 		default:
3577 			break;
3578 		}
3579 	}
3580 	/*
3581 	 * If this is a labeled system, then check to see if we're allowed to
3582 	 * send a response to this particular sender.  If not, then just drop.
3583 	 */
3584 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3585 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3586 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3587 		freemsg(mp);
3588 		return (NULL);
3589 	}
3590 	if (icmp_err_rate_limit(ipst)) {
3591 		/*
3592 		 * Only send ICMP error packets every so often.
3593 		 * This should be done on a per port/source basis,
3594 		 * but for now this will suffice.
3595 		 */
3596 		freemsg(mp);
3597 		return (NULL);
3598 	}
3599 	return (mp);
3600 }
3601 
3602 /*
3603  * Generate an ICMP redirect message.
3604  */
3605 static void
3606 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3607 {
3608 	icmph_t	icmph;
3609 
3610 	/*
3611 	 * We are called from ip_rput where we could
3612 	 * not have attached an IPSEC_IN.
3613 	 */
3614 	ASSERT(mp->b_datap->db_type == M_DATA);
3615 
3616 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3617 		return;
3618 	}
3619 
3620 	bzero(&icmph, sizeof (icmph_t));
3621 	icmph.icmph_type = ICMP_REDIRECT;
3622 	icmph.icmph_code = 1;
3623 	icmph.icmph_rd_gateway = gateway;
3624 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3625 	/* Redirects sent by router, and router is global zone */
3626 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3627 }
3628 
3629 /*
3630  * Generate an ICMP time exceeded message.
3631  */
3632 void
3633 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3634     ip_stack_t *ipst)
3635 {
3636 	icmph_t	icmph;
3637 	boolean_t mctl_present;
3638 	mblk_t *first_mp;
3639 
3640 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3641 
3642 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3643 		if (mctl_present)
3644 			freeb(first_mp);
3645 		return;
3646 	}
3647 
3648 	bzero(&icmph, sizeof (icmph_t));
3649 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3650 	icmph.icmph_code = code;
3651 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3652 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3653 	    ipst);
3654 }
3655 
3656 /*
3657  * Generate an ICMP unreachable message.
3658  */
3659 void
3660 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3661     ip_stack_t *ipst)
3662 {
3663 	icmph_t	icmph;
3664 	mblk_t *first_mp;
3665 	boolean_t mctl_present;
3666 
3667 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3668 
3669 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3670 		if (mctl_present)
3671 			freeb(first_mp);
3672 		return;
3673 	}
3674 
3675 	bzero(&icmph, sizeof (icmph_t));
3676 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3677 	icmph.icmph_code = code;
3678 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3679 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3680 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3681 	    zoneid, ipst);
3682 }
3683 
3684 /*
3685  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3686  * duplicate.  As long as someone else holds the address, the interface will
3687  * stay down.  When that conflict goes away, the interface is brought back up.
3688  * This is done so that accidental shutdowns of addresses aren't made
3689  * permanent.  Your server will recover from a failure.
3690  *
3691  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3692  * user space process (dhcpagent).
3693  *
3694  * Recovery completes if ARP reports that the address is now ours (via
3695  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3696  *
3697  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3698  */
3699 static void
3700 ipif_dup_recovery(void *arg)
3701 {
3702 	ipif_t *ipif = arg;
3703 	ill_t *ill = ipif->ipif_ill;
3704 	mblk_t *arp_add_mp;
3705 	mblk_t *arp_del_mp;
3706 	ip_stack_t *ipst = ill->ill_ipst;
3707 
3708 	ipif->ipif_recovery_id = 0;
3709 
3710 	/*
3711 	 * No lock needed for moving or condemned check, as this is just an
3712 	 * optimization.
3713 	 */
3714 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3715 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3716 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3717 		/* No reason to try to bring this address back. */
3718 		return;
3719 	}
3720 
3721 	/* ACE_F_UNVERIFIED restarts DAD */
3722 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3723 		goto alloc_fail;
3724 
3725 	if (ipif->ipif_arp_del_mp == NULL) {
3726 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3727 			goto alloc_fail;
3728 		ipif->ipif_arp_del_mp = arp_del_mp;
3729 	}
3730 
3731 	putnext(ill->ill_rq, arp_add_mp);
3732 	return;
3733 
3734 alloc_fail:
3735 	/*
3736 	 * On allocation failure, just restart the timer.  Note that the ipif
3737 	 * is down here, so no other thread could be trying to start a recovery
3738 	 * timer.  The ill_lock protects the condemned flag and the recovery
3739 	 * timer ID.
3740 	 */
3741 	freemsg(arp_add_mp);
3742 	mutex_enter(&ill->ill_lock);
3743 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3744 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3745 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3746 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3747 	}
3748 	mutex_exit(&ill->ill_lock);
3749 }
3750 
3751 /*
3752  * This is for exclusive changes due to ARP.  Either tear down an interface due
3753  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3754  */
3755 /* ARGSUSED */
3756 static void
3757 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3758 {
3759 	ill_t	*ill = rq->q_ptr;
3760 	arh_t *arh;
3761 	ipaddr_t src;
3762 	ipif_t	*ipif;
3763 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3764 	char hbuf[MAC_STR_LEN];
3765 	char sbuf[INET_ADDRSTRLEN];
3766 	const char *failtype;
3767 	boolean_t bring_up;
3768 	ip_stack_t *ipst = ill->ill_ipst;
3769 
3770 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3771 	case AR_CN_READY:
3772 		failtype = NULL;
3773 		bring_up = B_TRUE;
3774 		break;
3775 	case AR_CN_FAILED:
3776 		failtype = "in use";
3777 		bring_up = B_FALSE;
3778 		break;
3779 	default:
3780 		failtype = "claimed";
3781 		bring_up = B_FALSE;
3782 		break;
3783 	}
3784 
3785 	arh = (arh_t *)mp->b_cont->b_rptr;
3786 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3787 
3788 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3789 	    sizeof (hbuf));
3790 	(void) ip_dot_addr(src, sbuf);
3791 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3792 
3793 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3794 		    ipif->ipif_lcl_addr != src) {
3795 			continue;
3796 		}
3797 
3798 		/*
3799 		 * If we failed on a recovery probe, then restart the timer to
3800 		 * try again later.
3801 		 */
3802 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3803 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3804 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3805 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3806 		    ipst->ips_ip_dup_recovery > 0 &&
3807 		    ipif->ipif_recovery_id == 0) {
3808 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3809 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3810 			continue;
3811 		}
3812 
3813 		/*
3814 		 * If what we're trying to do has already been done, then do
3815 		 * nothing.
3816 		 */
3817 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3818 			continue;
3819 
3820 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3821 
3822 		if (failtype == NULL) {
3823 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3824 			    ibuf);
3825 		} else {
3826 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3827 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3828 		}
3829 
3830 		if (bring_up) {
3831 			ASSERT(ill->ill_dl_up);
3832 			/*
3833 			 * Free up the ARP delete message so we can allocate
3834 			 * a fresh one through the normal path.
3835 			 */
3836 			freemsg(ipif->ipif_arp_del_mp);
3837 			ipif->ipif_arp_del_mp = NULL;
3838 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3839 			    EINPROGRESS) {
3840 				ipif->ipif_addr_ready = 1;
3841 				(void) ipif_up_done(ipif);
3842 				ASSERT(ill->ill_move_ipif == NULL);
3843 			}
3844 			continue;
3845 		}
3846 
3847 		mutex_enter(&ill->ill_lock);
3848 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3849 		ipif->ipif_flags |= IPIF_DUPLICATE;
3850 		ill->ill_ipif_dup_count++;
3851 		mutex_exit(&ill->ill_lock);
3852 		/*
3853 		 * Already exclusive on the ill; no need to handle deferred
3854 		 * processing here.
3855 		 */
3856 		(void) ipif_down(ipif, NULL, NULL);
3857 		ipif_down_tail(ipif);
3858 		mutex_enter(&ill->ill_lock);
3859 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3860 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3861 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3862 		    ipst->ips_ip_dup_recovery > 0) {
3863 			ASSERT(ipif->ipif_recovery_id == 0);
3864 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3865 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3866 		}
3867 		mutex_exit(&ill->ill_lock);
3868 	}
3869 	freemsg(mp);
3870 }
3871 
3872 /* ARGSUSED */
3873 static void
3874 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3875 {
3876 	ill_t	*ill = rq->q_ptr;
3877 	arh_t *arh;
3878 	ipaddr_t src;
3879 	ipif_t	*ipif;
3880 
3881 	arh = (arh_t *)mp->b_cont->b_rptr;
3882 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3883 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3884 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3885 			(void) ipif_resolver_up(ipif, Res_act_defend);
3886 	}
3887 	freemsg(mp);
3888 }
3889 
3890 /*
3891  * News from ARP.  ARP sends notification of interesting events down
3892  * to its clients using M_CTL messages with the interesting ARP packet
3893  * attached via b_cont.
3894  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3895  * queue as opposed to ARP sending the message to all the clients, i.e. all
3896  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3897  * table if a cache IRE is found to delete all the entries for the address in
3898  * the packet.
3899  */
3900 static void
3901 ip_arp_news(queue_t *q, mblk_t *mp)
3902 {
3903 	arcn_t		*arcn;
3904 	arh_t		*arh;
3905 	ire_t		*ire = NULL;
3906 	char		hbuf[MAC_STR_LEN];
3907 	char		sbuf[INET_ADDRSTRLEN];
3908 	ipaddr_t	src;
3909 	in6_addr_t	v6src;
3910 	boolean_t	isv6 = B_FALSE;
3911 	ipif_t		*ipif;
3912 	ill_t		*ill;
3913 	ip_stack_t	*ipst;
3914 
3915 	if (CONN_Q(q)) {
3916 		conn_t *connp = Q_TO_CONN(q);
3917 
3918 		ipst = connp->conn_netstack->netstack_ip;
3919 	} else {
3920 		ill_t *ill = (ill_t *)q->q_ptr;
3921 
3922 		ipst = ill->ill_ipst;
3923 	}
3924 
3925 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3926 		if (q->q_next) {
3927 			putnext(q, mp);
3928 		} else
3929 			freemsg(mp);
3930 		return;
3931 	}
3932 	arh = (arh_t *)mp->b_cont->b_rptr;
3933 	/* Is it one we are interested in? */
3934 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3935 		isv6 = B_TRUE;
3936 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3937 		    IPV6_ADDR_LEN);
3938 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3939 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3940 		    IP_ADDR_LEN);
3941 	} else {
3942 		freemsg(mp);
3943 		return;
3944 	}
3945 
3946 	ill = q->q_ptr;
3947 
3948 	arcn = (arcn_t *)mp->b_rptr;
3949 	switch (arcn->arcn_code) {
3950 	case AR_CN_BOGON:
3951 		/*
3952 		 * Someone is sending ARP packets with a source protocol
3953 		 * address that we have published and for which we believe our
3954 		 * entry is authoritative and (when ill_arp_extend is set)
3955 		 * verified to be unique on the network.
3956 		 *
3957 		 * The ARP module internally handles the cases where the sender
3958 		 * is just probing (for DAD) and where the hardware address of
3959 		 * a non-authoritative entry has changed.  Thus, these are the
3960 		 * real conflicts, and we have to do resolution.
3961 		 *
3962 		 * We back away quickly from the address if it's from DHCP or
3963 		 * otherwise temporary and hasn't been used recently (or at
3964 		 * all).  We'd like to include "deprecated" addresses here as
3965 		 * well (as there's no real reason to defend something we're
3966 		 * discarding), but IPMP "reuses" this flag to mean something
3967 		 * other than the standard meaning.
3968 		 *
3969 		 * If the ARP module above is not extended (meaning that it
3970 		 * doesn't know how to defend the address), then we just log
3971 		 * the problem as we always did and continue on.  It's not
3972 		 * right, but there's little else we can do, and those old ATM
3973 		 * users are going away anyway.
3974 		 */
3975 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3976 		    hbuf, sizeof (hbuf));
3977 		(void) ip_dot_addr(src, sbuf);
3978 		if (isv6) {
3979 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3980 			    ipst);
3981 		} else {
3982 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3983 		}
3984 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3985 			uint32_t now;
3986 			uint32_t maxage;
3987 			clock_t lused;
3988 			uint_t maxdefense;
3989 			uint_t defs;
3990 
3991 			/*
3992 			 * First, figure out if this address hasn't been used
3993 			 * in a while.  If it hasn't, then it's a better
3994 			 * candidate for abandoning.
3995 			 */
3996 			ipif = ire->ire_ipif;
3997 			ASSERT(ipif != NULL);
3998 			now = gethrestime_sec();
3999 			maxage = now - ire->ire_create_time;
4000 			if (maxage > ipst->ips_ip_max_temp_idle)
4001 				maxage = ipst->ips_ip_max_temp_idle;
4002 			lused = drv_hztousec(ddi_get_lbolt() -
4003 			    ire->ire_last_used_time) / MICROSEC + 1;
4004 			if (lused >= maxage && (ipif->ipif_flags &
4005 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4006 				maxdefense = ipst->ips_ip_max_temp_defend;
4007 			else
4008 				maxdefense = ipst->ips_ip_max_defend;
4009 
4010 			/*
4011 			 * Now figure out how many times we've defended
4012 			 * ourselves.  Ignore defenses that happened long in
4013 			 * the past.
4014 			 */
4015 			mutex_enter(&ire->ire_lock);
4016 			if ((defs = ire->ire_defense_count) > 0 &&
4017 			    now - ire->ire_defense_time >
4018 			    ipst->ips_ip_defend_interval) {
4019 				ire->ire_defense_count = defs = 0;
4020 			}
4021 			ire->ire_defense_count++;
4022 			ire->ire_defense_time = now;
4023 			mutex_exit(&ire->ire_lock);
4024 			ill_refhold(ill);
4025 			ire_refrele(ire);
4026 
4027 			/*
4028 			 * If we've defended ourselves too many times already,
4029 			 * then give up and tear down the interface(s) using
4030 			 * this address.  Otherwise, defend by sending out a
4031 			 * gratuitous ARP.
4032 			 */
4033 			if (defs >= maxdefense && ill->ill_arp_extend) {
4034 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4035 				    B_FALSE);
4036 			} else {
4037 				cmn_err(CE_WARN,
4038 				    "node %s is using our IP address %s on %s",
4039 				    hbuf, sbuf, ill->ill_name);
4040 				/*
4041 				 * If this is an old (ATM) ARP module, then
4042 				 * don't try to defend the address.  Remain
4043 				 * compatible with the old behavior.  Defend
4044 				 * only with new ARP.
4045 				 */
4046 				if (ill->ill_arp_extend) {
4047 					qwriter_ip(ill, q, mp, ip_arp_defend,
4048 					    NEW_OP, B_FALSE);
4049 				} else {
4050 					ill_refrele(ill);
4051 				}
4052 			}
4053 			return;
4054 		}
4055 		cmn_err(CE_WARN,
4056 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4057 		    hbuf, sbuf, ill->ill_name);
4058 		if (ire != NULL)
4059 			ire_refrele(ire);
4060 		break;
4061 	case AR_CN_ANNOUNCE:
4062 		if (isv6) {
4063 			/*
4064 			 * For XRESOLV interfaces.
4065 			 * Delete the IRE cache entry and NCE for this
4066 			 * v6 address
4067 			 */
4068 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4069 			/*
4070 			 * If v6src is a non-zero, it's a router address
4071 			 * as below. Do the same sort of thing to clean
4072 			 * out off-net IRE_CACHE entries that go through
4073 			 * the router.
4074 			 */
4075 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4076 				ire_walk_v6(ire_delete_cache_gw_v6,
4077 				    (char *)&v6src, ALL_ZONES, ipst);
4078 			}
4079 		} else {
4080 			nce_hw_map_t hwm;
4081 
4082 			/*
4083 			 * ARP gives us a copy of any packet where it thinks
4084 			 * the address has changed, so that we can update our
4085 			 * caches.  We're responsible for caching known answers
4086 			 * in the current design.  We check whether the
4087 			 * hardware address really has changed in all of our
4088 			 * entries that have cached this mapping, and if so, we
4089 			 * blow them away.  This way we will immediately pick
4090 			 * up the rare case of a host changing hardware
4091 			 * address.
4092 			 */
4093 			if (src == 0)
4094 				break;
4095 			hwm.hwm_addr = src;
4096 			hwm.hwm_hwlen = arh->arh_hlen;
4097 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4098 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4099 			ndp_walk_common(ipst->ips_ndp4, NULL,
4100 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4101 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4102 		}
4103 		break;
4104 	case AR_CN_READY:
4105 		/* No external v6 resolver has a contract to use this */
4106 		if (isv6)
4107 			break;
4108 		/* If the link is down, we'll retry this later */
4109 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4110 			break;
4111 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4112 		    NULL, NULL, ipst);
4113 		if (ipif != NULL) {
4114 			/*
4115 			 * If this is a duplicate recovery, then we now need to
4116 			 * go exclusive to bring this thing back up.
4117 			 */
4118 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4119 			    IPIF_DUPLICATE) {
4120 				ipif_refrele(ipif);
4121 				ill_refhold(ill);
4122 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4123 				    B_FALSE);
4124 				return;
4125 			}
4126 			/*
4127 			 * If this is the first notice that this address is
4128 			 * ready, then let the user know now.
4129 			 */
4130 			if ((ipif->ipif_flags & IPIF_UP) &&
4131 			    !ipif->ipif_addr_ready) {
4132 				ipif_mask_reply(ipif);
4133 				ipif_up_notify(ipif);
4134 			}
4135 			ipif->ipif_addr_ready = 1;
4136 			ipif_refrele(ipif);
4137 		}
4138 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4139 		if (ire != NULL) {
4140 			ire->ire_defense_count = 0;
4141 			ire_refrele(ire);
4142 		}
4143 		break;
4144 	case AR_CN_FAILED:
4145 		/* No external v6 resolver has a contract to use this */
4146 		if (isv6)
4147 			break;
4148 		if (!ill->ill_arp_extend) {
4149 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4150 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4151 			(void) ip_dot_addr(src, sbuf);
4152 
4153 			cmn_err(CE_WARN,
4154 			    "node %s is using our IP address %s on %s",
4155 			    hbuf, sbuf, ill->ill_name);
4156 			break;
4157 		}
4158 		ill_refhold(ill);
4159 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4160 		return;
4161 	}
4162 	freemsg(mp);
4163 }
4164 
4165 /*
4166  * Create a mblk suitable for carrying the interface index and/or source link
4167  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4168  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4169  * application.
4170  */
4171 mblk_t *
4172 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4173     ip_stack_t *ipst)
4174 {
4175 	mblk_t		*mp;
4176 	ip_pktinfo_t	*pinfo;
4177 	ipha_t 		*ipha;
4178 	struct ether_header *pether;
4179 	boolean_t	ipmp_ill_held = B_FALSE;
4180 
4181 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4182 	if (mp == NULL) {
4183 		ip1dbg(("ip_add_info: allocation failure.\n"));
4184 		return (data_mp);
4185 	}
4186 
4187 	ipha = (ipha_t *)data_mp->b_rptr;
4188 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4189 	bzero(pinfo, sizeof (ip_pktinfo_t));
4190 	pinfo->ip_pkt_flags = (uchar_t)flags;
4191 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4192 
4193 	pether = (struct ether_header *)((char *)ipha
4194 	    - sizeof (struct ether_header));
4195 
4196 	/*
4197 	 * Make sure the interface is an ethernet type, since this option
4198 	 * is currently supported only on this type of interface. Also make
4199 	 * sure we are pointing correctly above db_base.
4200 	 */
4201 	if ((flags & IPF_RECVSLLA) &&
4202 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4203 	    (ill->ill_type == IFT_ETHER) &&
4204 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4205 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4206 		bcopy(pether->ether_shost.ether_addr_octet,
4207 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4208 	} else {
4209 		/*
4210 		 * Clear the bit. Indicate to upper layer that IP is not
4211 		 * sending this ancillary info.
4212 		 */
4213 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4214 	}
4215 
4216 	/*
4217 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4218 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4219 	 * IPF_RECVADDR support on test addresses is not needed.)
4220 	 *
4221 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4222 	 * processing a packet looped back to an IPMP data address
4223 	 * (since those IRE_LOCALs are tied to IPMP ills).
4224 	 */
4225 	if (IS_UNDER_IPMP(ill)) {
4226 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4227 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4228 			freemsg(mp);
4229 			return (data_mp);
4230 		}
4231 		ipmp_ill_held = B_TRUE;
4232 	}
4233 
4234 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4235 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4236 	if (flags & IPF_RECVADDR) {
4237 		ipif_t	*ipif;
4238 		ire_t	*ire;
4239 
4240 		/*
4241 		 * Only valid for V4
4242 		 */
4243 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4244 		    (IPV4_VERSION << 4));
4245 
4246 		ipif = ipif_get_next_ipif(NULL, ill);
4247 		if (ipif != NULL) {
4248 			/*
4249 			 * Since a decision has already been made to deliver the
4250 			 * packet, there is no need to test for SECATTR and
4251 			 * ZONEONLY.
4252 			 * When a multicast packet is transmitted
4253 			 * a cache entry is created for the multicast address.
4254 			 * When delivering a copy of the packet or when new
4255 			 * packets are received we do not want to match on the
4256 			 * cached entry so explicitly match on
4257 			 * IRE_LOCAL and IRE_LOOPBACK
4258 			 */
4259 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4260 			    IRE_LOCAL | IRE_LOOPBACK,
4261 			    ipif, zoneid, NULL,
4262 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4263 			if (ire == NULL) {
4264 				/*
4265 				 * packet must have come on a different
4266 				 * interface.
4267 				 * Since a decision has already been made to
4268 				 * deliver the packet, there is no need to test
4269 				 * for SECATTR and ZONEONLY.
4270 				 * Only match on local and broadcast ire's.
4271 				 * See detailed comment above.
4272 				 */
4273 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4274 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4275 				    NULL, MATCH_IRE_TYPE, ipst);
4276 			}
4277 
4278 			if (ire == NULL) {
4279 				/*
4280 				 * This is either a multicast packet or
4281 				 * the address has been removed since
4282 				 * the packet was received.
4283 				 * Return INADDR_ANY so that normal source
4284 				 * selection occurs for the response.
4285 				 */
4286 
4287 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4288 			} else {
4289 				pinfo->ip_pkt_match_addr.s_addr =
4290 				    ire->ire_src_addr;
4291 				ire_refrele(ire);
4292 			}
4293 			ipif_refrele(ipif);
4294 		} else {
4295 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4296 		}
4297 	}
4298 
4299 	if (ipmp_ill_held)
4300 		ill_refrele(ill);
4301 
4302 	mp->b_datap->db_type = M_CTL;
4303 	mp->b_wptr += sizeof (ip_pktinfo_t);
4304 	mp->b_cont = data_mp;
4305 
4306 	return (mp);
4307 }
4308 
4309 /*
4310  * Used to determine the most accurate cred_t to use for TX.
4311  * First priority is SCM_UCRED having set the label in the message,
4312  * which is used for MLP on UDP. Second priority is the open credentials
4313  * with the peer's label (aka conn_effective_cred), which is needed for
4314  * MLP on TCP/SCTP and for MAC-Exempt. Last priority is the open credentials.
4315  */
4316 cred_t *
4317 ip_best_cred(mblk_t *mp, conn_t *connp, pid_t *pidp)
4318 {
4319 	cred_t *cr;
4320 
4321 	cr = msg_getcred(mp, pidp);
4322 	if (cr != NULL && crgetlabel(cr) != NULL)
4323 		return (cr);
4324 	*pidp = NOPID;
4325 	return (CONN_CRED(connp));
4326 }
4327 
4328 /*
4329  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4330  * part of the bind request.
4331  */
4332 
4333 boolean_t
4334 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4335 {
4336 	ipsec_in_t *ii;
4337 
4338 	ASSERT(policy_mp != NULL);
4339 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4340 
4341 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4342 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4343 
4344 	connp->conn_policy = ii->ipsec_in_policy;
4345 	ii->ipsec_in_policy = NULL;
4346 
4347 	if (ii->ipsec_in_action != NULL) {
4348 		if (connp->conn_latch == NULL) {
4349 			connp->conn_latch = iplatch_create();
4350 			if (connp->conn_latch == NULL)
4351 				return (B_FALSE);
4352 		}
4353 		ipsec_latch_inbound(connp->conn_latch, ii);
4354 	}
4355 	return (B_TRUE);
4356 }
4357 
4358 static void
4359 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4360 {
4361 	/*
4362 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4363 	 * We can't do this in ip_bind_get_ire because the policy
4364 	 * may not have been inherited at that point in time and hence
4365 	 * conn_out_enforce_policy may not be set.
4366 	 */
4367 	if (ire_requested && connp->conn_out_enforce_policy &&
4368 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4369 		ire_t *ire = (ire_t *)mp->b_rptr;
4370 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4371 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4372 	}
4373 }
4374 
4375 /*
4376  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4377  * and to arrange for power-fanout assist.  The ULP is identified by
4378  * adding a single byte at the end of the original bind message.
4379  * A ULP other than UDP or TCP that wishes to be recognized passes
4380  * down a bind with a zero length address.
4381  *
4382  * The binding works as follows:
4383  * - A zero byte address means just bind to the protocol.
4384  * - A four byte address is treated as a request to validate
4385  *   that the address is a valid local address, appropriate for
4386  *   an application to bind to. This does not affect any fanout
4387  *   information in IP.
4388  * - A sizeof sin_t byte address is used to bind to only the local address
4389  *   and port.
4390  * - A sizeof ipa_conn_t byte address contains complete fanout information
4391  *   consisting of local and remote addresses and ports.  In
4392  *   this case, the addresses are both validated as appropriate
4393  *   for this operation, and, if so, the information is retained
4394  *   for use in the inbound fanout.
4395  *
4396  * The ULP (except in the zero-length bind) can append an
4397  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4398  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4399  * a copy of the source or destination IRE (source for local bind;
4400  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4401  * policy information contained should be copied on to the conn.
4402  *
4403  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4404  */
4405 mblk_t *
4406 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4407 {
4408 	ssize_t		len;
4409 	struct T_bind_req	*tbr;
4410 	sin_t		*sin;
4411 	ipa_conn_t	*ac;
4412 	uchar_t		*ucp;
4413 	mblk_t		*mp1;
4414 	boolean_t	ire_requested;
4415 	int		error = 0;
4416 	int		protocol;
4417 	ipa_conn_x_t	*acx;
4418 	cred_t		*cr;
4419 
4420 	/*
4421 	 * All Solaris components should pass a db_credp
4422 	 * for this TPI message, hence we ASSERT.
4423 	 * But in case there is some other M_PROTO that looks
4424 	 * like a TPI message sent by some other kernel
4425 	 * component, we check and return an error.
4426 	 */
4427 	cr = msg_getcred(mp, NULL);
4428 	ASSERT(cr != NULL);
4429 	if (cr == NULL) {
4430 		error = EINVAL;
4431 		goto bad_addr;
4432 	}
4433 
4434 	ASSERT(!connp->conn_af_isv6);
4435 	connp->conn_pkt_isv6 = B_FALSE;
4436 
4437 	len = MBLKL(mp);
4438 	if (len < (sizeof (*tbr) + 1)) {
4439 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4440 		    "ip_bind: bogus msg, len %ld", len);
4441 		/* XXX: Need to return something better */
4442 		goto bad_addr;
4443 	}
4444 	/* Back up and extract the protocol identifier. */
4445 	mp->b_wptr--;
4446 	protocol = *mp->b_wptr & 0xFF;
4447 	tbr = (struct T_bind_req *)mp->b_rptr;
4448 	/* Reset the message type in preparation for shipping it back. */
4449 	DB_TYPE(mp) = M_PCPROTO;
4450 
4451 	connp->conn_ulp = (uint8_t)protocol;
4452 
4453 	/*
4454 	 * Check for a zero length address.  This is from a protocol that
4455 	 * wants to register to receive all packets of its type.
4456 	 */
4457 	if (tbr->ADDR_length == 0) {
4458 		/*
4459 		 * These protocols are now intercepted in ip_bind_v6().
4460 		 * Reject protocol-level binds here for now.
4461 		 *
4462 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4463 		 * so that the protocol type cannot be SCTP.
4464 		 */
4465 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4466 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4467 			goto bad_addr;
4468 		}
4469 
4470 		/*
4471 		 *
4472 		 * The udp module never sends down a zero-length address,
4473 		 * and allowing this on a labeled system will break MLP
4474 		 * functionality.
4475 		 */
4476 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4477 			goto bad_addr;
4478 
4479 		if (connp->conn_mac_exempt)
4480 			goto bad_addr;
4481 
4482 		/* No hash here really.  The table is big enough. */
4483 		connp->conn_srcv6 = ipv6_all_zeros;
4484 
4485 		ipcl_proto_insert(connp, protocol);
4486 
4487 		tbr->PRIM_type = T_BIND_ACK;
4488 		return (mp);
4489 	}
4490 
4491 	/* Extract the address pointer from the message. */
4492 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4493 	    tbr->ADDR_length);
4494 	if (ucp == NULL) {
4495 		ip1dbg(("ip_bind: no address\n"));
4496 		goto bad_addr;
4497 	}
4498 	if (!OK_32PTR(ucp)) {
4499 		ip1dbg(("ip_bind: unaligned address\n"));
4500 		goto bad_addr;
4501 	}
4502 	/*
4503 	 * Check for trailing mps.
4504 	 */
4505 
4506 	mp1 = mp->b_cont;
4507 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4508 
4509 	switch (tbr->ADDR_length) {
4510 	default:
4511 		ip1dbg(("ip_bind: bad address length %d\n",
4512 		    (int)tbr->ADDR_length));
4513 		goto bad_addr;
4514 
4515 	case IP_ADDR_LEN:
4516 		/* Verification of local address only */
4517 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4518 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4519 		break;
4520 
4521 	case sizeof (sin_t):
4522 		sin = (sin_t *)ucp;
4523 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4524 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4525 		break;
4526 
4527 	case sizeof (ipa_conn_t):
4528 		ac = (ipa_conn_t *)ucp;
4529 		/* For raw socket, the local port is not set. */
4530 		if (ac->ac_lport == 0)
4531 			ac->ac_lport = connp->conn_lport;
4532 		/* Always verify destination reachability. */
4533 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4534 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4535 		    B_TRUE, B_TRUE, cr);
4536 		break;
4537 
4538 	case sizeof (ipa_conn_x_t):
4539 		acx = (ipa_conn_x_t *)ucp;
4540 		/*
4541 		 * Whether or not to verify destination reachability depends
4542 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4543 		 */
4544 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4545 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4546 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4547 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4548 		break;
4549 	}
4550 	ASSERT(error != EINPROGRESS);
4551 	if (error != 0)
4552 		goto bad_addr;
4553 
4554 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4555 
4556 	/* Send it home. */
4557 	mp->b_datap->db_type = M_PCPROTO;
4558 	tbr->PRIM_type = T_BIND_ACK;
4559 	return (mp);
4560 
4561 bad_addr:
4562 	/*
4563 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4564 	 * a unix errno.
4565 	 */
4566 	if (error > 0)
4567 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4568 	else
4569 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4570 	return (mp);
4571 }
4572 
4573 /*
4574  * Here address is verified to be a valid local address.
4575  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4576  * address is also considered a valid local address.
4577  * In the case of a broadcast/multicast address, however, the
4578  * upper protocol is expected to reset the src address
4579  * to 0 if it sees a IRE_BROADCAST type returned so that
4580  * no packets are emitted with broadcast/multicast address as
4581  * source address (that violates hosts requirements RFC 1122)
4582  * The addresses valid for bind are:
4583  *	(1) - INADDR_ANY (0)
4584  *	(2) - IP address of an UP interface
4585  *	(3) - IP address of a DOWN interface
4586  *	(4) - valid local IP broadcast addresses. In this case
4587  *	the conn will only receive packets destined to
4588  *	the specified broadcast address.
4589  *	(5) - a multicast address. In this case
4590  *	the conn will only receive packets destined to
4591  *	the specified multicast address. Note: the
4592  *	application still has to issue an
4593  *	IP_ADD_MEMBERSHIP socket option.
4594  *
4595  * On error, return -1 for TBADADDR otherwise pass the
4596  * errno with TSYSERR reply.
4597  *
4598  * In all the above cases, the bound address must be valid in the current zone.
4599  * When the address is loopback, multicast or broadcast, there might be many
4600  * matching IREs so bind has to look up based on the zone.
4601  *
4602  * Note: lport is in network byte order.
4603  *
4604  */
4605 int
4606 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4607     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4608 {
4609 	int		error = 0;
4610 	ire_t		*src_ire;
4611 	zoneid_t	zoneid;
4612 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4613 	mblk_t		*mp = NULL;
4614 	boolean_t	ire_requested = B_FALSE;
4615 	boolean_t	ipsec_policy_set = B_FALSE;
4616 
4617 	if (mpp)
4618 		mp = *mpp;
4619 
4620 	if (mp != NULL) {
4621 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4622 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4623 	}
4624 
4625 	/*
4626 	 * If it was previously connected, conn_fully_bound would have
4627 	 * been set.
4628 	 */
4629 	connp->conn_fully_bound = B_FALSE;
4630 
4631 	src_ire = NULL;
4632 
4633 	zoneid = IPCL_ZONEID(connp);
4634 
4635 	if (src_addr) {
4636 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4637 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4638 		/*
4639 		 * If an address other than 0.0.0.0 is requested,
4640 		 * we verify that it is a valid address for bind
4641 		 * Note: Following code is in if-else-if form for
4642 		 * readability compared to a condition check.
4643 		 */
4644 		/* LINTED - statement has no consequence */
4645 		if (IRE_IS_LOCAL(src_ire)) {
4646 			/*
4647 			 * (2) Bind to address of local UP interface
4648 			 */
4649 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4650 			/*
4651 			 * (4) Bind to broadcast address
4652 			 * Note: permitted only from transports that
4653 			 * request IRE
4654 			 */
4655 			if (!ire_requested)
4656 				error = EADDRNOTAVAIL;
4657 		} else {
4658 			/*
4659 			 * (3) Bind to address of local DOWN interface
4660 			 * (ipif_lookup_addr() looks up all interfaces
4661 			 * but we do not get here for UP interfaces
4662 			 * - case (2) above)
4663 			 */
4664 			/* LINTED - statement has no consequent */
4665 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4666 				/* The address exists */
4667 			} else if (CLASSD(src_addr)) {
4668 				error = 0;
4669 				if (src_ire != NULL)
4670 					ire_refrele(src_ire);
4671 				/*
4672 				 * (5) bind to multicast address.
4673 				 * Fake out the IRE returned to upper
4674 				 * layer to be a broadcast IRE.
4675 				 */
4676 				src_ire = ire_ctable_lookup(
4677 				    INADDR_BROADCAST, INADDR_ANY,
4678 				    IRE_BROADCAST, NULL, zoneid, NULL,
4679 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4680 				    ipst);
4681 				if (src_ire == NULL || !ire_requested)
4682 					error = EADDRNOTAVAIL;
4683 			} else {
4684 				/*
4685 				 * Not a valid address for bind
4686 				 */
4687 				error = EADDRNOTAVAIL;
4688 			}
4689 		}
4690 		if (error) {
4691 			/* Red Alert!  Attempting to be a bogon! */
4692 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4693 			    ntohl(src_addr)));
4694 			goto bad_addr;
4695 		}
4696 	}
4697 
4698 	/*
4699 	 * Allow setting new policies. For example, disconnects come
4700 	 * down as ipa_t bind. As we would have set conn_policy_cached
4701 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4702 	 * can change after the disconnect.
4703 	 */
4704 	connp->conn_policy_cached = B_FALSE;
4705 
4706 	/*
4707 	 * If not fanout_insert this was just an address verification
4708 	 */
4709 	if (fanout_insert) {
4710 		/*
4711 		 * The addresses have been verified. Time to insert in
4712 		 * the correct fanout list.
4713 		 */
4714 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4715 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4716 		connp->conn_lport = lport;
4717 		connp->conn_fport = 0;
4718 		/*
4719 		 * Do we need to add a check to reject Multicast packets
4720 		 */
4721 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4722 	}
4723 
4724 	if (error == 0) {
4725 		if (ire_requested) {
4726 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4727 				error = -1;
4728 				/* Falls through to bad_addr */
4729 			}
4730 		} else if (ipsec_policy_set) {
4731 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4732 				error = -1;
4733 				/* Falls through to bad_addr */
4734 			}
4735 		}
4736 	}
4737 bad_addr:
4738 	if (error != 0) {
4739 		if (connp->conn_anon_port) {
4740 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4741 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4742 			    B_FALSE);
4743 		}
4744 		connp->conn_mlp_type = mlptSingle;
4745 	}
4746 	if (src_ire != NULL)
4747 		IRE_REFRELE(src_ire);
4748 	return (error);
4749 }
4750 
4751 int
4752 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4753     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4754 {
4755 	int error;
4756 	mblk_t	*mp = NULL;
4757 	boolean_t ire_requested;
4758 
4759 	if (ire_mpp)
4760 		mp = *ire_mpp;
4761 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4762 
4763 	ASSERT(!connp->conn_af_isv6);
4764 	connp->conn_pkt_isv6 = B_FALSE;
4765 	connp->conn_ulp = protocol;
4766 
4767 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4768 	    fanout_insert);
4769 	if (error == 0) {
4770 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4771 		    ire_requested);
4772 	} else if (error < 0) {
4773 		error = -TBADADDR;
4774 	}
4775 	return (error);
4776 }
4777 
4778 /*
4779  * Verify that both the source and destination addresses
4780  * are valid.  If verify_dst is false, then the destination address may be
4781  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4782  * destination reachability, while tunnels do not.
4783  * Note that we allow connect to broadcast and multicast
4784  * addresses when ire_requested is set. Thus the ULP
4785  * has to check for IRE_BROADCAST and multicast.
4786  *
4787  * Returns zero if ok.
4788  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4789  * (for use with TSYSERR reply).
4790  *
4791  * Note: lport and fport are in network byte order.
4792  */
4793 int
4794 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4795     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4796     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4797 {
4798 
4799 	ire_t		*src_ire;
4800 	ire_t		*dst_ire;
4801 	int		error = 0;
4802 	ire_t		*sire = NULL;
4803 	ire_t		*md_dst_ire = NULL;
4804 	ire_t		*lso_dst_ire = NULL;
4805 	ill_t		*ill = NULL;
4806 	zoneid_t	zoneid;
4807 	ipaddr_t	src_addr = *src_addrp;
4808 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4809 	mblk_t		*mp = NULL;
4810 	boolean_t	ire_requested = B_FALSE;
4811 	boolean_t	ipsec_policy_set = B_FALSE;
4812 	ts_label_t	*tsl = NULL;
4813 	cred_t		*effective_cred = NULL;
4814 
4815 	if (mpp)
4816 		mp = *mpp;
4817 
4818 	if (mp != NULL) {
4819 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4820 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4821 	}
4822 
4823 	src_ire = dst_ire = NULL;
4824 
4825 	/*
4826 	 * If we never got a disconnect before, clear it now.
4827 	 */
4828 	connp->conn_fully_bound = B_FALSE;
4829 
4830 	zoneid = IPCL_ZONEID(connp);
4831 
4832 	/*
4833 	 * Check whether Trusted Solaris policy allows communication with this
4834 	 * host, and pretend that the destination is unreachable if not.
4835 	 *
4836 	 * This is never a problem for TCP, since that transport is known to
4837 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4838 	 * handling.  If the remote is unreachable, it will be detected at that
4839 	 * point, so there's no reason to check it here.
4840 	 *
4841 	 * Note that for sendto (and other datagram-oriented friends), this
4842 	 * check is done as part of the data path label computation instead.
4843 	 * The check here is just to make non-TCP connect() report the right
4844 	 * error.
4845 	 */
4846 	if (is_system_labeled() && !IPCL_IS_TCP(connp)) {
4847 		if ((error = tsol_check_dest(cr, &dst_addr, IPV4_VERSION,
4848 		    connp->conn_mac_exempt, &effective_cred)) != 0) {
4849 			if (ip_debug > 2) {
4850 				pr_addr_dbg(
4851 				    "ip_bind_connected_v4:"
4852 				    " no label for dst %s\n",
4853 				    AF_INET, &dst_addr);
4854 			}
4855 			goto bad_addr;
4856 		}
4857 
4858 		/*
4859 		 * tsol_check_dest() may have created a new cred with
4860 		 * a modified security label. Use that cred if it exists
4861 		 * for ire lookups.
4862 		 */
4863 		if (effective_cred == NULL) {
4864 			tsl = crgetlabel(cr);
4865 		} else {
4866 			tsl = crgetlabel(effective_cred);
4867 		}
4868 	}
4869 
4870 	if (CLASSD(dst_addr)) {
4871 		/* Pick up an IRE_BROADCAST */
4872 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4873 		    NULL, zoneid, tsl,
4874 		    (MATCH_IRE_RECURSIVE |
4875 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4876 		    MATCH_IRE_SECATTR), ipst);
4877 	} else {
4878 		/*
4879 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4880 		 * and onlink ipif is not found set ENETUNREACH error.
4881 		 */
4882 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4883 			ipif_t *ipif;
4884 
4885 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4886 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4887 			if (ipif == NULL) {
4888 				error = ENETUNREACH;
4889 				goto bad_addr;
4890 			}
4891 			ipif_refrele(ipif);
4892 		}
4893 
4894 		if (connp->conn_nexthop_set) {
4895 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4896 			    0, 0, NULL, NULL, zoneid, tsl,
4897 			    MATCH_IRE_SECATTR, ipst);
4898 		} else {
4899 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4900 			    &sire, zoneid, tsl,
4901 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4902 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4903 			    MATCH_IRE_SECATTR), ipst);
4904 		}
4905 	}
4906 	/*
4907 	 * dst_ire can't be a broadcast when not ire_requested.
4908 	 * We also prevent ire's with src address INADDR_ANY to
4909 	 * be used, which are created temporarily for
4910 	 * sending out packets from endpoints that have
4911 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4912 	 * reachable.  If verify_dst is false, the destination needn't be
4913 	 * reachable.
4914 	 *
4915 	 * If we match on a reject or black hole, then we've got a
4916 	 * local failure.  May as well fail out the connect() attempt,
4917 	 * since it's never going to succeed.
4918 	 */
4919 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4920 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4921 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4922 		/*
4923 		 * If we're verifying destination reachability, we always want
4924 		 * to complain here.
4925 		 *
4926 		 * If we're not verifying destination reachability but the
4927 		 * destination has a route, we still want to fail on the
4928 		 * temporary address and broadcast address tests.
4929 		 */
4930 		if (verify_dst || (dst_ire != NULL)) {
4931 			if (ip_debug > 2) {
4932 				pr_addr_dbg("ip_bind_connected_v4:"
4933 				    "bad connected dst %s\n",
4934 				    AF_INET, &dst_addr);
4935 			}
4936 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4937 				error = ENETUNREACH;
4938 			else
4939 				error = EHOSTUNREACH;
4940 			goto bad_addr;
4941 		}
4942 	}
4943 
4944 	/*
4945 	 * If the app does a connect(), it means that it will most likely
4946 	 * send more than 1 packet to the destination.  It makes sense
4947 	 * to clear the temporary flag.
4948 	 */
4949 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4950 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4951 		irb_t *irb = dst_ire->ire_bucket;
4952 
4953 		rw_enter(&irb->irb_lock, RW_WRITER);
4954 		/*
4955 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4956 		 * the lock to guarantee irb_tmp_ire_cnt.
4957 		 */
4958 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4959 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4960 			irb->irb_tmp_ire_cnt--;
4961 		}
4962 		rw_exit(&irb->irb_lock);
4963 	}
4964 
4965 	/*
4966 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4967 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4968 	 * eligibility tests for passive connects are handled separately
4969 	 * through tcp_adapt_ire().  We do this before the source address
4970 	 * selection, because dst_ire may change after a call to
4971 	 * ipif_select_source().  This is a best-effort check, as the
4972 	 * packet for this connection may not actually go through
4973 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4974 	 * calling ip_newroute().  This is why we further check on the
4975 	 * IRE during LSO/Multidata packet transmission in
4976 	 * tcp_lsosend()/tcp_multisend().
4977 	 */
4978 	if (!ipsec_policy_set && dst_ire != NULL &&
4979 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4980 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4981 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4982 			lso_dst_ire = dst_ire;
4983 			IRE_REFHOLD(lso_dst_ire);
4984 		} else if (ipst->ips_ip_multidata_outbound &&
4985 		    ILL_MDT_CAPABLE(ill)) {
4986 			md_dst_ire = dst_ire;
4987 			IRE_REFHOLD(md_dst_ire);
4988 		}
4989 	}
4990 
4991 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4992 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4993 		/*
4994 		 * If the IRE belongs to a different zone, look for a matching
4995 		 * route in the forwarding table and use the source address from
4996 		 * that route.
4997 		 */
4998 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4999 		    zoneid, 0, NULL,
5000 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
5001 		    MATCH_IRE_RJ_BHOLE, ipst);
5002 		if (src_ire == NULL) {
5003 			error = EHOSTUNREACH;
5004 			goto bad_addr;
5005 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5006 			if (!(src_ire->ire_type & IRE_HOST))
5007 				error = ENETUNREACH;
5008 			else
5009 				error = EHOSTUNREACH;
5010 			goto bad_addr;
5011 		}
5012 		if (src_addr == INADDR_ANY)
5013 			src_addr = src_ire->ire_src_addr;
5014 		ire_refrele(src_ire);
5015 		src_ire = NULL;
5016 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5017 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5018 			src_addr = sire->ire_src_addr;
5019 			ire_refrele(dst_ire);
5020 			dst_ire = sire;
5021 			sire = NULL;
5022 		} else {
5023 			/*
5024 			 * Pick a source address so that a proper inbound
5025 			 * load spreading would happen.
5026 			 */
5027 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5028 			ipif_t *src_ipif = NULL;
5029 			ire_t *ipif_ire;
5030 
5031 			/*
5032 			 * Supply a local source address such that inbound
5033 			 * load spreading happens.
5034 			 *
5035 			 * Determine the best source address on this ill for
5036 			 * the destination.
5037 			 *
5038 			 * 1) For broadcast, we should return a broadcast ire
5039 			 *    found above so that upper layers know that the
5040 			 *    destination address is a broadcast address.
5041 			 *
5042 			 * 2) If the ipif is DEPRECATED, select a better
5043 			 *    source address.  Similarly, if the ipif is on
5044 			 *    the IPMP meta-interface, pick a source address
5045 			 *    at random to improve inbound load spreading.
5046 			 *
5047 			 * 3) If the outgoing interface is part of a usesrc
5048 			 *    group, then try selecting a source address from
5049 			 *    the usesrc ILL.
5050 			 */
5051 			if ((dst_ire->ire_zoneid != zoneid &&
5052 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5053 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5054 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5055 			    (IS_IPMP(ire_ill) ||
5056 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5057 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5058 				/*
5059 				 * If the destination is reachable via a
5060 				 * given gateway, the selected source address
5061 				 * should be in the same subnet as the gateway.
5062 				 * Otherwise, the destination is not reachable.
5063 				 *
5064 				 * If there are no interfaces on the same subnet
5065 				 * as the destination, ipif_select_source gives
5066 				 * first non-deprecated interface which might be
5067 				 * on a different subnet than the gateway.
5068 				 * This is not desirable. Hence pass the dst_ire
5069 				 * source address to ipif_select_source.
5070 				 * It is sure that the destination is reachable
5071 				 * with the dst_ire source address subnet.
5072 				 * So passing dst_ire source address to
5073 				 * ipif_select_source will make sure that the
5074 				 * selected source will be on the same subnet
5075 				 * as dst_ire source address.
5076 				 */
5077 				ipaddr_t saddr =
5078 				    dst_ire->ire_ipif->ipif_src_addr;
5079 				src_ipif = ipif_select_source(ire_ill,
5080 				    saddr, zoneid);
5081 				if (src_ipif != NULL) {
5082 					if (IS_VNI(src_ipif->ipif_ill)) {
5083 						/*
5084 						 * For VNI there is no
5085 						 * interface route
5086 						 */
5087 						src_addr =
5088 						    src_ipif->ipif_src_addr;
5089 					} else {
5090 						ipif_ire =
5091 						    ipif_to_ire(src_ipif);
5092 						if (ipif_ire != NULL) {
5093 							IRE_REFRELE(dst_ire);
5094 							dst_ire = ipif_ire;
5095 						}
5096 						src_addr =
5097 						    dst_ire->ire_src_addr;
5098 					}
5099 					ipif_refrele(src_ipif);
5100 				} else {
5101 					src_addr = dst_ire->ire_src_addr;
5102 				}
5103 			} else {
5104 				src_addr = dst_ire->ire_src_addr;
5105 			}
5106 		}
5107 	}
5108 
5109 	/*
5110 	 * We do ire_route_lookup() here (and not
5111 	 * interface lookup as we assert that
5112 	 * src_addr should only come from an
5113 	 * UP interface for hard binding.
5114 	 */
5115 	ASSERT(src_ire == NULL);
5116 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5117 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5118 	/* src_ire must be a local|loopback */
5119 	if (!IRE_IS_LOCAL(src_ire)) {
5120 		if (ip_debug > 2) {
5121 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5122 			    "src %s\n", AF_INET, &src_addr);
5123 		}
5124 		error = EADDRNOTAVAIL;
5125 		goto bad_addr;
5126 	}
5127 
5128 	/*
5129 	 * If the source address is a loopback address, the
5130 	 * destination had best be local or multicast.
5131 	 * The transports that can't handle multicast will reject
5132 	 * those addresses.
5133 	 */
5134 	if (src_ire->ire_type == IRE_LOOPBACK &&
5135 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5136 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5137 		error = -1;
5138 		goto bad_addr;
5139 	}
5140 
5141 	/*
5142 	 * Allow setting new policies. For example, disconnects come
5143 	 * down as ipa_t bind. As we would have set conn_policy_cached
5144 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5145 	 * can change after the disconnect.
5146 	 */
5147 	connp->conn_policy_cached = B_FALSE;
5148 
5149 	/*
5150 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5151 	 * can handle their passed-in conn's.
5152 	 */
5153 
5154 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5155 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5156 	connp->conn_lport = lport;
5157 	connp->conn_fport = fport;
5158 	*src_addrp = src_addr;
5159 
5160 	ASSERT(!(ipsec_policy_set && ire_requested));
5161 	if (ire_requested) {
5162 		iulp_t *ulp_info = NULL;
5163 
5164 		/*
5165 		 * Note that sire will not be NULL if this is an off-link
5166 		 * connection and there is not cache for that dest yet.
5167 		 *
5168 		 * XXX Because of an existing bug, if there are multiple
5169 		 * default routes, the IRE returned now may not be the actual
5170 		 * default route used (default routes are chosen in a
5171 		 * round robin fashion).  So if the metrics for different
5172 		 * default routes are different, we may return the wrong
5173 		 * metrics.  This will not be a problem if the existing
5174 		 * bug is fixed.
5175 		 */
5176 		if (sire != NULL) {
5177 			ulp_info = &(sire->ire_uinfo);
5178 		}
5179 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5180 			error = -1;
5181 			goto bad_addr;
5182 		}
5183 		mp = *mpp;
5184 	} else if (ipsec_policy_set) {
5185 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5186 			error = -1;
5187 			goto bad_addr;
5188 		}
5189 	}
5190 
5191 	/*
5192 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5193 	 * we'll cache that.  If we don't, we'll inherit global policy.
5194 	 *
5195 	 * We can't insert until the conn reflects the policy. Note that
5196 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5197 	 * connections where we don't have a policy. This is to prevent
5198 	 * global policy lookups in the inbound path.
5199 	 *
5200 	 * If we insert before we set conn_policy_cached,
5201 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5202 	 * because global policy cound be non-empty. We normally call
5203 	 * ipsec_check_policy() for conn_policy_cached connections only if
5204 	 * ipc_in_enforce_policy is set. But in this case,
5205 	 * conn_policy_cached can get set anytime since we made the
5206 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5207 	 * called, which will make the above assumption false.  Thus, we
5208 	 * need to insert after we set conn_policy_cached.
5209 	 */
5210 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5211 		goto bad_addr;
5212 
5213 	if (fanout_insert) {
5214 		/*
5215 		 * The addresses have been verified. Time to insert in
5216 		 * the correct fanout list.
5217 		 */
5218 		error = ipcl_conn_insert(connp, protocol, src_addr,
5219 		    dst_addr, connp->conn_ports);
5220 	}
5221 
5222 	if (error == 0) {
5223 		connp->conn_fully_bound = B_TRUE;
5224 		/*
5225 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5226 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5227 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5228 		 * ip_xxinfo_return(), which performs further checks
5229 		 * against them and upon success, returns the LSO/MDT info
5230 		 * mblk which we will attach to the bind acknowledgment.
5231 		 */
5232 		if (lso_dst_ire != NULL) {
5233 			mblk_t *lsoinfo_mp;
5234 
5235 			ASSERT(ill->ill_lso_capab != NULL);
5236 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5237 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5238 				if (mp == NULL) {
5239 					*mpp = lsoinfo_mp;
5240 				} else {
5241 					linkb(mp, lsoinfo_mp);
5242 				}
5243 			}
5244 		} else if (md_dst_ire != NULL) {
5245 			mblk_t *mdinfo_mp;
5246 
5247 			ASSERT(ill->ill_mdt_capab != NULL);
5248 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5249 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5250 				if (mp == NULL) {
5251 					*mpp = mdinfo_mp;
5252 				} else {
5253 					linkb(mp, mdinfo_mp);
5254 				}
5255 			}
5256 		}
5257 	}
5258 bad_addr:
5259 	if (ipsec_policy_set) {
5260 		ASSERT(mp != NULL);
5261 		freeb(mp);
5262 		/*
5263 		 * As of now assume that nothing else accompanies
5264 		 * IPSEC_POLICY_SET.
5265 		 */
5266 		*mpp = NULL;
5267 	}
5268 	if (src_ire != NULL)
5269 		IRE_REFRELE(src_ire);
5270 	if (dst_ire != NULL)
5271 		IRE_REFRELE(dst_ire);
5272 	if (sire != NULL)
5273 		IRE_REFRELE(sire);
5274 	if (md_dst_ire != NULL)
5275 		IRE_REFRELE(md_dst_ire);
5276 	if (lso_dst_ire != NULL)
5277 		IRE_REFRELE(lso_dst_ire);
5278 	if (effective_cred != NULL)
5279 		crfree(effective_cred);
5280 	return (error);
5281 }
5282 
5283 int
5284 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5285     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5286     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5287 {
5288 	int error;
5289 	mblk_t	*mp = NULL;
5290 	boolean_t ire_requested;
5291 
5292 	if (ire_mpp)
5293 		mp = *ire_mpp;
5294 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5295 
5296 	ASSERT(!connp->conn_af_isv6);
5297 	connp->conn_pkt_isv6 = B_FALSE;
5298 	connp->conn_ulp = protocol;
5299 
5300 	/* For raw socket, the local port is not set. */
5301 	if (lport == 0)
5302 		lport = connp->conn_lport;
5303 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5304 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5305 	if (error == 0) {
5306 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5307 		    ire_requested);
5308 	} else if (error < 0) {
5309 		error = -TBADADDR;
5310 	}
5311 	return (error);
5312 }
5313 
5314 /*
5315  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5316  * Prefers dst_ire over src_ire.
5317  */
5318 static boolean_t
5319 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5320 {
5321 	mblk_t	*mp = *mpp;
5322 	ire_t	*ret_ire;
5323 
5324 	ASSERT(mp != NULL);
5325 
5326 	if (ire != NULL) {
5327 		/*
5328 		 * mp initialized above to IRE_DB_REQ_TYPE
5329 		 * appended mblk. Its <upper protocol>'s
5330 		 * job to make sure there is room.
5331 		 */
5332 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5333 			return (B_FALSE);
5334 
5335 		mp->b_datap->db_type = IRE_DB_TYPE;
5336 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5337 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5338 		ret_ire = (ire_t *)mp->b_rptr;
5339 		/*
5340 		 * Pass the latest setting of the ip_path_mtu_discovery and
5341 		 * copy the ulp info if any.
5342 		 */
5343 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5344 		    IPH_DF : 0;
5345 		if (ulp_info != NULL) {
5346 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5347 			    sizeof (iulp_t));
5348 		}
5349 		ret_ire->ire_mp = mp;
5350 	} else {
5351 		/*
5352 		 * No IRE was found. Remove IRE mblk.
5353 		 */
5354 		*mpp = mp->b_cont;
5355 		freeb(mp);
5356 	}
5357 	return (B_TRUE);
5358 }
5359 
5360 /*
5361  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5362  * the final piece where we don't.  Return a pointer to the first mblk in the
5363  * result, and update the pointer to the next mblk to chew on.  If anything
5364  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5365  * NULL pointer.
5366  */
5367 mblk_t *
5368 ip_carve_mp(mblk_t **mpp, ssize_t len)
5369 {
5370 	mblk_t	*mp0;
5371 	mblk_t	*mp1;
5372 	mblk_t	*mp2;
5373 
5374 	if (!len || !mpp || !(mp0 = *mpp))
5375 		return (NULL);
5376 	/* If we aren't going to consume the first mblk, we need a dup. */
5377 	if (mp0->b_wptr - mp0->b_rptr > len) {
5378 		mp1 = dupb(mp0);
5379 		if (mp1) {
5380 			/* Partition the data between the two mblks. */
5381 			mp1->b_wptr = mp1->b_rptr + len;
5382 			mp0->b_rptr = mp1->b_wptr;
5383 			/*
5384 			 * after adjustments if mblk not consumed is now
5385 			 * unaligned, try to align it. If this fails free
5386 			 * all messages and let upper layer recover.
5387 			 */
5388 			if (!OK_32PTR(mp0->b_rptr)) {
5389 				if (!pullupmsg(mp0, -1)) {
5390 					freemsg(mp0);
5391 					freemsg(mp1);
5392 					*mpp = NULL;
5393 					return (NULL);
5394 				}
5395 			}
5396 		}
5397 		return (mp1);
5398 	}
5399 	/* Eat through as many mblks as we need to get len bytes. */
5400 	len -= mp0->b_wptr - mp0->b_rptr;
5401 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5402 		if (mp2->b_wptr - mp2->b_rptr > len) {
5403 			/*
5404 			 * We won't consume the entire last mblk.  Like
5405 			 * above, dup and partition it.
5406 			 */
5407 			mp1->b_cont = dupb(mp2);
5408 			mp1 = mp1->b_cont;
5409 			if (!mp1) {
5410 				/*
5411 				 * Trouble.  Rather than go to a lot of
5412 				 * trouble to clean up, we free the messages.
5413 				 * This won't be any worse than losing it on
5414 				 * the wire.
5415 				 */
5416 				freemsg(mp0);
5417 				freemsg(mp2);
5418 				*mpp = NULL;
5419 				return (NULL);
5420 			}
5421 			mp1->b_wptr = mp1->b_rptr + len;
5422 			mp2->b_rptr = mp1->b_wptr;
5423 			/*
5424 			 * after adjustments if mblk not consumed is now
5425 			 * unaligned, try to align it. If this fails free
5426 			 * all messages and let upper layer recover.
5427 			 */
5428 			if (!OK_32PTR(mp2->b_rptr)) {
5429 				if (!pullupmsg(mp2, -1)) {
5430 					freemsg(mp0);
5431 					freemsg(mp2);
5432 					*mpp = NULL;
5433 					return (NULL);
5434 				}
5435 			}
5436 			*mpp = mp2;
5437 			return (mp0);
5438 		}
5439 		/* Decrement len by the amount we just got. */
5440 		len -= mp2->b_wptr - mp2->b_rptr;
5441 	}
5442 	/*
5443 	 * len should be reduced to zero now.  If not our caller has
5444 	 * screwed up.
5445 	 */
5446 	if (len) {
5447 		/* Shouldn't happen! */
5448 		freemsg(mp0);
5449 		*mpp = NULL;
5450 		return (NULL);
5451 	}
5452 	/*
5453 	 * We consumed up to exactly the end of an mblk.  Detach the part
5454 	 * we are returning from the rest of the chain.
5455 	 */
5456 	mp1->b_cont = NULL;
5457 	*mpp = mp2;
5458 	return (mp0);
5459 }
5460 
5461 /* The ill stream is being unplumbed. Called from ip_close */
5462 int
5463 ip_modclose(ill_t *ill)
5464 {
5465 	boolean_t success;
5466 	ipsq_t	*ipsq;
5467 	ipif_t	*ipif;
5468 	queue_t	*q = ill->ill_rq;
5469 	ip_stack_t	*ipst = ill->ill_ipst;
5470 	int	i;
5471 
5472 	/*
5473 	 * The punlink prior to this may have initiated a capability
5474 	 * negotiation. But ipsq_enter will block until that finishes or
5475 	 * times out.
5476 	 */
5477 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5478 
5479 	/*
5480 	 * Open/close/push/pop is guaranteed to be single threaded
5481 	 * per stream by STREAMS. FS guarantees that all references
5482 	 * from top are gone before close is called. So there can't
5483 	 * be another close thread that has set CONDEMNED on this ill.
5484 	 * and cause ipsq_enter to return failure.
5485 	 */
5486 	ASSERT(success);
5487 	ipsq = ill->ill_phyint->phyint_ipsq;
5488 
5489 	/*
5490 	 * Mark it condemned. No new reference will be made to this ill.
5491 	 * Lookup functions will return an error. Threads that try to
5492 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5493 	 * that the refcnt will drop down to zero.
5494 	 */
5495 	mutex_enter(&ill->ill_lock);
5496 	ill->ill_state_flags |= ILL_CONDEMNED;
5497 	for (ipif = ill->ill_ipif; ipif != NULL;
5498 	    ipif = ipif->ipif_next) {
5499 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5500 	}
5501 	/*
5502 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5503 	 * returns  error if ILL_CONDEMNED is set
5504 	 */
5505 	cv_broadcast(&ill->ill_cv);
5506 	mutex_exit(&ill->ill_lock);
5507 
5508 	/*
5509 	 * Send all the deferred DLPI messages downstream which came in
5510 	 * during the small window right before ipsq_enter(). We do this
5511 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5512 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5513 	 */
5514 	ill_dlpi_send_deferred(ill);
5515 
5516 	/*
5517 	 * Shut down fragmentation reassembly.
5518 	 * ill_frag_timer won't start a timer again.
5519 	 * Now cancel any existing timer
5520 	 */
5521 	(void) untimeout(ill->ill_frag_timer_id);
5522 	(void) ill_frag_timeout(ill, 0);
5523 
5524 	/*
5525 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5526 	 * this ill. Then wait for the refcnts to drop to zero.
5527 	 * ill_is_freeable checks whether the ill is really quiescent.
5528 	 * Then make sure that threads that are waiting to enter the
5529 	 * ipsq have seen the error returned by ipsq_enter and have
5530 	 * gone away. Then we call ill_delete_tail which does the
5531 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5532 	 */
5533 	ill_delete(ill);
5534 	mutex_enter(&ill->ill_lock);
5535 	while (!ill_is_freeable(ill))
5536 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5537 	while (ill->ill_waiters)
5538 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5539 
5540 	mutex_exit(&ill->ill_lock);
5541 
5542 	/*
5543 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5544 	 * it held until the end of the function since the cleanup
5545 	 * below needs to be able to use the ip_stack_t.
5546 	 */
5547 	netstack_hold(ipst->ips_netstack);
5548 
5549 	/* qprocsoff is done via ill_delete_tail */
5550 	ill_delete_tail(ill);
5551 	ASSERT(ill->ill_ipst == NULL);
5552 
5553 	/*
5554 	 * Walk through all upper (conn) streams and qenable
5555 	 * those that have queued data.
5556 	 * close synchronization needs this to
5557 	 * be done to ensure that all upper layers blocked
5558 	 * due to flow control to the closing device
5559 	 * get unblocked.
5560 	 */
5561 	ip1dbg(("ip_wsrv: walking\n"));
5562 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5563 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5564 	}
5565 
5566 	mutex_enter(&ipst->ips_ip_mi_lock);
5567 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5568 	mutex_exit(&ipst->ips_ip_mi_lock);
5569 
5570 	/*
5571 	 * credp could be null if the open didn't succeed and ip_modopen
5572 	 * itself calls ip_close.
5573 	 */
5574 	if (ill->ill_credp != NULL)
5575 		crfree(ill->ill_credp);
5576 
5577 	/*
5578 	 * Now we are done with the module close pieces that
5579 	 * need the netstack_t.
5580 	 */
5581 	netstack_rele(ipst->ips_netstack);
5582 
5583 	mi_close_free((IDP)ill);
5584 	q->q_ptr = WR(q)->q_ptr = NULL;
5585 
5586 	ipsq_exit(ipsq);
5587 
5588 	return (0);
5589 }
5590 
5591 /*
5592  * This is called as part of close() for IP, UDP, ICMP, and RTS
5593  * in order to quiesce the conn.
5594  */
5595 void
5596 ip_quiesce_conn(conn_t *connp)
5597 {
5598 	boolean_t	drain_cleanup_reqd = B_FALSE;
5599 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5600 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5601 	ip_stack_t	*ipst;
5602 
5603 	ASSERT(!IPCL_IS_TCP(connp));
5604 	ipst = connp->conn_netstack->netstack_ip;
5605 
5606 	/*
5607 	 * Mark the conn as closing, and this conn must not be
5608 	 * inserted in future into any list. Eg. conn_drain_insert(),
5609 	 * won't insert this conn into the conn_drain_list.
5610 	 * Similarly ill_pending_mp_add() will not add any mp to
5611 	 * the pending mp list, after this conn has started closing.
5612 	 *
5613 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5614 	 * cannot get set henceforth.
5615 	 */
5616 	mutex_enter(&connp->conn_lock);
5617 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5618 	connp->conn_state_flags |= CONN_CLOSING;
5619 	if (connp->conn_idl != NULL)
5620 		drain_cleanup_reqd = B_TRUE;
5621 	if (connp->conn_oper_pending_ill != NULL)
5622 		conn_ioctl_cleanup_reqd = B_TRUE;
5623 	if (connp->conn_dhcpinit_ill != NULL) {
5624 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5625 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5626 		connp->conn_dhcpinit_ill = NULL;
5627 	}
5628 	if (connp->conn_ilg_inuse != 0)
5629 		ilg_cleanup_reqd = B_TRUE;
5630 	mutex_exit(&connp->conn_lock);
5631 
5632 	if (conn_ioctl_cleanup_reqd)
5633 		conn_ioctl_cleanup(connp);
5634 
5635 	if (is_system_labeled() && connp->conn_anon_port) {
5636 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5637 		    connp->conn_mlp_type, connp->conn_ulp,
5638 		    ntohs(connp->conn_lport), B_FALSE);
5639 		connp->conn_anon_port = 0;
5640 	}
5641 	connp->conn_mlp_type = mlptSingle;
5642 
5643 	/*
5644 	 * Remove this conn from any fanout list it is on.
5645 	 * and then wait for any threads currently operating
5646 	 * on this endpoint to finish
5647 	 */
5648 	ipcl_hash_remove(connp);
5649 
5650 	/*
5651 	 * Remove this conn from the drain list, and do
5652 	 * any other cleanup that may be required.
5653 	 * (Only non-tcp streams may have a non-null conn_idl.
5654 	 * TCP streams are never flow controlled, and
5655 	 * conn_idl will be null)
5656 	 */
5657 	if (drain_cleanup_reqd)
5658 		conn_drain_tail(connp, B_TRUE);
5659 
5660 	if (connp == ipst->ips_ip_g_mrouter)
5661 		(void) ip_mrouter_done(NULL, ipst);
5662 
5663 	if (ilg_cleanup_reqd)
5664 		ilg_delete_all(connp);
5665 
5666 	conn_delete_ire(connp, NULL);
5667 
5668 	/*
5669 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5670 	 * callers from write side can't be there now because close
5671 	 * is in progress. The only other caller is ipcl_walk
5672 	 * which checks for the condemned flag.
5673 	 */
5674 	mutex_enter(&connp->conn_lock);
5675 	connp->conn_state_flags |= CONN_CONDEMNED;
5676 	while (connp->conn_ref != 1)
5677 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5678 	connp->conn_state_flags |= CONN_QUIESCED;
5679 	mutex_exit(&connp->conn_lock);
5680 }
5681 
5682 /* ARGSUSED */
5683 int
5684 ip_close(queue_t *q, int flags)
5685 {
5686 	conn_t		*connp;
5687 
5688 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5689 
5690 	/*
5691 	 * Call the appropriate delete routine depending on whether this is
5692 	 * a module or device.
5693 	 */
5694 	if (WR(q)->q_next != NULL) {
5695 		/* This is a module close */
5696 		return (ip_modclose((ill_t *)q->q_ptr));
5697 	}
5698 
5699 	connp = q->q_ptr;
5700 	ip_quiesce_conn(connp);
5701 
5702 	qprocsoff(q);
5703 
5704 	/*
5705 	 * Now we are truly single threaded on this stream, and can
5706 	 * delete the things hanging off the connp, and finally the connp.
5707 	 * We removed this connp from the fanout list, it cannot be
5708 	 * accessed thru the fanouts, and we already waited for the
5709 	 * conn_ref to drop to 0. We are already in close, so
5710 	 * there cannot be any other thread from the top. qprocsoff
5711 	 * has completed, and service has completed or won't run in
5712 	 * future.
5713 	 */
5714 	ASSERT(connp->conn_ref == 1);
5715 
5716 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5717 
5718 	connp->conn_ref--;
5719 	ipcl_conn_destroy(connp);
5720 
5721 	q->q_ptr = WR(q)->q_ptr = NULL;
5722 	return (0);
5723 }
5724 
5725 /*
5726  * Wapper around putnext() so that ip_rts_request can merely use
5727  * conn_recv.
5728  */
5729 /*ARGSUSED2*/
5730 static void
5731 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5732 {
5733 	conn_t *connp = (conn_t *)arg1;
5734 
5735 	putnext(connp->conn_rq, mp);
5736 }
5737 
5738 /*
5739  * Called when the module is about to be unloaded
5740  */
5741 void
5742 ip_ddi_destroy(void)
5743 {
5744 	tnet_fini();
5745 
5746 	icmp_ddi_g_destroy();
5747 	rts_ddi_g_destroy();
5748 	udp_ddi_g_destroy();
5749 	sctp_ddi_g_destroy();
5750 	tcp_ddi_g_destroy();
5751 	ipsec_policy_g_destroy();
5752 	ipcl_g_destroy();
5753 	ip_net_g_destroy();
5754 	ip_ire_g_fini();
5755 	inet_minor_destroy(ip_minor_arena_sa);
5756 #if defined(_LP64)
5757 	inet_minor_destroy(ip_minor_arena_la);
5758 #endif
5759 
5760 #ifdef DEBUG
5761 	list_destroy(&ip_thread_list);
5762 	rw_destroy(&ip_thread_rwlock);
5763 	tsd_destroy(&ip_thread_data);
5764 #endif
5765 
5766 	netstack_unregister(NS_IP);
5767 }
5768 
5769 /*
5770  * First step in cleanup.
5771  */
5772 /* ARGSUSED */
5773 static void
5774 ip_stack_shutdown(netstackid_t stackid, void *arg)
5775 {
5776 	ip_stack_t *ipst = (ip_stack_t *)arg;
5777 
5778 #ifdef NS_DEBUG
5779 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5780 #endif
5781 
5782 	/* Get rid of loopback interfaces and their IREs */
5783 	ip_loopback_cleanup(ipst);
5784 
5785 	/*
5786 	 * The *_hook_shutdown()s start the process of notifying any
5787 	 * consumers that things are going away.... nothing is destroyed.
5788 	 */
5789 	ipv4_hook_shutdown(ipst);
5790 	ipv6_hook_shutdown(ipst);
5791 
5792 	mutex_enter(&ipst->ips_capab_taskq_lock);
5793 	ipst->ips_capab_taskq_quit = B_TRUE;
5794 	cv_signal(&ipst->ips_capab_taskq_cv);
5795 	mutex_exit(&ipst->ips_capab_taskq_lock);
5796 
5797 	mutex_enter(&ipst->ips_mrt_lock);
5798 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5799 	cv_signal(&ipst->ips_mrt_cv);
5800 	mutex_exit(&ipst->ips_mrt_lock);
5801 }
5802 
5803 /*
5804  * Free the IP stack instance.
5805  */
5806 static void
5807 ip_stack_fini(netstackid_t stackid, void *arg)
5808 {
5809 	ip_stack_t *ipst = (ip_stack_t *)arg;
5810 	int ret;
5811 
5812 #ifdef NS_DEBUG
5813 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5814 #endif
5815 	/*
5816 	 * At this point, all of the notifications that the events and
5817 	 * protocols are going away have been run, meaning that we can
5818 	 * now set about starting to clean things up.
5819 	 */
5820 	ipv4_hook_destroy(ipst);
5821 	ipv6_hook_destroy(ipst);
5822 	ip_net_destroy(ipst);
5823 
5824 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5825 	cv_destroy(&ipst->ips_capab_taskq_cv);
5826 	list_destroy(&ipst->ips_capab_taskq_list);
5827 
5828 	mutex_enter(&ipst->ips_mrt_lock);
5829 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5830 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5831 	mutex_destroy(&ipst->ips_mrt_lock);
5832 	cv_destroy(&ipst->ips_mrt_cv);
5833 	cv_destroy(&ipst->ips_mrt_done_cv);
5834 
5835 	ipmp_destroy(ipst);
5836 	rw_destroy(&ipst->ips_srcid_lock);
5837 
5838 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5839 	ipst->ips_ip_mibkp = NULL;
5840 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5841 	ipst->ips_icmp_mibkp = NULL;
5842 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5843 	ipst->ips_ip_kstat = NULL;
5844 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5845 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5846 	ipst->ips_ip6_kstat = NULL;
5847 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5848 
5849 	nd_free(&ipst->ips_ip_g_nd);
5850 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5851 	ipst->ips_param_arr = NULL;
5852 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5853 	ipst->ips_ndp_arr = NULL;
5854 
5855 	ip_mrouter_stack_destroy(ipst);
5856 
5857 	mutex_destroy(&ipst->ips_ip_mi_lock);
5858 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5859 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5860 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5861 
5862 	ret = untimeout(ipst->ips_igmp_timeout_id);
5863 	if (ret == -1) {
5864 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5865 	} else {
5866 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5867 		ipst->ips_igmp_timeout_id = 0;
5868 	}
5869 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5874 		ipst->ips_igmp_slowtimeout_id = 0;
5875 	}
5876 	ret = untimeout(ipst->ips_mld_timeout_id);
5877 	if (ret == -1) {
5878 		ASSERT(ipst->ips_mld_timeout_id == 0);
5879 	} else {
5880 		ASSERT(ipst->ips_mld_timeout_id != 0);
5881 		ipst->ips_mld_timeout_id = 0;
5882 	}
5883 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5884 	if (ret == -1) {
5885 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5886 	} else {
5887 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5888 		ipst->ips_mld_slowtimeout_id = 0;
5889 	}
5890 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5891 	if (ret == -1) {
5892 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5893 	} else {
5894 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5895 		ipst->ips_ip_ire_expire_id = 0;
5896 	}
5897 
5898 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5899 	mutex_destroy(&ipst->ips_mld_timer_lock);
5900 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5901 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5902 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5903 	rw_destroy(&ipst->ips_ill_g_lock);
5904 
5905 	ipobs_fini(ipst);
5906 	ip_ire_fini(ipst);
5907 	ip6_asp_free(ipst);
5908 	conn_drain_fini(ipst);
5909 	ipcl_destroy(ipst);
5910 
5911 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5912 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5913 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5914 	ipst->ips_ndp4 = NULL;
5915 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5916 	ipst->ips_ndp6 = NULL;
5917 
5918 	if (ipst->ips_loopback_ksp != NULL) {
5919 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5920 		ipst->ips_loopback_ksp = NULL;
5921 	}
5922 
5923 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5924 	ipst->ips_phyint_g_list = NULL;
5925 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5926 	ipst->ips_ill_g_heads = NULL;
5927 
5928 	ldi_ident_release(ipst->ips_ldi_ident);
5929 	kmem_free(ipst, sizeof (*ipst));
5930 }
5931 
5932 /*
5933  * This function is called from the TSD destructor, and is used to debug
5934  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5935  * details.
5936  */
5937 static void
5938 ip_thread_exit(void *phash)
5939 {
5940 	th_hash_t *thh = phash;
5941 
5942 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5943 	list_remove(&ip_thread_list, thh);
5944 	rw_exit(&ip_thread_rwlock);
5945 	mod_hash_destroy_hash(thh->thh_hash);
5946 	kmem_free(thh, sizeof (*thh));
5947 }
5948 
5949 /*
5950  * Called when the IP kernel module is loaded into the kernel
5951  */
5952 void
5953 ip_ddi_init(void)
5954 {
5955 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5956 
5957 	/*
5958 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5959 	 * initial devices: ip, ip6, tcp, tcp6.
5960 	 */
5961 	/*
5962 	 * If this is a 64-bit kernel, then create two separate arenas -
5963 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5964 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5965 	 */
5966 	ip_minor_arena_la = NULL;
5967 	ip_minor_arena_sa = NULL;
5968 #if defined(_LP64)
5969 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5970 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5971 		cmn_err(CE_PANIC,
5972 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5973 	}
5974 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5975 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5976 		cmn_err(CE_PANIC,
5977 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5978 	}
5979 #else
5980 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5981 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5982 		cmn_err(CE_PANIC,
5983 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5984 	}
5985 #endif
5986 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5987 
5988 	ipcl_g_init();
5989 	ip_ire_g_init();
5990 	ip_net_g_init();
5991 
5992 #ifdef DEBUG
5993 	tsd_create(&ip_thread_data, ip_thread_exit);
5994 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5995 	list_create(&ip_thread_list, sizeof (th_hash_t),
5996 	    offsetof(th_hash_t, thh_link));
5997 #endif
5998 
5999 	/*
6000 	 * We want to be informed each time a stack is created or
6001 	 * destroyed in the kernel, so we can maintain the
6002 	 * set of udp_stack_t's.
6003 	 */
6004 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
6005 	    ip_stack_fini);
6006 
6007 	ipsec_policy_g_init();
6008 	tcp_ddi_g_init();
6009 	sctp_ddi_g_init();
6010 
6011 	tnet_init();
6012 
6013 	udp_ddi_g_init();
6014 	rts_ddi_g_init();
6015 	icmp_ddi_g_init();
6016 }
6017 
6018 /*
6019  * Initialize the IP stack instance.
6020  */
6021 static void *
6022 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6023 {
6024 	ip_stack_t	*ipst;
6025 	ipparam_t	*pa;
6026 	ipndp_t		*na;
6027 	major_t		major;
6028 
6029 #ifdef NS_DEBUG
6030 	printf("ip_stack_init(stack %d)\n", stackid);
6031 #endif
6032 
6033 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6034 	ipst->ips_netstack = ns;
6035 
6036 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6037 	    KM_SLEEP);
6038 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6039 	    KM_SLEEP);
6040 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6041 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6042 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6043 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6044 
6045 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6046 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6047 	ipst->ips_igmp_deferred_next = INFINITY;
6048 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6049 	ipst->ips_mld_deferred_next = INFINITY;
6050 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6051 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6052 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6053 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6054 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6055 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6056 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6057 
6058 	ipcl_init(ipst);
6059 	ip_ire_init(ipst);
6060 	ip6_asp_init(ipst);
6061 	ipif_init(ipst);
6062 	conn_drain_init(ipst);
6063 	ip_mrouter_stack_init(ipst);
6064 
6065 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6066 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6067 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
6068 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
6069 
6070 	ipst->ips_ip_multirt_log_interval = 1000;
6071 
6072 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6073 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6074 	ipst->ips_ill_index = 1;
6075 
6076 	ipst->ips_saved_ip_g_forward = -1;
6077 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6078 
6079 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6080 	ipst->ips_param_arr = pa;
6081 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6082 
6083 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6084 	ipst->ips_ndp_arr = na;
6085 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6086 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6087 	    (caddr_t)&ipst->ips_ip_g_forward;
6088 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6089 	    (caddr_t)&ipst->ips_ipv6_forward;
6090 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6091 	    "ip_cgtp_filter") == 0);
6092 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6093 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6094 
6095 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6096 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6097 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6098 
6099 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6100 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6101 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6102 	ipst->ips_ip6_kstat =
6103 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6104 
6105 	ipst->ips_ip_src_id = 1;
6106 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6107 
6108 	ipobs_init(ipst);
6109 	ip_net_init(ipst, ns);
6110 	ipv4_hook_init(ipst);
6111 	ipv6_hook_init(ipst);
6112 	ipmp_init(ipst);
6113 
6114 	/*
6115 	 * Create the taskq dispatcher thread and initialize related stuff.
6116 	 */
6117 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6118 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6119 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6120 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6121 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6122 	    offsetof(mblk_t, b_next));
6123 
6124 	/*
6125 	 * Create the mcast_restart_timers_thread() worker thread.
6126 	 */
6127 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6128 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6129 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6130 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6131 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6132 
6133 	major = mod_name_to_major(INET_NAME);
6134 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6135 	return (ipst);
6136 }
6137 
6138 /*
6139  * Allocate and initialize a DLPI template of the specified length.  (May be
6140  * called as writer.)
6141  */
6142 mblk_t *
6143 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6144 {
6145 	mblk_t	*mp;
6146 
6147 	mp = allocb(len, BPRI_MED);
6148 	if (!mp)
6149 		return (NULL);
6150 
6151 	/*
6152 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6153 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6154 	 * that other DLPI are M_PROTO.
6155 	 */
6156 	if (prim == DL_INFO_REQ) {
6157 		mp->b_datap->db_type = M_PCPROTO;
6158 	} else {
6159 		mp->b_datap->db_type = M_PROTO;
6160 	}
6161 
6162 	mp->b_wptr = mp->b_rptr + len;
6163 	bzero(mp->b_rptr, len);
6164 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6165 	return (mp);
6166 }
6167 
6168 /*
6169  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6170  */
6171 mblk_t *
6172 ip_dlnotify_alloc(uint_t notification, uint_t data)
6173 {
6174 	dl_notify_ind_t	*notifyp;
6175 	mblk_t		*mp;
6176 
6177 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6178 		return (NULL);
6179 
6180 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6181 	notifyp->dl_notification = notification;
6182 	notifyp->dl_data = data;
6183 	return (mp);
6184 }
6185 
6186 /*
6187  * Debug formatting routine.  Returns a character string representation of the
6188  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6189  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6190  *
6191  * Once the ndd table-printing interfaces are removed, this can be changed to
6192  * standard dotted-decimal form.
6193  */
6194 char *
6195 ip_dot_addr(ipaddr_t addr, char *buf)
6196 {
6197 	uint8_t *ap = (uint8_t *)&addr;
6198 
6199 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6200 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6201 	return (buf);
6202 }
6203 
6204 /*
6205  * Write the given MAC address as a printable string in the usual colon-
6206  * separated format.
6207  */
6208 const char *
6209 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6210 {
6211 	char *bp;
6212 
6213 	if (alen == 0 || buflen < 4)
6214 		return ("?");
6215 	bp = buf;
6216 	for (;;) {
6217 		/*
6218 		 * If there are more MAC address bytes available, but we won't
6219 		 * have any room to print them, then add "..." to the string
6220 		 * instead.  See below for the 'magic number' explanation.
6221 		 */
6222 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6223 			(void) strcpy(bp, "...");
6224 			break;
6225 		}
6226 		(void) sprintf(bp, "%02x", *addr++);
6227 		bp += 2;
6228 		if (--alen == 0)
6229 			break;
6230 		*bp++ = ':';
6231 		buflen -= 3;
6232 		/*
6233 		 * At this point, based on the first 'if' statement above,
6234 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6235 		 * buflen >= 4.  The first case leaves room for the final "xx"
6236 		 * number and trailing NUL byte.  The second leaves room for at
6237 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6238 		 * that statement.
6239 		 */
6240 	}
6241 	return (buf);
6242 }
6243 
6244 /*
6245  * Send an ICMP error after patching up the packet appropriately.  Returns
6246  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6247  */
6248 static boolean_t
6249 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6250     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6251     zoneid_t zoneid, ip_stack_t *ipst)
6252 {
6253 	ipha_t *ipha;
6254 	mblk_t *first_mp;
6255 	boolean_t secure;
6256 	unsigned char db_type;
6257 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6258 
6259 	first_mp = mp;
6260 	if (mctl_present) {
6261 		mp = mp->b_cont;
6262 		secure = ipsec_in_is_secure(first_mp);
6263 		ASSERT(mp != NULL);
6264 	} else {
6265 		/*
6266 		 * If this is an ICMP error being reported - which goes
6267 		 * up as M_CTLs, we need to convert them to M_DATA till
6268 		 * we finish checking with global policy because
6269 		 * ipsec_check_global_policy() assumes M_DATA as clear
6270 		 * and M_CTL as secure.
6271 		 */
6272 		db_type = DB_TYPE(mp);
6273 		DB_TYPE(mp) = M_DATA;
6274 		secure = B_FALSE;
6275 	}
6276 	/*
6277 	 * We are generating an icmp error for some inbound packet.
6278 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6279 	 * Before we generate an error, check with global policy
6280 	 * to see whether this is allowed to enter the system. As
6281 	 * there is no "conn", we are checking with global policy.
6282 	 */
6283 	ipha = (ipha_t *)mp->b_rptr;
6284 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6285 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6286 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6287 		if (first_mp == NULL)
6288 			return (B_FALSE);
6289 	}
6290 
6291 	if (!mctl_present)
6292 		DB_TYPE(mp) = db_type;
6293 
6294 	if (flags & IP_FF_SEND_ICMP) {
6295 		if (flags & IP_FF_HDR_COMPLETE) {
6296 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6297 				freemsg(first_mp);
6298 				return (B_TRUE);
6299 			}
6300 		}
6301 		if (flags & IP_FF_CKSUM) {
6302 			/*
6303 			 * Have to correct checksum since
6304 			 * the packet might have been
6305 			 * fragmented and the reassembly code in ip_rput
6306 			 * does not restore the IP checksum.
6307 			 */
6308 			ipha->ipha_hdr_checksum = 0;
6309 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6310 		}
6311 		switch (icmp_type) {
6312 		case ICMP_DEST_UNREACHABLE:
6313 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6314 			    ipst);
6315 			break;
6316 		default:
6317 			freemsg(first_mp);
6318 			break;
6319 		}
6320 	} else {
6321 		freemsg(first_mp);
6322 		return (B_FALSE);
6323 	}
6324 
6325 	return (B_TRUE);
6326 }
6327 
6328 /*
6329  * Used to send an ICMP error message when a packet is received for
6330  * a protocol that is not supported. The mblk passed as argument
6331  * is consumed by this function.
6332  */
6333 void
6334 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6335     ip_stack_t *ipst)
6336 {
6337 	mblk_t *mp;
6338 	ipha_t *ipha;
6339 	ill_t *ill;
6340 	ipsec_in_t *ii;
6341 
6342 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6343 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6344 
6345 	mp = ipsec_mp->b_cont;
6346 	ipsec_mp->b_cont = NULL;
6347 	ipha = (ipha_t *)mp->b_rptr;
6348 	/* Get ill from index in ipsec_in_t. */
6349 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6350 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6351 	    ipst);
6352 	if (ill != NULL) {
6353 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6354 			if (ip_fanout_send_icmp(q, mp, flags,
6355 			    ICMP_DEST_UNREACHABLE,
6356 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6357 				BUMP_MIB(ill->ill_ip_mib,
6358 				    ipIfStatsInUnknownProtos);
6359 			}
6360 		} else {
6361 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6362 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6363 			    0, B_FALSE, zoneid, ipst)) {
6364 				BUMP_MIB(ill->ill_ip_mib,
6365 				    ipIfStatsInUnknownProtos);
6366 			}
6367 		}
6368 		ill_refrele(ill);
6369 	} else { /* re-link for the freemsg() below. */
6370 		ipsec_mp->b_cont = mp;
6371 	}
6372 
6373 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6374 	freemsg(ipsec_mp);
6375 }
6376 
6377 /*
6378  * See if the inbound datagram has had IPsec processing applied to it.
6379  */
6380 boolean_t
6381 ipsec_in_is_secure(mblk_t *ipsec_mp)
6382 {
6383 	ipsec_in_t *ii;
6384 
6385 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6386 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6387 
6388 	if (ii->ipsec_in_loopback) {
6389 		return (ii->ipsec_in_secure);
6390 	} else {
6391 		return (ii->ipsec_in_ah_sa != NULL ||
6392 		    ii->ipsec_in_esp_sa != NULL ||
6393 		    ii->ipsec_in_decaps);
6394 	}
6395 }
6396 
6397 /*
6398  * Handle protocols with which IP is less intimate.  There
6399  * can be more than one stream bound to a particular
6400  * protocol.  When this is the case, normally each one gets a copy
6401  * of any incoming packets.
6402  *
6403  * IPsec NOTE :
6404  *
6405  * Don't allow a secure packet going up a non-secure connection.
6406  * We don't allow this because
6407  *
6408  * 1) Reply might go out in clear which will be dropped at
6409  *    the sending side.
6410  * 2) If the reply goes out in clear it will give the
6411  *    adversary enough information for getting the key in
6412  *    most of the cases.
6413  *
6414  * Moreover getting a secure packet when we expect clear
6415  * implies that SA's were added without checking for
6416  * policy on both ends. This should not happen once ISAKMP
6417  * is used to negotiate SAs as SAs will be added only after
6418  * verifying the policy.
6419  *
6420  * NOTE : If the packet was tunneled and not multicast we only send
6421  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6422  * back to delivering packets to AF_INET6 raw sockets.
6423  *
6424  * IPQoS Notes:
6425  * Once we have determined the client, invoke IPPF processing.
6426  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6427  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6428  * ip_policy will be false.
6429  *
6430  * Zones notes:
6431  * Currently only applications in the global zone can create raw sockets for
6432  * protocols other than ICMP. So unlike the broadcast / multicast case of
6433  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6434  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6435  */
6436 static void
6437 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6438     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6439     zoneid_t zoneid)
6440 {
6441 	queue_t	*rq;
6442 	mblk_t	*mp1, *first_mp1;
6443 	uint_t	protocol = ipha->ipha_protocol;
6444 	ipaddr_t dst;
6445 	boolean_t one_only;
6446 	mblk_t *first_mp = mp;
6447 	boolean_t secure;
6448 	uint32_t ill_index;
6449 	conn_t	*connp, *first_connp, *next_connp;
6450 	connf_t	*connfp;
6451 	boolean_t shared_addr;
6452 	mib2_ipIfStatsEntry_t *mibptr;
6453 	ip_stack_t *ipst = recv_ill->ill_ipst;
6454 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6455 
6456 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6457 	if (mctl_present) {
6458 		mp = first_mp->b_cont;
6459 		secure = ipsec_in_is_secure(first_mp);
6460 		ASSERT(mp != NULL);
6461 	} else {
6462 		secure = B_FALSE;
6463 	}
6464 	dst = ipha->ipha_dst;
6465 	/*
6466 	 * If the packet was tunneled and not multicast we only send to it
6467 	 * the first match.
6468 	 */
6469 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6470 	    !CLASSD(dst));
6471 
6472 	shared_addr = (zoneid == ALL_ZONES);
6473 	if (shared_addr) {
6474 		/*
6475 		 * We don't allow multilevel ports for raw IP, so no need to
6476 		 * check for that here.
6477 		 */
6478 		zoneid = tsol_packet_to_zoneid(mp);
6479 	}
6480 
6481 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6482 	mutex_enter(&connfp->connf_lock);
6483 	connp = connfp->connf_head;
6484 	for (connp = connfp->connf_head; connp != NULL;
6485 	    connp = connp->conn_next) {
6486 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6487 		    zoneid) &&
6488 		    (!is_system_labeled() ||
6489 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6490 		    connp))) {
6491 			break;
6492 		}
6493 	}
6494 
6495 	if (connp == NULL) {
6496 		/*
6497 		 * No one bound to these addresses.  Is
6498 		 * there a client that wants all
6499 		 * unclaimed datagrams?
6500 		 */
6501 		mutex_exit(&connfp->connf_lock);
6502 		/*
6503 		 * Check for IPPROTO_ENCAP...
6504 		 */
6505 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6506 			/*
6507 			 * If an IPsec mblk is here on a multicast
6508 			 * tunnel (using ip_mroute stuff), check policy here,
6509 			 * THEN ship off to ip_mroute_decap().
6510 			 *
6511 			 * BTW,  If I match a configured IP-in-IP
6512 			 * tunnel, this path will not be reached, and
6513 			 * ip_mroute_decap will never be called.
6514 			 */
6515 			first_mp = ipsec_check_global_policy(first_mp, connp,
6516 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6517 			if (first_mp != NULL) {
6518 				if (mctl_present)
6519 					freeb(first_mp);
6520 				ip_mroute_decap(q, mp, ill);
6521 			} /* Else we already freed everything! */
6522 		} else {
6523 			/*
6524 			 * Otherwise send an ICMP protocol unreachable.
6525 			 */
6526 			if (ip_fanout_send_icmp(q, first_mp, flags,
6527 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6528 			    mctl_present, zoneid, ipst)) {
6529 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6530 			}
6531 		}
6532 		return;
6533 	}
6534 
6535 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6536 
6537 	CONN_INC_REF(connp);
6538 	first_connp = connp;
6539 
6540 	/*
6541 	 * Only send message to one tunnel driver by immediately
6542 	 * terminating the loop.
6543 	 */
6544 	connp = one_only ? NULL : connp->conn_next;
6545 
6546 	for (;;) {
6547 		while (connp != NULL) {
6548 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6549 			    flags, zoneid) &&
6550 			    (!is_system_labeled() ||
6551 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6552 			    shared_addr, connp)))
6553 				break;
6554 			connp = connp->conn_next;
6555 		}
6556 
6557 		/*
6558 		 * Copy the packet.
6559 		 */
6560 		if (connp == NULL ||
6561 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6562 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6563 			/*
6564 			 * No more interested clients or memory
6565 			 * allocation failed
6566 			 */
6567 			connp = first_connp;
6568 			break;
6569 		}
6570 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6571 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6572 		CONN_INC_REF(connp);
6573 		mutex_exit(&connfp->connf_lock);
6574 		rq = connp->conn_rq;
6575 
6576 		/*
6577 		 * Check flow control
6578 		 */
6579 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6580 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6581 			if (flags & IP_FF_RAWIP) {
6582 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6583 			} else {
6584 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6585 			}
6586 
6587 			freemsg(first_mp1);
6588 		} else {
6589 			/*
6590 			 * Don't enforce here if we're an actual tunnel -
6591 			 * let "tun" do it instead.
6592 			 */
6593 			if (!IPCL_IS_IPTUN(connp) &&
6594 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6595 			    secure)) {
6596 				first_mp1 = ipsec_check_inbound_policy
6597 				    (first_mp1, connp, ipha, NULL,
6598 				    mctl_present);
6599 			}
6600 			if (first_mp1 != NULL) {
6601 				int in_flags = 0;
6602 				/*
6603 				 * ip_fanout_proto also gets called from
6604 				 * icmp_inbound_error_fanout, in which case
6605 				 * the msg type is M_CTL.  Don't add info
6606 				 * in this case for the time being. In future
6607 				 * when there is a need for knowing the
6608 				 * inbound iface index for ICMP error msgs,
6609 				 * then this can be changed.
6610 				 */
6611 				if (connp->conn_recvif)
6612 					in_flags = IPF_RECVIF;
6613 				/*
6614 				 * The ULP may support IP_RECVPKTINFO for both
6615 				 * IP v4 and v6 so pass the appropriate argument
6616 				 * based on conn IP version.
6617 				 */
6618 				if (connp->conn_ip_recvpktinfo) {
6619 					if (connp->conn_af_isv6) {
6620 						/*
6621 						 * V6 only needs index
6622 						 */
6623 						in_flags |= IPF_RECVIF;
6624 					} else {
6625 						/*
6626 						 * V4 needs index +
6627 						 * matching address.
6628 						 */
6629 						in_flags |= IPF_RECVADDR;
6630 					}
6631 				}
6632 				if ((in_flags != 0) &&
6633 				    (mp->b_datap->db_type != M_CTL)) {
6634 					/*
6635 					 * the actual data will be
6636 					 * contained in b_cont upon
6637 					 * successful return of the
6638 					 * following call else
6639 					 * original mblk is returned
6640 					 */
6641 					ASSERT(recv_ill != NULL);
6642 					mp1 = ip_add_info(mp1, recv_ill,
6643 					    in_flags, IPCL_ZONEID(connp), ipst);
6644 				}
6645 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6646 				if (mctl_present)
6647 					freeb(first_mp1);
6648 				(connp->conn_recv)(connp, mp1, NULL);
6649 			}
6650 		}
6651 		mutex_enter(&connfp->connf_lock);
6652 		/* Follow the next pointer before releasing the conn. */
6653 		next_connp = connp->conn_next;
6654 		CONN_DEC_REF(connp);
6655 		connp = next_connp;
6656 	}
6657 
6658 	/* Last one.  Send it upstream. */
6659 	mutex_exit(&connfp->connf_lock);
6660 
6661 	/*
6662 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6663 	 * will be set to false.
6664 	 */
6665 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6666 		ill_index = ill->ill_phyint->phyint_ifindex;
6667 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6668 		if (mp == NULL) {
6669 			CONN_DEC_REF(connp);
6670 			if (mctl_present) {
6671 				freeb(first_mp);
6672 			}
6673 			return;
6674 		}
6675 	}
6676 
6677 	rq = connp->conn_rq;
6678 	/*
6679 	 * Check flow control
6680 	 */
6681 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6682 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6683 		if (flags & IP_FF_RAWIP) {
6684 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6685 		} else {
6686 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6687 		}
6688 
6689 		freemsg(first_mp);
6690 	} else {
6691 		if (IPCL_IS_IPTUN(connp)) {
6692 			/*
6693 			 * Tunneled packet.  We enforce policy in the tunnel
6694 			 * module itself.
6695 			 *
6696 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6697 			 * a policy check.
6698 			 * FIXME to use conn_recv for tun later.
6699 			 */
6700 			putnext(rq, first_mp);
6701 			CONN_DEC_REF(connp);
6702 			return;
6703 		}
6704 
6705 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6706 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6707 			    ipha, NULL, mctl_present);
6708 		}
6709 
6710 		if (first_mp != NULL) {
6711 			int in_flags = 0;
6712 
6713 			/*
6714 			 * ip_fanout_proto also gets called
6715 			 * from icmp_inbound_error_fanout, in
6716 			 * which case the msg type is M_CTL.
6717 			 * Don't add info in this case for time
6718 			 * being. In future when there is a
6719 			 * need for knowing the inbound iface
6720 			 * index for ICMP error msgs, then this
6721 			 * can be changed
6722 			 */
6723 			if (connp->conn_recvif)
6724 				in_flags = IPF_RECVIF;
6725 			if (connp->conn_ip_recvpktinfo) {
6726 				if (connp->conn_af_isv6) {
6727 					/*
6728 					 * V6 only needs index
6729 					 */
6730 					in_flags |= IPF_RECVIF;
6731 				} else {
6732 					/*
6733 					 * V4 needs index +
6734 					 * matching address.
6735 					 */
6736 					in_flags |= IPF_RECVADDR;
6737 				}
6738 			}
6739 			if ((in_flags != 0) &&
6740 			    (mp->b_datap->db_type != M_CTL)) {
6741 
6742 				/*
6743 				 * the actual data will be contained in
6744 				 * b_cont upon successful return
6745 				 * of the following call else original
6746 				 * mblk is returned
6747 				 */
6748 				ASSERT(recv_ill != NULL);
6749 				mp = ip_add_info(mp, recv_ill,
6750 				    in_flags, IPCL_ZONEID(connp), ipst);
6751 			}
6752 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6753 			(connp->conn_recv)(connp, mp, NULL);
6754 			if (mctl_present)
6755 				freeb(first_mp);
6756 		}
6757 	}
6758 	CONN_DEC_REF(connp);
6759 }
6760 
6761 /*
6762  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6763  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6764  * the correct squeue, in this case the same squeue as a valid listener with
6765  * no current connection state for the packet we are processing. The function
6766  * is called for synchronizing both IPv4 and IPv6.
6767  */
6768 void
6769 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6770     tcp_stack_t *tcps, conn_t *connp)
6771 {
6772 	mblk_t *rst_mp;
6773 	tcp_xmit_reset_event_t *eventp;
6774 
6775 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6776 
6777 	if (rst_mp == NULL) {
6778 		freemsg(mp);
6779 		return;
6780 	}
6781 
6782 	rst_mp->b_datap->db_type = M_PROTO;
6783 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6784 
6785 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6786 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6787 	eventp->tcp_xre_iphdrlen = hdrlen;
6788 	eventp->tcp_xre_zoneid = zoneid;
6789 	eventp->tcp_xre_tcps = tcps;
6790 
6791 	rst_mp->b_cont = mp;
6792 	mp = rst_mp;
6793 
6794 	/*
6795 	 * Increment the connref, this ref will be released by the squeue
6796 	 * framework.
6797 	 */
6798 	CONN_INC_REF(connp);
6799 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6800 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6801 }
6802 
6803 /*
6804  * Fanout for TCP packets
6805  * The caller puts <fport, lport> in the ports parameter.
6806  *
6807  * IPQoS Notes
6808  * Before sending it to the client, invoke IPPF processing.
6809  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6810  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6811  * ip_policy is false.
6812  */
6813 static void
6814 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6815     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6816 {
6817 	mblk_t  *first_mp;
6818 	boolean_t secure;
6819 	uint32_t ill_index;
6820 	int	ip_hdr_len;
6821 	tcph_t	*tcph;
6822 	boolean_t syn_present = B_FALSE;
6823 	conn_t	*connp;
6824 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6825 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6826 
6827 	ASSERT(recv_ill != NULL);
6828 
6829 	first_mp = mp;
6830 	if (mctl_present) {
6831 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6832 		mp = first_mp->b_cont;
6833 		secure = ipsec_in_is_secure(first_mp);
6834 		ASSERT(mp != NULL);
6835 	} else {
6836 		secure = B_FALSE;
6837 	}
6838 
6839 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6840 
6841 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6842 	    zoneid, ipst)) == NULL) {
6843 		/*
6844 		 * No connected connection or listener. Send a
6845 		 * TH_RST via tcp_xmit_listeners_reset.
6846 		 */
6847 
6848 		/* Initiate IPPf processing, if needed. */
6849 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6850 			uint32_t ill_index;
6851 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6852 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6853 			if (first_mp == NULL)
6854 				return;
6855 		}
6856 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6857 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6858 		    zoneid));
6859 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6860 		    ipst->ips_netstack->netstack_tcp, NULL);
6861 		return;
6862 	}
6863 
6864 	/*
6865 	 * Allocate the SYN for the TCP connection here itself
6866 	 */
6867 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6868 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6869 		if (IPCL_IS_TCP(connp)) {
6870 			squeue_t *sqp;
6871 
6872 			/*
6873 			 * If the queue belongs to a conn, and fused tcp
6874 			 * loopback is enabled, assign the eager's squeue
6875 			 * to be that of the active connect's. Note that
6876 			 * we don't check for IP_FF_LOOPBACK here since this
6877 			 * routine gets called only for loopback (unlike the
6878 			 * IPv6 counterpart).
6879 			 */
6880 			if (do_tcp_fusion &&
6881 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6882 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6883 			    !secure &&
6884 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6885 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6886 				sqp = Q_TO_CONN(q)->conn_sqp;
6887 			} else {
6888 				sqp = IP_SQUEUE_GET(lbolt);
6889 			}
6890 
6891 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6892 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6893 			syn_present = B_TRUE;
6894 		}
6895 	}
6896 
6897 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6898 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6899 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6900 		if ((flags & TH_RST) || (flags & TH_URG)) {
6901 			CONN_DEC_REF(connp);
6902 			freemsg(first_mp);
6903 			return;
6904 		}
6905 		if (flags & TH_ACK) {
6906 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6907 			    ipst->ips_netstack->netstack_tcp, connp);
6908 			CONN_DEC_REF(connp);
6909 			return;
6910 		}
6911 
6912 		CONN_DEC_REF(connp);
6913 		freemsg(first_mp);
6914 		return;
6915 	}
6916 
6917 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6918 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6919 		    NULL, mctl_present);
6920 		if (first_mp == NULL) {
6921 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6922 			CONN_DEC_REF(connp);
6923 			return;
6924 		}
6925 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6926 			ASSERT(syn_present);
6927 			if (mctl_present) {
6928 				ASSERT(first_mp != mp);
6929 				first_mp->b_datap->db_struioflag |=
6930 				    STRUIO_POLICY;
6931 			} else {
6932 				ASSERT(first_mp == mp);
6933 				mp->b_datap->db_struioflag &=
6934 				    ~STRUIO_EAGER;
6935 				mp->b_datap->db_struioflag |=
6936 				    STRUIO_POLICY;
6937 			}
6938 		} else {
6939 			/*
6940 			 * Discard first_mp early since we're dealing with a
6941 			 * fully-connected conn_t and tcp doesn't do policy in
6942 			 * this case.
6943 			 */
6944 			if (mctl_present) {
6945 				freeb(first_mp);
6946 				mctl_present = B_FALSE;
6947 			}
6948 			first_mp = mp;
6949 		}
6950 	}
6951 
6952 	/*
6953 	 * Initiate policy processing here if needed. If we get here from
6954 	 * icmp_inbound_error_fanout, ip_policy is false.
6955 	 */
6956 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6957 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6958 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6959 		if (mp == NULL) {
6960 			CONN_DEC_REF(connp);
6961 			if (mctl_present)
6962 				freeb(first_mp);
6963 			return;
6964 		} else if (mctl_present) {
6965 			ASSERT(first_mp != mp);
6966 			first_mp->b_cont = mp;
6967 		} else {
6968 			first_mp = mp;
6969 		}
6970 	}
6971 
6972 	/* Handle socket options. */
6973 	if (!syn_present &&
6974 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6975 		/* Add header */
6976 		ASSERT(recv_ill != NULL);
6977 		/*
6978 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6979 		 * IPF_RECVIF.
6980 		 */
6981 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6982 		    ipst);
6983 		if (mp == NULL) {
6984 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6985 			CONN_DEC_REF(connp);
6986 			if (mctl_present)
6987 				freeb(first_mp);
6988 			return;
6989 		} else if (mctl_present) {
6990 			/*
6991 			 * ip_add_info might return a new mp.
6992 			 */
6993 			ASSERT(first_mp != mp);
6994 			first_mp->b_cont = mp;
6995 		} else {
6996 			first_mp = mp;
6997 		}
6998 	}
6999 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
7000 	if (IPCL_IS_TCP(connp)) {
7001 		/* do not drain, certain use cases can blow the stack */
7002 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
7003 		    connp, SQ_NODRAIN, SQTAG_IP_FANOUT_TCP);
7004 	} else {
7005 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
7006 		(connp->conn_recv)(connp, first_mp, NULL);
7007 		CONN_DEC_REF(connp);
7008 	}
7009 }
7010 
7011 /*
7012  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
7013  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
7014  * is not consumed.
7015  *
7016  * One of four things can happen, all of which affect the passed-in mblk:
7017  *
7018  * 1.) ICMP messages that go through here just get returned TRUE.
7019  *
7020  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
7021  *
7022  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7023  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7024  *
7025  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7026  */
7027 static boolean_t
7028 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7029     ipsec_stack_t *ipss)
7030 {
7031 	int shift, plen, iph_len;
7032 	ipha_t *ipha;
7033 	udpha_t *udpha;
7034 	uint32_t *spi;
7035 	uint32_t esp_ports;
7036 	uint8_t *orptr;
7037 	boolean_t free_ire;
7038 
7039 	if (DB_TYPE(mp) == M_CTL) {
7040 		/*
7041 		 * ICMP message with UDP inside.  Don't bother stripping, just
7042 		 * send it up.
7043 		 *
7044 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7045 		 * to ignore errors set by ICMP anyway ('cause they might be
7046 		 * forged), but that's the app's decision, not ours.
7047 		 */
7048 
7049 		/* Bunch of reality checks for DEBUG kernels... */
7050 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7051 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7052 
7053 		return (B_TRUE);
7054 	}
7055 
7056 	ipha = (ipha_t *)mp->b_rptr;
7057 	iph_len = IPH_HDR_LENGTH(ipha);
7058 	plen = ntohs(ipha->ipha_length);
7059 
7060 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7061 		/*
7062 		 * Most likely a keepalive for the benefit of an intervening
7063 		 * NAT.  These aren't for us, per se, so drop it.
7064 		 *
7065 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7066 		 * byte packets (keepalives are 1-byte), but we'll drop them
7067 		 * also.
7068 		 */
7069 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7070 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7071 		return (B_FALSE);
7072 	}
7073 
7074 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7075 		/* might as well pull it all up - it might be ESP. */
7076 		if (!pullupmsg(mp, -1)) {
7077 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7078 			    DROPPER(ipss, ipds_esp_nomem),
7079 			    &ipss->ipsec_dropper);
7080 			return (B_FALSE);
7081 		}
7082 
7083 		ipha = (ipha_t *)mp->b_rptr;
7084 	}
7085 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7086 	if (*spi == 0) {
7087 		/* UDP packet - remove 0-spi. */
7088 		shift = sizeof (uint32_t);
7089 	} else {
7090 		/* ESP-in-UDP packet - reduce to ESP. */
7091 		ipha->ipha_protocol = IPPROTO_ESP;
7092 		shift = sizeof (udpha_t);
7093 	}
7094 
7095 	/* Fix IP header */
7096 	ipha->ipha_length = htons(plen - shift);
7097 	ipha->ipha_hdr_checksum = 0;
7098 
7099 	orptr = mp->b_rptr;
7100 	mp->b_rptr += shift;
7101 
7102 	udpha = (udpha_t *)(orptr + iph_len);
7103 	if (*spi == 0) {
7104 		ASSERT((uint8_t *)ipha == orptr);
7105 		udpha->uha_length = htons(plen - shift - iph_len);
7106 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7107 		esp_ports = 0;
7108 	} else {
7109 		esp_ports = *((uint32_t *)udpha);
7110 		ASSERT(esp_ports != 0);
7111 	}
7112 	ovbcopy(orptr, orptr + shift, iph_len);
7113 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7114 		ipha = (ipha_t *)(orptr + shift);
7115 
7116 		free_ire = (ire == NULL);
7117 		if (free_ire) {
7118 			/* Re-acquire ire. */
7119 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7120 			    ipss->ipsec_netstack->netstack_ip);
7121 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7122 				if (ire != NULL)
7123 					ire_refrele(ire);
7124 				/*
7125 				 * Do a regular freemsg(), as this is an IP
7126 				 * error (no local route) not an IPsec one.
7127 				 */
7128 				freemsg(mp);
7129 			}
7130 		}
7131 
7132 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7133 		if (free_ire)
7134 			ire_refrele(ire);
7135 	}
7136 
7137 	return (esp_ports == 0);
7138 }
7139 
7140 /*
7141  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7142  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7143  * Caller is responsible for dropping references to the conn, and freeing
7144  * first_mp.
7145  *
7146  * IPQoS Notes
7147  * Before sending it to the client, invoke IPPF processing. Policy processing
7148  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7149  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7150  * ip_wput_local, ip_policy is false.
7151  */
7152 static void
7153 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7154     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7155     boolean_t ip_policy)
7156 {
7157 	boolean_t	mctl_present = (first_mp != NULL);
7158 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7159 	uint32_t	ill_index;
7160 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7161 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7162 
7163 	ASSERT(ill != NULL);
7164 
7165 	if (mctl_present)
7166 		first_mp->b_cont = mp;
7167 	else
7168 		first_mp = mp;
7169 
7170 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7171 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7172 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7173 		freemsg(first_mp);
7174 		return;
7175 	}
7176 
7177 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7178 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7179 		    NULL, mctl_present);
7180 		/* Freed by ipsec_check_inbound_policy(). */
7181 		if (first_mp == NULL) {
7182 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7183 			return;
7184 		}
7185 	}
7186 	if (mctl_present)
7187 		freeb(first_mp);
7188 
7189 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7190 	if (connp->conn_udp->udp_nat_t_endpoint) {
7191 		if (mctl_present) {
7192 			/* mctl_present *shouldn't* happen. */
7193 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7194 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7195 			    &ipss->ipsec_dropper);
7196 			return;
7197 		}
7198 
7199 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7200 			return;
7201 	}
7202 
7203 	/* Handle options. */
7204 	if (connp->conn_recvif)
7205 		in_flags = IPF_RECVIF;
7206 	/*
7207 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7208 	 * passed to ip_add_info is based on IP version of connp.
7209 	 */
7210 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7211 		if (connp->conn_af_isv6) {
7212 			/*
7213 			 * V6 only needs index
7214 			 */
7215 			in_flags |= IPF_RECVIF;
7216 		} else {
7217 			/*
7218 			 * V4 needs index + matching address.
7219 			 */
7220 			in_flags |= IPF_RECVADDR;
7221 		}
7222 	}
7223 
7224 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7225 		in_flags |= IPF_RECVSLLA;
7226 
7227 	/*
7228 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7229 	 * freed if the packet is dropped. The caller will do so.
7230 	 */
7231 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7232 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7233 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7234 		if (mp == NULL) {
7235 			return;
7236 		}
7237 	}
7238 	if ((in_flags != 0) &&
7239 	    (mp->b_datap->db_type != M_CTL)) {
7240 		/*
7241 		 * The actual data will be contained in b_cont
7242 		 * upon successful return of the following call
7243 		 * else original mblk is returned
7244 		 */
7245 		ASSERT(recv_ill != NULL);
7246 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7247 		    ipst);
7248 	}
7249 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7250 	/* Send it upstream */
7251 	(connp->conn_recv)(connp, mp, NULL);
7252 }
7253 
7254 /*
7255  * Fanout for UDP packets.
7256  * The caller puts <fport, lport> in the ports parameter.
7257  *
7258  * If SO_REUSEADDR is set all multicast and broadcast packets
7259  * will be delivered to all streams bound to the same port.
7260  *
7261  * Zones notes:
7262  * Multicast and broadcast packets will be distributed to streams in all zones.
7263  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7264  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7265  * packets. To maintain this behavior with multiple zones, the conns are grouped
7266  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7267  * each zone. If unset, all the following conns in the same zone are skipped.
7268  */
7269 static void
7270 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7271     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7272     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7273 {
7274 	uint32_t	dstport, srcport;
7275 	ipaddr_t	dst;
7276 	mblk_t		*first_mp;
7277 	boolean_t	secure;
7278 	in6_addr_t	v6src;
7279 	conn_t		*connp;
7280 	connf_t		*connfp;
7281 	conn_t		*first_connp;
7282 	conn_t		*next_connp;
7283 	mblk_t		*mp1, *first_mp1;
7284 	ipaddr_t	src;
7285 	zoneid_t	last_zoneid;
7286 	boolean_t	reuseaddr;
7287 	boolean_t	shared_addr;
7288 	boolean_t	unlabeled;
7289 	ip_stack_t	*ipst;
7290 
7291 	ASSERT(recv_ill != NULL);
7292 	ipst = recv_ill->ill_ipst;
7293 
7294 	first_mp = mp;
7295 	if (mctl_present) {
7296 		mp = first_mp->b_cont;
7297 		first_mp->b_cont = NULL;
7298 		secure = ipsec_in_is_secure(first_mp);
7299 		ASSERT(mp != NULL);
7300 	} else {
7301 		first_mp = NULL;
7302 		secure = B_FALSE;
7303 	}
7304 
7305 	/* Extract ports in net byte order */
7306 	dstport = htons(ntohl(ports) & 0xFFFF);
7307 	srcport = htons(ntohl(ports) >> 16);
7308 	dst = ipha->ipha_dst;
7309 	src = ipha->ipha_src;
7310 
7311 	unlabeled = B_FALSE;
7312 	if (is_system_labeled())
7313 		/* Cred cannot be null on IPv4 */
7314 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7315 		    TSLF_UNLABELED) != 0;
7316 	shared_addr = (zoneid == ALL_ZONES);
7317 	if (shared_addr) {
7318 		/*
7319 		 * No need to handle exclusive-stack zones since ALL_ZONES
7320 		 * only applies to the shared stack.
7321 		 */
7322 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7323 		/*
7324 		 * If no shared MLP is found, tsol_mlp_findzone returns
7325 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7326 		 * search for the zone based on the packet label.
7327 		 *
7328 		 * If there is such a zone, we prefer to find a
7329 		 * connection in it.  Otherwise, we look for a
7330 		 * MAC-exempt connection in any zone whose label
7331 		 * dominates the default label on the packet.
7332 		 */
7333 		if (zoneid == ALL_ZONES)
7334 			zoneid = tsol_packet_to_zoneid(mp);
7335 		else
7336 			unlabeled = B_FALSE;
7337 	}
7338 
7339 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7340 	mutex_enter(&connfp->connf_lock);
7341 	connp = connfp->connf_head;
7342 	if (!broadcast && !CLASSD(dst)) {
7343 		/*
7344 		 * Not broadcast or multicast. Send to the one (first)
7345 		 * client we find. No need to check conn_wantpacket()
7346 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7347 		 * IPv4 unicast packets.
7348 		 */
7349 		while ((connp != NULL) &&
7350 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7351 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7352 		    !(unlabeled && connp->conn_mac_exempt && shared_addr)))) {
7353 			/*
7354 			 * We keep searching since the conn did not match,
7355 			 * or its zone did not match and it is not either
7356 			 * an allzones conn or a mac exempt conn (if the
7357 			 * sender is unlabeled.)
7358 			 */
7359 			connp = connp->conn_next;
7360 		}
7361 
7362 		if (connp == NULL ||
7363 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7364 			goto notfound;
7365 
7366 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7367 
7368 		if (is_system_labeled() &&
7369 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7370 		    connp))
7371 			goto notfound;
7372 
7373 		CONN_INC_REF(connp);
7374 		mutex_exit(&connfp->connf_lock);
7375 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7376 		    flags, recv_ill, ip_policy);
7377 		IP_STAT(ipst, ip_udp_fannorm);
7378 		CONN_DEC_REF(connp);
7379 		return;
7380 	}
7381 
7382 	/*
7383 	 * Broadcast and multicast case
7384 	 *
7385 	 * Need to check conn_wantpacket().
7386 	 * If SO_REUSEADDR has been set on the first we send the
7387 	 * packet to all clients that have joined the group and
7388 	 * match the port.
7389 	 */
7390 
7391 	while (connp != NULL) {
7392 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7393 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7394 		    (!is_system_labeled() ||
7395 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7396 		    connp)))
7397 			break;
7398 		connp = connp->conn_next;
7399 	}
7400 
7401 	if (connp == NULL ||
7402 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7403 		goto notfound;
7404 
7405 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7406 
7407 	first_connp = connp;
7408 	/*
7409 	 * When SO_REUSEADDR is not set, send the packet only to the first
7410 	 * matching connection in its zone by keeping track of the zoneid.
7411 	 */
7412 	reuseaddr = first_connp->conn_reuseaddr;
7413 	last_zoneid = first_connp->conn_zoneid;
7414 
7415 	CONN_INC_REF(connp);
7416 	connp = connp->conn_next;
7417 	for (;;) {
7418 		while (connp != NULL) {
7419 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7420 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7421 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7422 			    (!is_system_labeled() ||
7423 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7424 			    shared_addr, connp)))
7425 				break;
7426 			connp = connp->conn_next;
7427 		}
7428 		/*
7429 		 * Just copy the data part alone. The mctl part is
7430 		 * needed just for verifying policy and it is never
7431 		 * sent up.
7432 		 */
7433 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7434 		    ((mp1 = copymsg(mp)) == NULL))) {
7435 			/*
7436 			 * No more interested clients or memory
7437 			 * allocation failed
7438 			 */
7439 			connp = first_connp;
7440 			break;
7441 		}
7442 		if (connp->conn_zoneid != last_zoneid) {
7443 			/*
7444 			 * Update the zoneid so that the packet isn't sent to
7445 			 * any more conns in the same zone unless SO_REUSEADDR
7446 			 * is set.
7447 			 */
7448 			reuseaddr = connp->conn_reuseaddr;
7449 			last_zoneid = connp->conn_zoneid;
7450 		}
7451 		if (first_mp != NULL) {
7452 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7453 			    ipsec_info_type == IPSEC_IN);
7454 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7455 			    ipst->ips_netstack);
7456 			if (first_mp1 == NULL) {
7457 				freemsg(mp1);
7458 				connp = first_connp;
7459 				break;
7460 			}
7461 		} else {
7462 			first_mp1 = NULL;
7463 		}
7464 		CONN_INC_REF(connp);
7465 		mutex_exit(&connfp->connf_lock);
7466 		/*
7467 		 * IPQoS notes: We don't send the packet for policy
7468 		 * processing here, will do it for the last one (below).
7469 		 * i.e. we do it per-packet now, but if we do policy
7470 		 * processing per-conn, then we would need to do it
7471 		 * here too.
7472 		 */
7473 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7474 		    ipha, flags, recv_ill, B_FALSE);
7475 		mutex_enter(&connfp->connf_lock);
7476 		/* Follow the next pointer before releasing the conn. */
7477 		next_connp = connp->conn_next;
7478 		IP_STAT(ipst, ip_udp_fanmb);
7479 		CONN_DEC_REF(connp);
7480 		connp = next_connp;
7481 	}
7482 
7483 	/* Last one.  Send it upstream. */
7484 	mutex_exit(&connfp->connf_lock);
7485 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7486 	    recv_ill, ip_policy);
7487 	IP_STAT(ipst, ip_udp_fanmb);
7488 	CONN_DEC_REF(connp);
7489 	return;
7490 
7491 notfound:
7492 
7493 	mutex_exit(&connfp->connf_lock);
7494 	IP_STAT(ipst, ip_udp_fanothers);
7495 	/*
7496 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7497 	 * have already been matched above, since they live in the IPv4
7498 	 * fanout tables. This implies we only need to
7499 	 * check for IPv6 in6addr_any endpoints here.
7500 	 * Thus we compare using ipv6_all_zeros instead of the destination
7501 	 * address, except for the multicast group membership lookup which
7502 	 * uses the IPv4 destination.
7503 	 */
7504 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7505 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7506 	mutex_enter(&connfp->connf_lock);
7507 	connp = connfp->connf_head;
7508 	if (!broadcast && !CLASSD(dst)) {
7509 		while (connp != NULL) {
7510 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7511 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7512 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7513 			    !connp->conn_ipv6_v6only)
7514 				break;
7515 			connp = connp->conn_next;
7516 		}
7517 
7518 		if (connp != NULL && is_system_labeled() &&
7519 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7520 		    connp))
7521 			connp = NULL;
7522 
7523 		if (connp == NULL ||
7524 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7525 			/*
7526 			 * No one bound to this port.  Is
7527 			 * there a client that wants all
7528 			 * unclaimed datagrams?
7529 			 */
7530 			mutex_exit(&connfp->connf_lock);
7531 
7532 			if (mctl_present)
7533 				first_mp->b_cont = mp;
7534 			else
7535 				first_mp = mp;
7536 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7537 			    connf_head != NULL) {
7538 				ip_fanout_proto(q, first_mp, ill, ipha,
7539 				    flags | IP_FF_RAWIP, mctl_present,
7540 				    ip_policy, recv_ill, zoneid);
7541 			} else {
7542 				if (ip_fanout_send_icmp(q, first_mp, flags,
7543 				    ICMP_DEST_UNREACHABLE,
7544 				    ICMP_PORT_UNREACHABLE,
7545 				    mctl_present, zoneid, ipst)) {
7546 					BUMP_MIB(ill->ill_ip_mib,
7547 					    udpIfStatsNoPorts);
7548 				}
7549 			}
7550 			return;
7551 		}
7552 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7553 
7554 		CONN_INC_REF(connp);
7555 		mutex_exit(&connfp->connf_lock);
7556 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7557 		    flags, recv_ill, ip_policy);
7558 		CONN_DEC_REF(connp);
7559 		return;
7560 	}
7561 	/*
7562 	 * IPv4 multicast packet being delivered to an AF_INET6
7563 	 * in6addr_any endpoint.
7564 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7565 	 * and not conn_wantpacket_v6() since any multicast membership is
7566 	 * for an IPv4-mapped multicast address.
7567 	 * The packet is sent to all clients in all zones that have joined the
7568 	 * group and match the port.
7569 	 */
7570 	while (connp != NULL) {
7571 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7572 		    srcport, v6src) &&
7573 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7574 		    (!is_system_labeled() ||
7575 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7576 		    connp)))
7577 			break;
7578 		connp = connp->conn_next;
7579 	}
7580 
7581 	if (connp == NULL ||
7582 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7583 		/*
7584 		 * No one bound to this port.  Is
7585 		 * there a client that wants all
7586 		 * unclaimed datagrams?
7587 		 */
7588 		mutex_exit(&connfp->connf_lock);
7589 
7590 		if (mctl_present)
7591 			first_mp->b_cont = mp;
7592 		else
7593 			first_mp = mp;
7594 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7595 		    NULL) {
7596 			ip_fanout_proto(q, first_mp, ill, ipha,
7597 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7598 			    recv_ill, zoneid);
7599 		} else {
7600 			/*
7601 			 * We used to attempt to send an icmp error here, but
7602 			 * since this is known to be a multicast packet
7603 			 * and we don't send icmp errors in response to
7604 			 * multicast, just drop the packet and give up sooner.
7605 			 */
7606 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7607 			freemsg(first_mp);
7608 		}
7609 		return;
7610 	}
7611 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7612 
7613 	first_connp = connp;
7614 
7615 	CONN_INC_REF(connp);
7616 	connp = connp->conn_next;
7617 	for (;;) {
7618 		while (connp != NULL) {
7619 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7620 			    ipv6_all_zeros, srcport, v6src) &&
7621 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7622 			    (!is_system_labeled() ||
7623 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7624 			    shared_addr, connp)))
7625 				break;
7626 			connp = connp->conn_next;
7627 		}
7628 		/*
7629 		 * Just copy the data part alone. The mctl part is
7630 		 * needed just for verifying policy and it is never
7631 		 * sent up.
7632 		 */
7633 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7634 		    ((mp1 = copymsg(mp)) == NULL))) {
7635 			/*
7636 			 * No more intested clients or memory
7637 			 * allocation failed
7638 			 */
7639 			connp = first_connp;
7640 			break;
7641 		}
7642 		if (first_mp != NULL) {
7643 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7644 			    ipsec_info_type == IPSEC_IN);
7645 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7646 			    ipst->ips_netstack);
7647 			if (first_mp1 == NULL) {
7648 				freemsg(mp1);
7649 				connp = first_connp;
7650 				break;
7651 			}
7652 		} else {
7653 			first_mp1 = NULL;
7654 		}
7655 		CONN_INC_REF(connp);
7656 		mutex_exit(&connfp->connf_lock);
7657 		/*
7658 		 * IPQoS notes: We don't send the packet for policy
7659 		 * processing here, will do it for the last one (below).
7660 		 * i.e. we do it per-packet now, but if we do policy
7661 		 * processing per-conn, then we would need to do it
7662 		 * here too.
7663 		 */
7664 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7665 		    ipha, flags, recv_ill, B_FALSE);
7666 		mutex_enter(&connfp->connf_lock);
7667 		/* Follow the next pointer before releasing the conn. */
7668 		next_connp = connp->conn_next;
7669 		CONN_DEC_REF(connp);
7670 		connp = next_connp;
7671 	}
7672 
7673 	/* Last one.  Send it upstream. */
7674 	mutex_exit(&connfp->connf_lock);
7675 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7676 	    recv_ill, ip_policy);
7677 	CONN_DEC_REF(connp);
7678 }
7679 
7680 /*
7681  * Complete the ip_wput header so that it
7682  * is possible to generate ICMP
7683  * errors.
7684  */
7685 int
7686 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7687 {
7688 	ire_t *ire;
7689 
7690 	if (ipha->ipha_src == INADDR_ANY) {
7691 		ire = ire_lookup_local(zoneid, ipst);
7692 		if (ire == NULL) {
7693 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7694 			return (1);
7695 		}
7696 		ipha->ipha_src = ire->ire_addr;
7697 		ire_refrele(ire);
7698 	}
7699 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7700 	ipha->ipha_hdr_checksum = 0;
7701 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7702 	return (0);
7703 }
7704 
7705 /*
7706  * Nobody should be sending
7707  * packets up this stream
7708  */
7709 static void
7710 ip_lrput(queue_t *q, mblk_t *mp)
7711 {
7712 	mblk_t *mp1;
7713 
7714 	switch (mp->b_datap->db_type) {
7715 	case M_FLUSH:
7716 		/* Turn around */
7717 		if (*mp->b_rptr & FLUSHW) {
7718 			*mp->b_rptr &= ~FLUSHR;
7719 			qreply(q, mp);
7720 			return;
7721 		}
7722 		break;
7723 	}
7724 	/* Could receive messages that passed through ar_rput */
7725 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7726 		mp1->b_prev = mp1->b_next = NULL;
7727 	freemsg(mp);
7728 }
7729 
7730 /* Nobody should be sending packets down this stream */
7731 /* ARGSUSED */
7732 void
7733 ip_lwput(queue_t *q, mblk_t *mp)
7734 {
7735 	freemsg(mp);
7736 }
7737 
7738 /*
7739  * Move the first hop in any source route to ipha_dst and remove that part of
7740  * the source route.  Called by other protocols.  Errors in option formatting
7741  * are ignored - will be handled by ip_wput_options Return the final
7742  * destination (either ipha_dst or the last entry in a source route.)
7743  */
7744 ipaddr_t
7745 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7746 {
7747 	ipoptp_t	opts;
7748 	uchar_t		*opt;
7749 	uint8_t		optval;
7750 	uint8_t		optlen;
7751 	ipaddr_t	dst;
7752 	int		i;
7753 	ire_t		*ire;
7754 	ip_stack_t	*ipst = ns->netstack_ip;
7755 
7756 	ip2dbg(("ip_massage_options\n"));
7757 	dst = ipha->ipha_dst;
7758 	for (optval = ipoptp_first(&opts, ipha);
7759 	    optval != IPOPT_EOL;
7760 	    optval = ipoptp_next(&opts)) {
7761 		opt = opts.ipoptp_cur;
7762 		switch (optval) {
7763 			uint8_t off;
7764 		case IPOPT_SSRR:
7765 		case IPOPT_LSRR:
7766 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7767 				ip1dbg(("ip_massage_options: bad src route\n"));
7768 				break;
7769 			}
7770 			optlen = opts.ipoptp_len;
7771 			off = opt[IPOPT_OFFSET];
7772 			off--;
7773 		redo_srr:
7774 			if (optlen < IP_ADDR_LEN ||
7775 			    off > optlen - IP_ADDR_LEN) {
7776 				/* End of source route */
7777 				ip1dbg(("ip_massage_options: end of SR\n"));
7778 				break;
7779 			}
7780 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7781 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7782 			    ntohl(dst)));
7783 			/*
7784 			 * Check if our address is present more than
7785 			 * once as consecutive hops in source route.
7786 			 * XXX verify per-interface ip_forwarding
7787 			 * for source route?
7788 			 */
7789 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7790 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7791 			if (ire != NULL) {
7792 				ire_refrele(ire);
7793 				off += IP_ADDR_LEN;
7794 				goto redo_srr;
7795 			}
7796 			if (dst == htonl(INADDR_LOOPBACK)) {
7797 				ip1dbg(("ip_massage_options: loopback addr in "
7798 				    "source route!\n"));
7799 				break;
7800 			}
7801 			/*
7802 			 * Update ipha_dst to be the first hop and remove the
7803 			 * first hop from the source route (by overwriting
7804 			 * part of the option with NOP options).
7805 			 */
7806 			ipha->ipha_dst = dst;
7807 			/* Put the last entry in dst */
7808 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7809 			    3;
7810 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7811 
7812 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7813 			    ntohl(dst)));
7814 			/* Move down and overwrite */
7815 			opt[IP_ADDR_LEN] = opt[0];
7816 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7817 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7818 			for (i = 0; i < IP_ADDR_LEN; i++)
7819 				opt[i] = IPOPT_NOP;
7820 			break;
7821 		}
7822 	}
7823 	return (dst);
7824 }
7825 
7826 /*
7827  * Return the network mask
7828  * associated with the specified address.
7829  */
7830 ipaddr_t
7831 ip_net_mask(ipaddr_t addr)
7832 {
7833 	uchar_t	*up = (uchar_t *)&addr;
7834 	ipaddr_t mask = 0;
7835 	uchar_t	*maskp = (uchar_t *)&mask;
7836 
7837 #if defined(__i386) || defined(__amd64)
7838 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7839 #endif
7840 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7841 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7842 #endif
7843 	if (CLASSD(addr)) {
7844 		maskp[0] = 0xF0;
7845 		return (mask);
7846 	}
7847 
7848 	/* We assume Class E default netmask to be 32 */
7849 	if (CLASSE(addr))
7850 		return (0xffffffffU);
7851 
7852 	if (addr == 0)
7853 		return (0);
7854 	maskp[0] = 0xFF;
7855 	if ((up[0] & 0x80) == 0)
7856 		return (mask);
7857 
7858 	maskp[1] = 0xFF;
7859 	if ((up[0] & 0xC0) == 0x80)
7860 		return (mask);
7861 
7862 	maskp[2] = 0xFF;
7863 	if ((up[0] & 0xE0) == 0xC0)
7864 		return (mask);
7865 
7866 	/* Otherwise return no mask */
7867 	return ((ipaddr_t)0);
7868 }
7869 
7870 /*
7871  * Helper ill lookup function used by IPsec.
7872  */
7873 ill_t *
7874 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7875 {
7876 	ill_t *ret_ill;
7877 
7878 	ASSERT(ifindex != 0);
7879 
7880 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7881 	    ipst);
7882 	if (ret_ill == NULL) {
7883 		if (isv6) {
7884 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7885 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7886 			    ifindex));
7887 		} else {
7888 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7889 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7890 			    ifindex));
7891 		}
7892 		freemsg(first_mp);
7893 		return (NULL);
7894 	}
7895 	return (ret_ill);
7896 }
7897 
7898 /*
7899  * IPv4 -
7900  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7901  * out a packet to a destination address for which we do not have specific
7902  * (or sufficient) routing information.
7903  *
7904  * NOTE : These are the scopes of some of the variables that point at IRE,
7905  *	  which needs to be followed while making any future modifications
7906  *	  to avoid memory leaks.
7907  *
7908  *	- ire and sire are the entries looked up initially by
7909  *	  ire_ftable_lookup.
7910  *	- ipif_ire is used to hold the interface ire associated with
7911  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7912  *	  it before branching out to error paths.
7913  *	- save_ire is initialized before ire_create, so that ire returned
7914  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7915  *	  before breaking out of the switch.
7916  *
7917  *	Thus on failures, we have to REFRELE only ire and sire, if they
7918  *	are not NULL.
7919  */
7920 void
7921 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7922     zoneid_t zoneid, ip_stack_t *ipst)
7923 {
7924 	areq_t	*areq;
7925 	ipaddr_t gw = 0;
7926 	ire_t	*ire = NULL;
7927 	mblk_t	*res_mp;
7928 	ipaddr_t *addrp;
7929 	ipaddr_t nexthop_addr;
7930 	ipif_t  *src_ipif = NULL;
7931 	ill_t	*dst_ill = NULL;
7932 	ipha_t  *ipha;
7933 	ire_t	*sire = NULL;
7934 	mblk_t	*first_mp;
7935 	ire_t	*save_ire;
7936 	ushort_t ire_marks = 0;
7937 	boolean_t mctl_present;
7938 	ipsec_out_t *io;
7939 	mblk_t	*saved_mp;
7940 	mblk_t	*copy_mp = NULL;
7941 	mblk_t	*xmit_mp = NULL;
7942 	ipaddr_t save_dst;
7943 	uint32_t multirt_flags =
7944 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7945 	boolean_t multirt_is_resolvable;
7946 	boolean_t multirt_resolve_next;
7947 	boolean_t unspec_src;
7948 	boolean_t ip_nexthop = B_FALSE;
7949 	tsol_ire_gw_secattr_t *attrp = NULL;
7950 	tsol_gcgrp_t *gcgrp = NULL;
7951 	tsol_gcgrp_addr_t ga;
7952 	int multirt_res_failures = 0;
7953 	int multirt_res_attempts = 0;
7954 	int multirt_already_resolved = 0;
7955 	boolean_t multirt_no_icmp_error = B_FALSE;
7956 
7957 	if (ip_debug > 2) {
7958 		/* ip1dbg */
7959 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7960 	}
7961 
7962 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7963 	if (mctl_present) {
7964 		io = (ipsec_out_t *)first_mp->b_rptr;
7965 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7966 		ASSERT(zoneid == io->ipsec_out_zoneid);
7967 		ASSERT(zoneid != ALL_ZONES);
7968 	}
7969 
7970 	ipha = (ipha_t *)mp->b_rptr;
7971 
7972 	/* All multicast lookups come through ip_newroute_ipif() */
7973 	if (CLASSD(dst)) {
7974 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7975 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7976 		freemsg(first_mp);
7977 		return;
7978 	}
7979 
7980 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7981 		ip_nexthop = B_TRUE;
7982 		nexthop_addr = io->ipsec_out_nexthop_addr;
7983 	}
7984 	/*
7985 	 * If this IRE is created for forwarding or it is not for
7986 	 * traffic for congestion controlled protocols, mark it as temporary.
7987 	 */
7988 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7989 		ire_marks |= IRE_MARK_TEMPORARY;
7990 
7991 	/*
7992 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7993 	 * chain until it gets the most specific information available.
7994 	 * For example, we know that there is no IRE_CACHE for this dest,
7995 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7996 	 * ire_ftable_lookup will look up the gateway, etc.
7997 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7998 	 * to the destination, of equal netmask length in the forward table,
7999 	 * will be recursively explored. If no information is available
8000 	 * for the final gateway of that route, we force the returned ire
8001 	 * to be equal to sire using MATCH_IRE_PARENT.
8002 	 * At least, in this case we have a starting point (in the buckets)
8003 	 * to look for other routes to the destination in the forward table.
8004 	 * This is actually used only for multirouting, where a list
8005 	 * of routes has to be processed in sequence.
8006 	 *
8007 	 * In the process of coming up with the most specific information,
8008 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8009 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8010 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8011 	 * Two caveats when handling incomplete ire's in ip_newroute:
8012 	 * - we should be careful when accessing its ire_nce (specifically
8013 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8014 	 * - not all legacy code path callers are prepared to handle
8015 	 *   incomplete ire's, so we should not create/add incomplete
8016 	 *   ire_cache entries here. (See discussion about temporary solution
8017 	 *   further below).
8018 	 *
8019 	 * In order to minimize packet dropping, and to preserve existing
8020 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8021 	 * gateway, and instead use the IF_RESOLVER ire to send out
8022 	 * another request to ARP (this is achieved by passing the
8023 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8024 	 * arp response comes back in ip_wput_nondata, we will create
8025 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8026 	 *
8027 	 * Note that this is a temporary solution; the correct solution is
8028 	 * to create an incomplete  per-dst ire_cache entry, and send the
8029 	 * packet out when the gw's nce is resolved. In order to achieve this,
8030 	 * all packet processing must have been completed prior to calling
8031 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8032 	 * to be modified to accomodate this solution.
8033 	 */
8034 	if (ip_nexthop) {
8035 		/*
8036 		 * The first time we come here, we look for an IRE_INTERFACE
8037 		 * entry for the specified nexthop, set the dst to be the
8038 		 * nexthop address and create an IRE_CACHE entry for the
8039 		 * nexthop. The next time around, we are able to find an
8040 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8041 		 * nexthop address and create an IRE_CACHE entry for the
8042 		 * destination address via the specified nexthop.
8043 		 */
8044 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8045 		    msg_getlabel(mp), ipst);
8046 		if (ire != NULL) {
8047 			gw = nexthop_addr;
8048 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8049 		} else {
8050 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8051 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8052 			    msg_getlabel(mp),
8053 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8054 			    ipst);
8055 			if (ire != NULL) {
8056 				dst = nexthop_addr;
8057 			}
8058 		}
8059 	} else {
8060 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8061 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8062 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8063 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8064 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8065 		    ipst);
8066 	}
8067 
8068 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8069 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8070 
8071 	/*
8072 	 * This loop is run only once in most cases.
8073 	 * We loop to resolve further routes only when the destination
8074 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8075 	 */
8076 	do {
8077 		/* Clear the previous iteration's values */
8078 		if (src_ipif != NULL) {
8079 			ipif_refrele(src_ipif);
8080 			src_ipif = NULL;
8081 		}
8082 		if (dst_ill != NULL) {
8083 			ill_refrele(dst_ill);
8084 			dst_ill = NULL;
8085 		}
8086 
8087 		multirt_resolve_next = B_FALSE;
8088 		/*
8089 		 * We check if packets have to be multirouted.
8090 		 * In this case, given the current <ire, sire> couple,
8091 		 * we look for the next suitable <ire, sire>.
8092 		 * This check is done in ire_multirt_lookup(),
8093 		 * which applies various criteria to find the next route
8094 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8095 		 * unchanged if it detects it has not been tried yet.
8096 		 */
8097 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8098 			ip3dbg(("ip_newroute: starting next_resolution "
8099 			    "with first_mp %p, tag %d\n",
8100 			    (void *)first_mp,
8101 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8102 
8103 			ASSERT(sire != NULL);
8104 			multirt_is_resolvable =
8105 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8106 			    &multirt_already_resolved, msg_getlabel(mp), ipst);
8107 
8108 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8109 			    "multirt_already_resolved %d, "
8110 			    "multirt_res_attempts %d, multirt_res_failures %d, "
8111 			    "ire %p, sire %p\n", multirt_is_resolvable,
8112 			    multirt_already_resolved, multirt_res_attempts,
8113 			    multirt_res_failures, (void *)ire, (void *)sire));
8114 
8115 			if (!multirt_is_resolvable) {
8116 				/*
8117 				 * No more multirt route to resolve; give up
8118 				 * (all routes resolved or no more
8119 				 * resolvable routes).
8120 				 */
8121 				if (ire != NULL) {
8122 					ire_refrele(ire);
8123 					ire = NULL;
8124 				}
8125 				/*
8126 				 * Generate ICMP error only if all attempts to
8127 				 * resolve multirt route failed and there is no
8128 				 * already resolved one.  Don't generate ICMP
8129 				 * error when:
8130 				 *
8131 				 *  1) there was no attempt to resolve
8132 				 *  2) at least one attempt passed
8133 				 *  3) a multirt route is already resolved
8134 				 *
8135 				 *  Case 1) may occur due to multiple
8136 				 *    resolution attempts during single
8137 				 *    ip_multirt_resolution_interval.
8138 				 *
8139 				 *  Case 2-3) means that CGTP destination is
8140 				 *    reachable via one link so we don't want to
8141 				 *    generate ICMP host unreachable error.
8142 				 */
8143 				if (multirt_res_attempts == 0 ||
8144 				    multirt_res_failures <
8145 				    multirt_res_attempts ||
8146 				    multirt_already_resolved > 0)
8147 					multirt_no_icmp_error = B_TRUE;
8148 			} else {
8149 				ASSERT(sire != NULL);
8150 				ASSERT(ire != NULL);
8151 
8152 				multirt_res_attempts++;
8153 			}
8154 		}
8155 
8156 		if (ire == NULL) {
8157 			if (ip_debug > 3) {
8158 				/* ip2dbg */
8159 				pr_addr_dbg("ip_newroute: "
8160 				    "can't resolve %s\n", AF_INET, &dst);
8161 			}
8162 			ip3dbg(("ip_newroute: "
8163 			    "ire %p, sire %p, multirt_no_icmp_error %d\n",
8164 			    (void *)ire, (void *)sire,
8165 			    (int)multirt_no_icmp_error));
8166 
8167 			if (sire != NULL) {
8168 				ire_refrele(sire);
8169 				sire = NULL;
8170 			}
8171 
8172 			if (multirt_no_icmp_error) {
8173 				/* There is no need to report an ICMP error. */
8174 				MULTIRT_DEBUG_UNTAG(first_mp);
8175 				freemsg(first_mp);
8176 				return;
8177 			}
8178 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8179 			    RTA_DST, ipst);
8180 			goto icmp_err_ret;
8181 		}
8182 
8183 		/*
8184 		 * Verify that the returned IRE does not have either
8185 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8186 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8187 		 */
8188 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8189 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8190 			goto icmp_err_ret;
8191 		}
8192 		/*
8193 		 * Increment the ire_ob_pkt_count field for ire if it is an
8194 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8195 		 * increment the same for the parent IRE, sire, if it is some
8196 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8197 		 */
8198 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8199 			UPDATE_OB_PKT_COUNT(ire);
8200 			ire->ire_last_used_time = lbolt;
8201 		}
8202 
8203 		if (sire != NULL) {
8204 			gw = sire->ire_gateway_addr;
8205 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8206 			    IRE_INTERFACE)) == 0);
8207 			UPDATE_OB_PKT_COUNT(sire);
8208 			sire->ire_last_used_time = lbolt;
8209 		}
8210 		/*
8211 		 * We have a route to reach the destination.  Find the
8212 		 * appropriate ill, then get a source address using
8213 		 * ipif_select_source().
8214 		 *
8215 		 * If we are here trying to create an IRE_CACHE for an offlink
8216 		 * destination and have an IRE_CACHE entry for VNI, then use
8217 		 * ire_stq instead since VNI's queue is a black hole.
8218 		 */
8219 		if ((ire->ire_type == IRE_CACHE) &&
8220 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8221 			dst_ill = ire->ire_stq->q_ptr;
8222 			ill_refhold(dst_ill);
8223 		} else {
8224 			ill_t *ill = ire->ire_ipif->ipif_ill;
8225 
8226 			if (IS_IPMP(ill)) {
8227 				dst_ill =
8228 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8229 			} else {
8230 				dst_ill = ill;
8231 				ill_refhold(dst_ill);
8232 			}
8233 		}
8234 
8235 		if (dst_ill == NULL) {
8236 			if (ip_debug > 2) {
8237 				pr_addr_dbg("ip_newroute: no dst "
8238 				    "ill for dst %s\n", AF_INET, &dst);
8239 			}
8240 			goto icmp_err_ret;
8241 		}
8242 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8243 
8244 		/*
8245 		 * Pick the best source address from dst_ill.
8246 		 *
8247 		 * 1) Try to pick the source address from the destination
8248 		 *    route. Clustering assumes that when we have multiple
8249 		 *    prefixes hosted on an interface, the prefix of the
8250 		 *    source address matches the prefix of the destination
8251 		 *    route. We do this only if the address is not
8252 		 *    DEPRECATED.
8253 		 *
8254 		 * 2) If the conn is in a different zone than the ire, we
8255 		 *    need to pick a source address from the right zone.
8256 		 */
8257 		ASSERT(src_ipif == NULL);
8258 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8259 			/*
8260 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8261 			 * Check that the ipif matching the requested source
8262 			 * address still exists.
8263 			 */
8264 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8265 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8266 		}
8267 
8268 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8269 
8270 		if (src_ipif == NULL &&
8271 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8272 			ire_marks |= IRE_MARK_USESRC_CHECK;
8273 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8274 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8275 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8276 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8277 			    ire->ire_zoneid != ALL_ZONES) ||
8278 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8279 				/*
8280 				 * If the destination is reachable via a
8281 				 * given gateway, the selected source address
8282 				 * should be in the same subnet as the gateway.
8283 				 * Otherwise, the destination is not reachable.
8284 				 *
8285 				 * If there are no interfaces on the same subnet
8286 				 * as the destination, ipif_select_source gives
8287 				 * first non-deprecated interface which might be
8288 				 * on a different subnet than the gateway.
8289 				 * This is not desirable. Hence pass the dst_ire
8290 				 * source address to ipif_select_source.
8291 				 * It is sure that the destination is reachable
8292 				 * with the dst_ire source address subnet.
8293 				 * So passing dst_ire source address to
8294 				 * ipif_select_source will make sure that the
8295 				 * selected source will be on the same subnet
8296 				 * as dst_ire source address.
8297 				 */
8298 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8299 
8300 				src_ipif = ipif_select_source(dst_ill, saddr,
8301 				    zoneid);
8302 				if (src_ipif == NULL) {
8303 					/*
8304 					 * In the case of multirouting, it may
8305 					 * happen that ipif_select_source fails
8306 					 * as DAD may disallow use of the
8307 					 * particular source interface.  Anyway,
8308 					 * we need to continue and attempt to
8309 					 * resolve other multirt routes.
8310 					 */
8311 					if ((sire != NULL) &&
8312 					    (sire->ire_flags & RTF_MULTIRT)) {
8313 						ire_refrele(ire);
8314 						ire = NULL;
8315 						multirt_resolve_next = B_TRUE;
8316 						multirt_res_failures++;
8317 						continue;
8318 					}
8319 
8320 					if (ip_debug > 2) {
8321 						pr_addr_dbg("ip_newroute: "
8322 						    "no src for dst %s ",
8323 						    AF_INET, &dst);
8324 						printf("on interface %s\n",
8325 						    dst_ill->ill_name);
8326 					}
8327 					goto icmp_err_ret;
8328 				}
8329 			} else {
8330 				src_ipif = ire->ire_ipif;
8331 				ASSERT(src_ipif != NULL);
8332 				/* hold src_ipif for uniformity */
8333 				ipif_refhold(src_ipif);
8334 			}
8335 		}
8336 
8337 		/*
8338 		 * Assign a source address while we have the conn.
8339 		 * We can't have ip_wput_ire pick a source address when the
8340 		 * packet returns from arp since we need to look at
8341 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8342 		 * going through arp.
8343 		 *
8344 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8345 		 *	  it uses ip6i to store this information.
8346 		 */
8347 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8348 			ipha->ipha_src = src_ipif->ipif_src_addr;
8349 
8350 		if (ip_debug > 3) {
8351 			/* ip2dbg */
8352 			pr_addr_dbg("ip_newroute: first hop %s\n",
8353 			    AF_INET, &gw);
8354 		}
8355 		ip2dbg(("\tire type %s (%d)\n",
8356 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8357 
8358 		/*
8359 		 * The TTL of multirouted packets is bounded by the
8360 		 * ip_multirt_ttl ndd variable.
8361 		 */
8362 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8363 			/* Force TTL of multirouted packets */
8364 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8365 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8366 				ip2dbg(("ip_newroute: forcing multirt TTL "
8367 				    "to %d (was %d), dst 0x%08x\n",
8368 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8369 				    ntohl(sire->ire_addr)));
8370 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8371 			}
8372 		}
8373 		/*
8374 		 * At this point in ip_newroute(), ire is either the
8375 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8376 		 * destination or an IRE_INTERFACE type that should be used
8377 		 * to resolve an on-subnet destination or an on-subnet
8378 		 * next-hop gateway.
8379 		 *
8380 		 * In the IRE_CACHE case, we have the following :
8381 		 *
8382 		 * 1) src_ipif - used for getting a source address.
8383 		 *
8384 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8385 		 *    means packets using this IRE_CACHE will go out on
8386 		 *    dst_ill.
8387 		 *
8388 		 * 3) The IRE sire will point to the prefix that is the
8389 		 *    longest  matching route for the destination. These
8390 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8391 		 *
8392 		 *    The newly created IRE_CACHE entry for the off-subnet
8393 		 *    destination is tied to both the prefix route and the
8394 		 *    interface route used to resolve the next-hop gateway
8395 		 *    via the ire_phandle and ire_ihandle fields,
8396 		 *    respectively.
8397 		 *
8398 		 * In the IRE_INTERFACE case, we have the following :
8399 		 *
8400 		 * 1) src_ipif - used for getting a source address.
8401 		 *
8402 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8403 		 *    means packets using the IRE_CACHE that we will build
8404 		 *    here will go out on dst_ill.
8405 		 *
8406 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8407 		 *    to be created will only be tied to the IRE_INTERFACE
8408 		 *    that was derived from the ire_ihandle field.
8409 		 *
8410 		 *    If sire is non-NULL, it means the destination is
8411 		 *    off-link and we will first create the IRE_CACHE for the
8412 		 *    gateway. Next time through ip_newroute, we will create
8413 		 *    the IRE_CACHE for the final destination as described
8414 		 *    above.
8415 		 *
8416 		 * In both cases, after the current resolution has been
8417 		 * completed (or possibly initialised, in the IRE_INTERFACE
8418 		 * case), the loop may be re-entered to attempt the resolution
8419 		 * of another RTF_MULTIRT route.
8420 		 *
8421 		 * When an IRE_CACHE entry for the off-subnet destination is
8422 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8423 		 * for further processing in emission loops.
8424 		 */
8425 		save_ire = ire;
8426 		switch (ire->ire_type) {
8427 		case IRE_CACHE: {
8428 			ire_t	*ipif_ire;
8429 
8430 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8431 			if (gw == 0)
8432 				gw = ire->ire_gateway_addr;
8433 			/*
8434 			 * We need 3 ire's to create a new cache ire for an
8435 			 * off-link destination from the cache ire of the
8436 			 * gateway.
8437 			 *
8438 			 *	1. The prefix ire 'sire' (Note that this does
8439 			 *	   not apply to the conn_nexthop_set case)
8440 			 *	2. The cache ire of the gateway 'ire'
8441 			 *	3. The interface ire 'ipif_ire'
8442 			 *
8443 			 * We have (1) and (2). We lookup (3) below.
8444 			 *
8445 			 * If there is no interface route to the gateway,
8446 			 * it is a race condition, where we found the cache
8447 			 * but the interface route has been deleted.
8448 			 */
8449 			if (ip_nexthop) {
8450 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8451 			} else {
8452 				ipif_ire =
8453 				    ire_ihandle_lookup_offlink(ire, sire);
8454 			}
8455 			if (ipif_ire == NULL) {
8456 				ip1dbg(("ip_newroute: "
8457 				    "ire_ihandle_lookup_offlink failed\n"));
8458 				goto icmp_err_ret;
8459 			}
8460 
8461 			/*
8462 			 * Check cached gateway IRE for any security
8463 			 * attributes; if found, associate the gateway
8464 			 * credentials group to the destination IRE.
8465 			 */
8466 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8467 				mutex_enter(&attrp->igsa_lock);
8468 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8469 					GCGRP_REFHOLD(gcgrp);
8470 				mutex_exit(&attrp->igsa_lock);
8471 			}
8472 
8473 			/*
8474 			 * XXX For the source of the resolver mp,
8475 			 * we are using the same DL_UNITDATA_REQ
8476 			 * (from save_ire->ire_nce->nce_res_mp)
8477 			 * though the save_ire is not pointing at the same ill.
8478 			 * This is incorrect. We need to send it up to the
8479 			 * resolver to get the right res_mp. For ethernets
8480 			 * this may be okay (ill_type == DL_ETHER).
8481 			 */
8482 
8483 			ire = ire_create(
8484 			    (uchar_t *)&dst,		/* dest address */
8485 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8486 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8487 			    (uchar_t *)&gw,		/* gateway address */
8488 			    &save_ire->ire_max_frag,
8489 			    save_ire->ire_nce,		/* src nce */
8490 			    dst_ill->ill_rq,		/* recv-from queue */
8491 			    dst_ill->ill_wq,		/* send-to queue */
8492 			    IRE_CACHE,			/* IRE type */
8493 			    src_ipif,
8494 			    (sire != NULL) ?
8495 			    sire->ire_mask : 0, 	/* Parent mask */
8496 			    (sire != NULL) ?
8497 			    sire->ire_phandle : 0,	/* Parent handle */
8498 			    ipif_ire->ire_ihandle,	/* Interface handle */
8499 			    (sire != NULL) ? (sire->ire_flags &
8500 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8501 			    (sire != NULL) ?
8502 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8503 			    NULL,
8504 			    gcgrp,
8505 			    ipst);
8506 
8507 			if (ire == NULL) {
8508 				if (gcgrp != NULL) {
8509 					GCGRP_REFRELE(gcgrp);
8510 					gcgrp = NULL;
8511 				}
8512 				ire_refrele(ipif_ire);
8513 				ire_refrele(save_ire);
8514 				break;
8515 			}
8516 
8517 			/* reference now held by IRE */
8518 			gcgrp = NULL;
8519 
8520 			ire->ire_marks |= ire_marks;
8521 
8522 			/*
8523 			 * Prevent sire and ipif_ire from getting deleted.
8524 			 * The newly created ire is tied to both of them via
8525 			 * the phandle and ihandle respectively.
8526 			 */
8527 			if (sire != NULL) {
8528 				IRB_REFHOLD(sire->ire_bucket);
8529 				/* Has it been removed already ? */
8530 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8531 					IRB_REFRELE(sire->ire_bucket);
8532 					ire_refrele(ipif_ire);
8533 					ire_refrele(save_ire);
8534 					break;
8535 				}
8536 			}
8537 
8538 			IRB_REFHOLD(ipif_ire->ire_bucket);
8539 			/* Has it been removed already ? */
8540 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8541 				IRB_REFRELE(ipif_ire->ire_bucket);
8542 				if (sire != NULL)
8543 					IRB_REFRELE(sire->ire_bucket);
8544 				ire_refrele(ipif_ire);
8545 				ire_refrele(save_ire);
8546 				break;
8547 			}
8548 
8549 			xmit_mp = first_mp;
8550 			/*
8551 			 * In the case of multirouting, a copy
8552 			 * of the packet is done before its sending.
8553 			 * The copy is used to attempt another
8554 			 * route resolution, in a next loop.
8555 			 */
8556 			if (ire->ire_flags & RTF_MULTIRT) {
8557 				copy_mp = copymsg(first_mp);
8558 				if (copy_mp != NULL) {
8559 					xmit_mp = copy_mp;
8560 					MULTIRT_DEBUG_TAG(first_mp);
8561 				}
8562 			}
8563 
8564 			ire_add_then_send(q, ire, xmit_mp);
8565 			ire_refrele(save_ire);
8566 
8567 			/* Assert that sire is not deleted yet. */
8568 			if (sire != NULL) {
8569 				ASSERT(sire->ire_ptpn != NULL);
8570 				IRB_REFRELE(sire->ire_bucket);
8571 			}
8572 
8573 			/* Assert that ipif_ire is not deleted yet. */
8574 			ASSERT(ipif_ire->ire_ptpn != NULL);
8575 			IRB_REFRELE(ipif_ire->ire_bucket);
8576 			ire_refrele(ipif_ire);
8577 
8578 			/*
8579 			 * If copy_mp is not NULL, multirouting was
8580 			 * requested. We loop to initiate a next
8581 			 * route resolution attempt, starting from sire.
8582 			 */
8583 			if (copy_mp != NULL) {
8584 				/*
8585 				 * Search for the next unresolved
8586 				 * multirt route.
8587 				 */
8588 				copy_mp = NULL;
8589 				ipif_ire = NULL;
8590 				ire = NULL;
8591 				multirt_resolve_next = B_TRUE;
8592 				continue;
8593 			}
8594 			if (sire != NULL)
8595 				ire_refrele(sire);
8596 			ipif_refrele(src_ipif);
8597 			ill_refrele(dst_ill);
8598 			return;
8599 		}
8600 		case IRE_IF_NORESOLVER: {
8601 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8602 			    dst_ill->ill_resolver_mp == NULL) {
8603 				ip1dbg(("ip_newroute: dst_ill %p "
8604 				    "for IRE_IF_NORESOLVER ire %p has "
8605 				    "no ill_resolver_mp\n",
8606 				    (void *)dst_ill, (void *)ire));
8607 				break;
8608 			}
8609 
8610 			/*
8611 			 * TSol note: We are creating the ire cache for the
8612 			 * destination 'dst'. If 'dst' is offlink, going
8613 			 * through the first hop 'gw', the security attributes
8614 			 * of 'dst' must be set to point to the gateway
8615 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8616 			 * is possible that 'dst' is a potential gateway that is
8617 			 * referenced by some route that has some security
8618 			 * attributes. Thus in the former case, we need to do a
8619 			 * gcgrp_lookup of 'gw' while in the latter case we
8620 			 * need to do gcgrp_lookup of 'dst' itself.
8621 			 */
8622 			ga.ga_af = AF_INET;
8623 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8624 			    &ga.ga_addr);
8625 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8626 
8627 			ire = ire_create(
8628 			    (uchar_t *)&dst,		/* dest address */
8629 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8630 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8631 			    (uchar_t *)&gw,		/* gateway address */
8632 			    &save_ire->ire_max_frag,
8633 			    NULL,			/* no src nce */
8634 			    dst_ill->ill_rq,		/* recv-from queue */
8635 			    dst_ill->ill_wq,		/* send-to queue */
8636 			    IRE_CACHE,
8637 			    src_ipif,
8638 			    save_ire->ire_mask,		/* Parent mask */
8639 			    (sire != NULL) ?		/* Parent handle */
8640 			    sire->ire_phandle : 0,
8641 			    save_ire->ire_ihandle,	/* Interface handle */
8642 			    (sire != NULL) ? sire->ire_flags &
8643 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8644 			    &(save_ire->ire_uinfo),
8645 			    NULL,
8646 			    gcgrp,
8647 			    ipst);
8648 
8649 			if (ire == NULL) {
8650 				if (gcgrp != NULL) {
8651 					GCGRP_REFRELE(gcgrp);
8652 					gcgrp = NULL;
8653 				}
8654 				ire_refrele(save_ire);
8655 				break;
8656 			}
8657 
8658 			/* reference now held by IRE */
8659 			gcgrp = NULL;
8660 
8661 			ire->ire_marks |= ire_marks;
8662 
8663 			/* Prevent save_ire from getting deleted */
8664 			IRB_REFHOLD(save_ire->ire_bucket);
8665 			/* Has it been removed already ? */
8666 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8667 				IRB_REFRELE(save_ire->ire_bucket);
8668 				ire_refrele(save_ire);
8669 				break;
8670 			}
8671 
8672 			/*
8673 			 * In the case of multirouting, a copy
8674 			 * of the packet is made before it is sent.
8675 			 * The copy is used in the next
8676 			 * loop to attempt another resolution.
8677 			 */
8678 			xmit_mp = first_mp;
8679 			if ((sire != NULL) &&
8680 			    (sire->ire_flags & RTF_MULTIRT)) {
8681 				copy_mp = copymsg(first_mp);
8682 				if (copy_mp != NULL) {
8683 					xmit_mp = copy_mp;
8684 					MULTIRT_DEBUG_TAG(first_mp);
8685 				}
8686 			}
8687 			ire_add_then_send(q, ire, xmit_mp);
8688 
8689 			/* Assert that it is not deleted yet. */
8690 			ASSERT(save_ire->ire_ptpn != NULL);
8691 			IRB_REFRELE(save_ire->ire_bucket);
8692 			ire_refrele(save_ire);
8693 
8694 			if (copy_mp != NULL) {
8695 				/*
8696 				 * If we found a (no)resolver, we ignore any
8697 				 * trailing top priority IRE_CACHE in further
8698 				 * loops. This ensures that we do not omit any
8699 				 * (no)resolver.
8700 				 * This IRE_CACHE, if any, will be processed
8701 				 * by another thread entering ip_newroute().
8702 				 * IRE_CACHE entries, if any, will be processed
8703 				 * by another thread entering ip_newroute(),
8704 				 * (upon resolver response, for instance).
8705 				 * This aims to force parallel multirt
8706 				 * resolutions as soon as a packet must be sent.
8707 				 * In the best case, after the tx of only one
8708 				 * packet, all reachable routes are resolved.
8709 				 * Otherwise, the resolution of all RTF_MULTIRT
8710 				 * routes would require several emissions.
8711 				 */
8712 				multirt_flags &= ~MULTIRT_CACHEGW;
8713 
8714 				/*
8715 				 * Search for the next unresolved multirt
8716 				 * route.
8717 				 */
8718 				copy_mp = NULL;
8719 				save_ire = NULL;
8720 				ire = NULL;
8721 				multirt_resolve_next = B_TRUE;
8722 				continue;
8723 			}
8724 
8725 			/*
8726 			 * Don't need sire anymore
8727 			 */
8728 			if (sire != NULL)
8729 				ire_refrele(sire);
8730 
8731 			ipif_refrele(src_ipif);
8732 			ill_refrele(dst_ill);
8733 			return;
8734 		}
8735 		case IRE_IF_RESOLVER:
8736 			/*
8737 			 * We can't build an IRE_CACHE yet, but at least we
8738 			 * found a resolver that can help.
8739 			 */
8740 			res_mp = dst_ill->ill_resolver_mp;
8741 			if (!OK_RESOLVER_MP(res_mp))
8742 				break;
8743 
8744 			/*
8745 			 * To be at this point in the code with a non-zero gw
8746 			 * means that dst is reachable through a gateway that
8747 			 * we have never resolved.  By changing dst to the gw
8748 			 * addr we resolve the gateway first.
8749 			 * When ire_add_then_send() tries to put the IP dg
8750 			 * to dst, it will reenter ip_newroute() at which
8751 			 * time we will find the IRE_CACHE for the gw and
8752 			 * create another IRE_CACHE in case IRE_CACHE above.
8753 			 */
8754 			if (gw != INADDR_ANY) {
8755 				/*
8756 				 * The source ipif that was determined above was
8757 				 * relative to the destination address, not the
8758 				 * gateway's. If src_ipif was not taken out of
8759 				 * the IRE_IF_RESOLVER entry, we'll need to call
8760 				 * ipif_select_source() again.
8761 				 */
8762 				if (src_ipif != ire->ire_ipif) {
8763 					ipif_refrele(src_ipif);
8764 					src_ipif = ipif_select_source(dst_ill,
8765 					    gw, zoneid);
8766 					/*
8767 					 * In the case of multirouting, it may
8768 					 * happen that ipif_select_source fails
8769 					 * as DAD may disallow use of the
8770 					 * particular source interface.  Anyway,
8771 					 * we need to continue and attempt to
8772 					 * resolve other multirt routes.
8773 					 */
8774 					if (src_ipif == NULL) {
8775 						if (sire != NULL &&
8776 						    (sire->ire_flags &
8777 						    RTF_MULTIRT)) {
8778 							ire_refrele(ire);
8779 							ire = NULL;
8780 							multirt_resolve_next =
8781 							    B_TRUE;
8782 							multirt_res_failures++;
8783 							continue;
8784 						}
8785 						if (ip_debug > 2) {
8786 							pr_addr_dbg(
8787 							    "ip_newroute: no "
8788 							    "src for gw %s ",
8789 							    AF_INET, &gw);
8790 							printf("on "
8791 							    "interface %s\n",
8792 							    dst_ill->ill_name);
8793 						}
8794 						goto icmp_err_ret;
8795 					}
8796 				}
8797 				save_dst = dst;
8798 				dst = gw;
8799 				gw = INADDR_ANY;
8800 			}
8801 
8802 			/*
8803 			 * We obtain a partial IRE_CACHE which we will pass
8804 			 * along with the resolver query.  When the response
8805 			 * comes back it will be there ready for us to add.
8806 			 * The ire_max_frag is atomically set under the
8807 			 * irebucket lock in ire_add_v[46].
8808 			 */
8809 
8810 			ire = ire_create_mp(
8811 			    (uchar_t *)&dst,		/* dest address */
8812 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8813 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8814 			    (uchar_t *)&gw,		/* gateway address */
8815 			    NULL,			/* ire_max_frag */
8816 			    NULL,			/* no src nce */
8817 			    dst_ill->ill_rq,		/* recv-from queue */
8818 			    dst_ill->ill_wq,		/* send-to queue */
8819 			    IRE_CACHE,
8820 			    src_ipif,			/* Interface ipif */
8821 			    save_ire->ire_mask,		/* Parent mask */
8822 			    0,
8823 			    save_ire->ire_ihandle,	/* Interface handle */
8824 			    0,				/* flags if any */
8825 			    &(save_ire->ire_uinfo),
8826 			    NULL,
8827 			    NULL,
8828 			    ipst);
8829 
8830 			if (ire == NULL) {
8831 				ire_refrele(save_ire);
8832 				break;
8833 			}
8834 
8835 			if ((sire != NULL) &&
8836 			    (sire->ire_flags & RTF_MULTIRT)) {
8837 				copy_mp = copymsg(first_mp);
8838 				if (copy_mp != NULL)
8839 					MULTIRT_DEBUG_TAG(copy_mp);
8840 			}
8841 
8842 			ire->ire_marks |= ire_marks;
8843 
8844 			/*
8845 			 * Construct message chain for the resolver
8846 			 * of the form:
8847 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8848 			 * Packet could contain a IPSEC_OUT mp.
8849 			 *
8850 			 * NOTE : ire will be added later when the response
8851 			 * comes back from ARP. If the response does not
8852 			 * come back, ARP frees the packet. For this reason,
8853 			 * we can't REFHOLD the bucket of save_ire to prevent
8854 			 * deletions. We may not be able to REFRELE the bucket
8855 			 * if the response never comes back. Thus, before
8856 			 * adding the ire, ire_add_v4 will make sure that the
8857 			 * interface route does not get deleted. This is the
8858 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8859 			 * where we can always prevent deletions because of
8860 			 * the synchronous nature of adding IRES i.e
8861 			 * ire_add_then_send is called after creating the IRE.
8862 			 */
8863 			ASSERT(ire->ire_mp != NULL);
8864 			ire->ire_mp->b_cont = first_mp;
8865 			/* Have saved_mp handy, for cleanup if canput fails */
8866 			saved_mp = mp;
8867 			mp = copyb(res_mp);
8868 			if (mp == NULL) {
8869 				/* Prepare for cleanup */
8870 				mp = saved_mp; /* pkt */
8871 				ire_delete(ire); /* ire_mp */
8872 				ire = NULL;
8873 				ire_refrele(save_ire);
8874 				if (copy_mp != NULL) {
8875 					MULTIRT_DEBUG_UNTAG(copy_mp);
8876 					freemsg(copy_mp);
8877 					copy_mp = NULL;
8878 				}
8879 				break;
8880 			}
8881 			linkb(mp, ire->ire_mp);
8882 
8883 			/*
8884 			 * Fill in the source and dest addrs for the resolver.
8885 			 * NOTE: this depends on memory layouts imposed by
8886 			 * ill_init().
8887 			 */
8888 			areq = (areq_t *)mp->b_rptr;
8889 			addrp = (ipaddr_t *)((char *)areq +
8890 			    areq->areq_sender_addr_offset);
8891 			*addrp = save_ire->ire_src_addr;
8892 
8893 			ire_refrele(save_ire);
8894 			addrp = (ipaddr_t *)((char *)areq +
8895 			    areq->areq_target_addr_offset);
8896 			*addrp = dst;
8897 			/* Up to the resolver. */
8898 			if (canputnext(dst_ill->ill_rq) &&
8899 			    !(dst_ill->ill_arp_closing)) {
8900 				putnext(dst_ill->ill_rq, mp);
8901 				ire = NULL;
8902 				if (copy_mp != NULL) {
8903 					/*
8904 					 * If we found a resolver, we ignore
8905 					 * any trailing top priority IRE_CACHE
8906 					 * in the further loops. This ensures
8907 					 * that we do not omit any resolver.
8908 					 * IRE_CACHE entries, if any, will be
8909 					 * processed next time we enter
8910 					 * ip_newroute().
8911 					 */
8912 					multirt_flags &= ~MULTIRT_CACHEGW;
8913 					/*
8914 					 * Search for the next unresolved
8915 					 * multirt route.
8916 					 */
8917 					first_mp = copy_mp;
8918 					copy_mp = NULL;
8919 					/* Prepare the next resolution loop. */
8920 					mp = first_mp;
8921 					EXTRACT_PKT_MP(mp, first_mp,
8922 					    mctl_present);
8923 					if (mctl_present)
8924 						io = (ipsec_out_t *)
8925 						    first_mp->b_rptr;
8926 					ipha = (ipha_t *)mp->b_rptr;
8927 
8928 					ASSERT(sire != NULL);
8929 
8930 					dst = save_dst;
8931 					multirt_resolve_next = B_TRUE;
8932 					continue;
8933 				}
8934 
8935 				if (sire != NULL)
8936 					ire_refrele(sire);
8937 
8938 				/*
8939 				 * The response will come back in ip_wput
8940 				 * with db_type IRE_DB_TYPE.
8941 				 */
8942 				ipif_refrele(src_ipif);
8943 				ill_refrele(dst_ill);
8944 				return;
8945 			} else {
8946 				/* Prepare for cleanup */
8947 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8948 				    mp);
8949 				mp->b_cont = NULL;
8950 				freeb(mp); /* areq */
8951 				/*
8952 				 * this is an ire that is not added to the
8953 				 * cache. ire_freemblk will handle the release
8954 				 * of any resources associated with the ire.
8955 				 */
8956 				ire_delete(ire); /* ire_mp */
8957 				mp = saved_mp; /* pkt */
8958 				ire = NULL;
8959 				if (copy_mp != NULL) {
8960 					MULTIRT_DEBUG_UNTAG(copy_mp);
8961 					freemsg(copy_mp);
8962 					copy_mp = NULL;
8963 				}
8964 				break;
8965 			}
8966 		default:
8967 			break;
8968 		}
8969 	} while (multirt_resolve_next);
8970 
8971 	ip1dbg(("ip_newroute: dropped\n"));
8972 	/* Did this packet originate externally? */
8973 	if (mp->b_prev) {
8974 		mp->b_next = NULL;
8975 		mp->b_prev = NULL;
8976 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8977 	} else {
8978 		if (dst_ill != NULL) {
8979 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8980 		} else {
8981 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8982 		}
8983 	}
8984 	ASSERT(copy_mp == NULL);
8985 	MULTIRT_DEBUG_UNTAG(first_mp);
8986 	freemsg(first_mp);
8987 	if (ire != NULL)
8988 		ire_refrele(ire);
8989 	if (sire != NULL)
8990 		ire_refrele(sire);
8991 	if (src_ipif != NULL)
8992 		ipif_refrele(src_ipif);
8993 	if (dst_ill != NULL)
8994 		ill_refrele(dst_ill);
8995 	return;
8996 
8997 icmp_err_ret:
8998 	ip1dbg(("ip_newroute: no route\n"));
8999 	if (src_ipif != NULL)
9000 		ipif_refrele(src_ipif);
9001 	if (dst_ill != NULL)
9002 		ill_refrele(dst_ill);
9003 	if (sire != NULL)
9004 		ire_refrele(sire);
9005 	/* Did this packet originate externally? */
9006 	if (mp->b_prev) {
9007 		mp->b_next = NULL;
9008 		mp->b_prev = NULL;
9009 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9010 		q = WR(q);
9011 	} else {
9012 		/*
9013 		 * There is no outgoing ill, so just increment the
9014 		 * system MIB.
9015 		 */
9016 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9017 		/*
9018 		 * Since ip_wput() isn't close to finished, we fill
9019 		 * in enough of the header for credible error reporting.
9020 		 */
9021 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9022 			/* Failed */
9023 			MULTIRT_DEBUG_UNTAG(first_mp);
9024 			freemsg(first_mp);
9025 			if (ire != NULL)
9026 				ire_refrele(ire);
9027 			return;
9028 		}
9029 	}
9030 
9031 	/*
9032 	 * At this point we will have ire only if RTF_BLACKHOLE
9033 	 * or RTF_REJECT flags are set on the IRE. It will not
9034 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9035 	 */
9036 	if (ire != NULL) {
9037 		if (ire->ire_flags & RTF_BLACKHOLE) {
9038 			ire_refrele(ire);
9039 			MULTIRT_DEBUG_UNTAG(first_mp);
9040 			freemsg(first_mp);
9041 			return;
9042 		}
9043 		ire_refrele(ire);
9044 	}
9045 	if (ip_source_routed(ipha, ipst)) {
9046 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9047 		    zoneid, ipst);
9048 		return;
9049 	}
9050 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9051 }
9052 
9053 ip_opt_info_t zero_info;
9054 
9055 /*
9056  * IPv4 -
9057  * ip_newroute_ipif is called by ip_wput_multicast and
9058  * ip_rput_forward_multicast whenever we need to send
9059  * out a packet to a destination address for which we do not have specific
9060  * routing information. It is used when the packet will be sent out
9061  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9062  * socket option is set or icmp error message wants to go out on a particular
9063  * interface for a unicast packet.
9064  *
9065  * In most cases, the destination address is resolved thanks to the ipif
9066  * intrinsic resolver. However, there are some cases where the call to
9067  * ip_newroute_ipif must take into account the potential presence of
9068  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9069  * that uses the interface. This is specified through flags,
9070  * which can be a combination of:
9071  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9072  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9073  *   and flags. Additionally, the packet source address has to be set to
9074  *   the specified address. The caller is thus expected to set this flag
9075  *   if the packet has no specific source address yet.
9076  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9077  *   flag, the resulting ire will inherit the flag. All unresolved routes
9078  *   to the destination must be explored in the same call to
9079  *   ip_newroute_ipif().
9080  */
9081 static void
9082 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9083     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9084 {
9085 	areq_t	*areq;
9086 	ire_t	*ire = NULL;
9087 	mblk_t	*res_mp;
9088 	ipaddr_t *addrp;
9089 	mblk_t *first_mp;
9090 	ire_t	*save_ire = NULL;
9091 	ipif_t	*src_ipif = NULL;
9092 	ushort_t ire_marks = 0;
9093 	ill_t	*dst_ill = NULL;
9094 	ipha_t *ipha;
9095 	mblk_t	*saved_mp;
9096 	ire_t   *fire = NULL;
9097 	mblk_t  *copy_mp = NULL;
9098 	boolean_t multirt_resolve_next;
9099 	boolean_t unspec_src;
9100 	ipaddr_t ipha_dst;
9101 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9102 
9103 	/*
9104 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9105 	 * here for uniformity
9106 	 */
9107 	ipif_refhold(ipif);
9108 
9109 	/*
9110 	 * This loop is run only once in most cases.
9111 	 * We loop to resolve further routes only when the destination
9112 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9113 	 */
9114 	do {
9115 		if (dst_ill != NULL) {
9116 			ill_refrele(dst_ill);
9117 			dst_ill = NULL;
9118 		}
9119 		if (src_ipif != NULL) {
9120 			ipif_refrele(src_ipif);
9121 			src_ipif = NULL;
9122 		}
9123 		multirt_resolve_next = B_FALSE;
9124 
9125 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9126 		    ipif->ipif_ill->ill_name));
9127 
9128 		first_mp = mp;
9129 		if (DB_TYPE(mp) == M_CTL)
9130 			mp = mp->b_cont;
9131 		ipha = (ipha_t *)mp->b_rptr;
9132 
9133 		/*
9134 		 * Save the packet destination address, we may need it after
9135 		 * the packet has been consumed.
9136 		 */
9137 		ipha_dst = ipha->ipha_dst;
9138 
9139 		/*
9140 		 * If the interface is a pt-pt interface we look for an
9141 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9142 		 * local_address and the pt-pt destination address. Otherwise
9143 		 * we just match the local address.
9144 		 * NOTE: dst could be different than ipha->ipha_dst in case
9145 		 * of sending igmp multicast packets over a point-to-point
9146 		 * connection.
9147 		 * Thus we must be careful enough to check ipha_dst to be a
9148 		 * multicast address, otherwise it will take xmit_if path for
9149 		 * multicast packets resulting into kernel stack overflow by
9150 		 * repeated calls to ip_newroute_ipif from ire_send().
9151 		 */
9152 		if (CLASSD(ipha_dst) &&
9153 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9154 			goto err_ret;
9155 		}
9156 
9157 		/*
9158 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9159 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9160 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9161 		 * propagate its flags to the new ire.
9162 		 */
9163 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9164 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9165 			ip2dbg(("ip_newroute_ipif: "
9166 			    "ipif_lookup_multi_ire("
9167 			    "ipif %p, dst %08x) = fire %p\n",
9168 			    (void *)ipif, ntohl(dst), (void *)fire));
9169 		}
9170 
9171 		/*
9172 		 * Note: While we pick a dst_ill we are really only
9173 		 * interested in the ill for load spreading. The source
9174 		 * ipif is determined by source address selection below.
9175 		 */
9176 		if (IS_IPMP(ipif->ipif_ill)) {
9177 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9178 
9179 			if (CLASSD(ipha_dst))
9180 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9181 			else
9182 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9183 		} else {
9184 			dst_ill = ipif->ipif_ill;
9185 			ill_refhold(dst_ill);
9186 		}
9187 
9188 		if (dst_ill == NULL) {
9189 			if (ip_debug > 2) {
9190 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9191 				    "for dst %s\n", AF_INET, &dst);
9192 			}
9193 			goto err_ret;
9194 		}
9195 
9196 		/*
9197 		 * Pick a source address preferring non-deprecated ones.
9198 		 * Unlike ip_newroute, we don't do any source address
9199 		 * selection here since for multicast it really does not help
9200 		 * in inbound load spreading as in the unicast case.
9201 		 */
9202 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9203 		    (fire->ire_flags & RTF_SETSRC)) {
9204 			/*
9205 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9206 			 * on that interface. This ire has RTF_SETSRC flag, so
9207 			 * the source address of the packet must be changed.
9208 			 * Check that the ipif matching the requested source
9209 			 * address still exists.
9210 			 */
9211 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9212 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9213 		}
9214 
9215 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9216 
9217 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9218 		    (IS_IPMP(ipif->ipif_ill) ||
9219 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9220 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9221 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9222 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9223 		    (src_ipif == NULL) &&
9224 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9225 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9226 			if (src_ipif == NULL) {
9227 				if (ip_debug > 2) {
9228 					/* ip1dbg */
9229 					pr_addr_dbg("ip_newroute_ipif: "
9230 					    "no src for dst %s",
9231 					    AF_INET, &dst);
9232 				}
9233 				ip1dbg((" on interface %s\n",
9234 				    dst_ill->ill_name));
9235 				goto err_ret;
9236 			}
9237 			ipif_refrele(ipif);
9238 			ipif = src_ipif;
9239 			ipif_refhold(ipif);
9240 		}
9241 		if (src_ipif == NULL) {
9242 			src_ipif = ipif;
9243 			ipif_refhold(src_ipif);
9244 		}
9245 
9246 		/*
9247 		 * Assign a source address while we have the conn.
9248 		 * We can't have ip_wput_ire pick a source address when the
9249 		 * packet returns from arp since conn_unspec_src might be set
9250 		 * and we lose the conn when going through arp.
9251 		 */
9252 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9253 			ipha->ipha_src = src_ipif->ipif_src_addr;
9254 
9255 		/*
9256 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9257 		 * that the outgoing interface does not have an interface ire.
9258 		 */
9259 		if (CLASSD(ipha_dst) && (connp == NULL ||
9260 		    connp->conn_outgoing_ill == NULL) &&
9261 		    infop->ip_opt_ill_index == 0) {
9262 			/* ipif_to_ire returns an held ire */
9263 			ire = ipif_to_ire(ipif);
9264 			if (ire == NULL)
9265 				goto err_ret;
9266 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9267 				goto err_ret;
9268 			save_ire = ire;
9269 
9270 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9271 			    "flags %04x\n",
9272 			    (void *)ire, (void *)ipif, flags));
9273 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9274 			    (fire->ire_flags & RTF_MULTIRT)) {
9275 				/*
9276 				 * As requested by flags, an IRE_OFFSUBNET was
9277 				 * looked up on that interface. This ire has
9278 				 * RTF_MULTIRT flag, so the resolution loop will
9279 				 * be re-entered to resolve additional routes on
9280 				 * other interfaces. For that purpose, a copy of
9281 				 * the packet is performed at this point.
9282 				 */
9283 				fire->ire_last_used_time = lbolt;
9284 				copy_mp = copymsg(first_mp);
9285 				if (copy_mp) {
9286 					MULTIRT_DEBUG_TAG(copy_mp);
9287 				}
9288 			}
9289 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9290 			    (fire->ire_flags & RTF_SETSRC)) {
9291 				/*
9292 				 * As requested by flags, an IRE_OFFSUBET was
9293 				 * looked up on that interface. This ire has
9294 				 * RTF_SETSRC flag, so the source address of the
9295 				 * packet must be changed.
9296 				 */
9297 				ipha->ipha_src = fire->ire_src_addr;
9298 			}
9299 		} else {
9300 			/*
9301 			 * The only ways we can come here are:
9302 			 * 1) IP_BOUND_IF socket option is set
9303 			 * 2) SO_DONTROUTE socket option is set
9304 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9305 			 * In all cases, the new ire will not be added
9306 			 * into cache table.
9307 			 */
9308 			ASSERT(connp == NULL || connp->conn_dontroute ||
9309 			    connp->conn_outgoing_ill != NULL ||
9310 			    infop->ip_opt_ill_index != 0);
9311 			ire_marks |= IRE_MARK_NOADD;
9312 		}
9313 
9314 		switch (ipif->ipif_net_type) {
9315 		case IRE_IF_NORESOLVER: {
9316 			/* We have what we need to build an IRE_CACHE. */
9317 
9318 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9319 			    (dst_ill->ill_resolver_mp == NULL)) {
9320 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9321 				    "for IRE_IF_NORESOLVER ire %p has "
9322 				    "no ill_resolver_mp\n",
9323 				    (void *)dst_ill, (void *)ire));
9324 				break;
9325 			}
9326 
9327 			/*
9328 			 * The new ire inherits the IRE_OFFSUBNET flags
9329 			 * and source address, if this was requested.
9330 			 */
9331 			ire = ire_create(
9332 			    (uchar_t *)&dst,		/* dest address */
9333 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9334 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9335 			    NULL,			/* gateway address */
9336 			    &ipif->ipif_mtu,
9337 			    NULL,			/* no src nce */
9338 			    dst_ill->ill_rq,		/* recv-from queue */
9339 			    dst_ill->ill_wq,		/* send-to queue */
9340 			    IRE_CACHE,
9341 			    src_ipif,
9342 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9343 			    (fire != NULL) ?		/* Parent handle */
9344 			    fire->ire_phandle : 0,
9345 			    (save_ire != NULL) ?	/* Interface handle */
9346 			    save_ire->ire_ihandle : 0,
9347 			    (fire != NULL) ?
9348 			    (fire->ire_flags &
9349 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9350 			    (save_ire == NULL ? &ire_uinfo_null :
9351 			    &save_ire->ire_uinfo),
9352 			    NULL,
9353 			    NULL,
9354 			    ipst);
9355 
9356 			if (ire == NULL) {
9357 				if (save_ire != NULL)
9358 					ire_refrele(save_ire);
9359 				break;
9360 			}
9361 
9362 			ire->ire_marks |= ire_marks;
9363 
9364 			/*
9365 			 * If IRE_MARK_NOADD is set then we need to convert
9366 			 * the max_fragp to a useable value now. This is
9367 			 * normally done in ire_add_v[46]. We also need to
9368 			 * associate the ire with an nce (normally would be
9369 			 * done in ip_wput_nondata()).
9370 			 *
9371 			 * Note that IRE_MARK_NOADD packets created here
9372 			 * do not have a non-null ire_mp pointer. The null
9373 			 * value of ire_bucket indicates that they were
9374 			 * never added.
9375 			 */
9376 			if (ire->ire_marks & IRE_MARK_NOADD) {
9377 				uint_t  max_frag;
9378 
9379 				max_frag = *ire->ire_max_fragp;
9380 				ire->ire_max_fragp = NULL;
9381 				ire->ire_max_frag = max_frag;
9382 
9383 				if ((ire->ire_nce = ndp_lookup_v4(
9384 				    ire_to_ill(ire),
9385 				    (ire->ire_gateway_addr != INADDR_ANY ?
9386 				    &ire->ire_gateway_addr : &ire->ire_addr),
9387 				    B_FALSE)) == NULL) {
9388 					if (save_ire != NULL)
9389 						ire_refrele(save_ire);
9390 					break;
9391 				}
9392 				ASSERT(ire->ire_nce->nce_state ==
9393 				    ND_REACHABLE);
9394 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9395 			}
9396 
9397 			/* Prevent save_ire from getting deleted */
9398 			if (save_ire != NULL) {
9399 				IRB_REFHOLD(save_ire->ire_bucket);
9400 				/* Has it been removed already ? */
9401 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9402 					IRB_REFRELE(save_ire->ire_bucket);
9403 					ire_refrele(save_ire);
9404 					break;
9405 				}
9406 			}
9407 
9408 			ire_add_then_send(q, ire, first_mp);
9409 
9410 			/* Assert that save_ire is not deleted yet. */
9411 			if (save_ire != NULL) {
9412 				ASSERT(save_ire->ire_ptpn != NULL);
9413 				IRB_REFRELE(save_ire->ire_bucket);
9414 				ire_refrele(save_ire);
9415 				save_ire = NULL;
9416 			}
9417 			if (fire != NULL) {
9418 				ire_refrele(fire);
9419 				fire = NULL;
9420 			}
9421 
9422 			/*
9423 			 * the resolution loop is re-entered if this
9424 			 * was requested through flags and if we
9425 			 * actually are in a multirouting case.
9426 			 */
9427 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9428 				boolean_t need_resolve =
9429 				    ire_multirt_need_resolve(ipha_dst,
9430 				    msg_getlabel(copy_mp), ipst);
9431 				if (!need_resolve) {
9432 					MULTIRT_DEBUG_UNTAG(copy_mp);
9433 					freemsg(copy_mp);
9434 					copy_mp = NULL;
9435 				} else {
9436 					/*
9437 					 * ipif_lookup_group() calls
9438 					 * ire_lookup_multi() that uses
9439 					 * ire_ftable_lookup() to find
9440 					 * an IRE_INTERFACE for the group.
9441 					 * In the multirt case,
9442 					 * ire_lookup_multi() then invokes
9443 					 * ire_multirt_lookup() to find
9444 					 * the next resolvable ire.
9445 					 * As a result, we obtain an new
9446 					 * interface, derived from the
9447 					 * next ire.
9448 					 */
9449 					ipif_refrele(ipif);
9450 					ipif = ipif_lookup_group(ipha_dst,
9451 					    zoneid, ipst);
9452 					ip2dbg(("ip_newroute_ipif: "
9453 					    "multirt dst %08x, ipif %p\n",
9454 					    htonl(dst), (void *)ipif));
9455 					if (ipif != NULL) {
9456 						mp = copy_mp;
9457 						copy_mp = NULL;
9458 						multirt_resolve_next = B_TRUE;
9459 						continue;
9460 					} else {
9461 						freemsg(copy_mp);
9462 					}
9463 				}
9464 			}
9465 			if (ipif != NULL)
9466 				ipif_refrele(ipif);
9467 			ill_refrele(dst_ill);
9468 			ipif_refrele(src_ipif);
9469 			return;
9470 		}
9471 		case IRE_IF_RESOLVER:
9472 			/*
9473 			 * We can't build an IRE_CACHE yet, but at least
9474 			 * we found a resolver that can help.
9475 			 */
9476 			res_mp = dst_ill->ill_resolver_mp;
9477 			if (!OK_RESOLVER_MP(res_mp))
9478 				break;
9479 
9480 			/*
9481 			 * We obtain a partial IRE_CACHE which we will pass
9482 			 * along with the resolver query.  When the response
9483 			 * comes back it will be there ready for us to add.
9484 			 * The new ire inherits the IRE_OFFSUBNET flags
9485 			 * and source address, if this was requested.
9486 			 * The ire_max_frag is atomically set under the
9487 			 * irebucket lock in ire_add_v[46]. Only in the
9488 			 * case of IRE_MARK_NOADD, we set it here itself.
9489 			 */
9490 			ire = ire_create_mp(
9491 			    (uchar_t *)&dst,		/* dest address */
9492 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9493 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9494 			    NULL,			/* gateway address */
9495 			    (ire_marks & IRE_MARK_NOADD) ?
9496 			    ipif->ipif_mtu : 0,		/* max_frag */
9497 			    NULL,			/* no src nce */
9498 			    dst_ill->ill_rq,		/* recv-from queue */
9499 			    dst_ill->ill_wq,		/* send-to queue */
9500 			    IRE_CACHE,
9501 			    src_ipif,
9502 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9503 			    (fire != NULL) ?		/* Parent handle */
9504 			    fire->ire_phandle : 0,
9505 			    (save_ire != NULL) ?	/* Interface handle */
9506 			    save_ire->ire_ihandle : 0,
9507 			    (fire != NULL) ?		/* flags if any */
9508 			    (fire->ire_flags &
9509 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9510 			    (save_ire == NULL ? &ire_uinfo_null :
9511 			    &save_ire->ire_uinfo),
9512 			    NULL,
9513 			    NULL,
9514 			    ipst);
9515 
9516 			if (save_ire != NULL) {
9517 				ire_refrele(save_ire);
9518 				save_ire = NULL;
9519 			}
9520 			if (ire == NULL)
9521 				break;
9522 
9523 			ire->ire_marks |= ire_marks;
9524 			/*
9525 			 * Construct message chain for the resolver of the
9526 			 * form:
9527 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9528 			 *
9529 			 * NOTE : ire will be added later when the response
9530 			 * comes back from ARP. If the response does not
9531 			 * come back, ARP frees the packet. For this reason,
9532 			 * we can't REFHOLD the bucket of save_ire to prevent
9533 			 * deletions. We may not be able to REFRELE the
9534 			 * bucket if the response never comes back.
9535 			 * Thus, before adding the ire, ire_add_v4 will make
9536 			 * sure that the interface route does not get deleted.
9537 			 * This is the only case unlike ip_newroute_v6,
9538 			 * ip_newroute_ipif_v6 where we can always prevent
9539 			 * deletions because ire_add_then_send is called after
9540 			 * creating the IRE.
9541 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9542 			 * does not add this IRE into the IRE CACHE.
9543 			 */
9544 			ASSERT(ire->ire_mp != NULL);
9545 			ire->ire_mp->b_cont = first_mp;
9546 			/* Have saved_mp handy, for cleanup if canput fails */
9547 			saved_mp = mp;
9548 			mp = copyb(res_mp);
9549 			if (mp == NULL) {
9550 				/* Prepare for cleanup */
9551 				mp = saved_mp; /* pkt */
9552 				ire_delete(ire); /* ire_mp */
9553 				ire = NULL;
9554 				if (copy_mp != NULL) {
9555 					MULTIRT_DEBUG_UNTAG(copy_mp);
9556 					freemsg(copy_mp);
9557 					copy_mp = NULL;
9558 				}
9559 				break;
9560 			}
9561 			linkb(mp, ire->ire_mp);
9562 
9563 			/*
9564 			 * Fill in the source and dest addrs for the resolver.
9565 			 * NOTE: this depends on memory layouts imposed by
9566 			 * ill_init().  There are corner cases above where we
9567 			 * might've created the IRE with an INADDR_ANY source
9568 			 * address (e.g., if the zeroth ipif on an underlying
9569 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9570 			 * on the ill has a usable test address).  If so, tell
9571 			 * ARP to use ipha_src as its sender address.
9572 			 */
9573 			areq = (areq_t *)mp->b_rptr;
9574 			addrp = (ipaddr_t *)((char *)areq +
9575 			    areq->areq_sender_addr_offset);
9576 			if (ire->ire_src_addr != INADDR_ANY)
9577 				*addrp = ire->ire_src_addr;
9578 			else
9579 				*addrp = ipha->ipha_src;
9580 			addrp = (ipaddr_t *)((char *)areq +
9581 			    areq->areq_target_addr_offset);
9582 			*addrp = dst;
9583 			/* Up to the resolver. */
9584 			if (canputnext(dst_ill->ill_rq) &&
9585 			    !(dst_ill->ill_arp_closing)) {
9586 				putnext(dst_ill->ill_rq, mp);
9587 				/*
9588 				 * The response will come back in ip_wput
9589 				 * with db_type IRE_DB_TYPE.
9590 				 */
9591 			} else {
9592 				mp->b_cont = NULL;
9593 				freeb(mp); /* areq */
9594 				ire_delete(ire); /* ire_mp */
9595 				saved_mp->b_next = NULL;
9596 				saved_mp->b_prev = NULL;
9597 				freemsg(first_mp); /* pkt */
9598 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9599 			}
9600 
9601 			if (fire != NULL) {
9602 				ire_refrele(fire);
9603 				fire = NULL;
9604 			}
9605 
9606 			/*
9607 			 * The resolution loop is re-entered if this was
9608 			 * requested through flags and we actually are
9609 			 * in a multirouting case.
9610 			 */
9611 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9612 				boolean_t need_resolve =
9613 				    ire_multirt_need_resolve(ipha_dst,
9614 				    msg_getlabel(copy_mp), ipst);
9615 				if (!need_resolve) {
9616 					MULTIRT_DEBUG_UNTAG(copy_mp);
9617 					freemsg(copy_mp);
9618 					copy_mp = NULL;
9619 				} else {
9620 					/*
9621 					 * ipif_lookup_group() calls
9622 					 * ire_lookup_multi() that uses
9623 					 * ire_ftable_lookup() to find
9624 					 * an IRE_INTERFACE for the group.
9625 					 * In the multirt case,
9626 					 * ire_lookup_multi() then invokes
9627 					 * ire_multirt_lookup() to find
9628 					 * the next resolvable ire.
9629 					 * As a result, we obtain an new
9630 					 * interface, derived from the
9631 					 * next ire.
9632 					 */
9633 					ipif_refrele(ipif);
9634 					ipif = ipif_lookup_group(ipha_dst,
9635 					    zoneid, ipst);
9636 					if (ipif != NULL) {
9637 						mp = copy_mp;
9638 						copy_mp = NULL;
9639 						multirt_resolve_next = B_TRUE;
9640 						continue;
9641 					} else {
9642 						freemsg(copy_mp);
9643 					}
9644 				}
9645 			}
9646 			if (ipif != NULL)
9647 				ipif_refrele(ipif);
9648 			ill_refrele(dst_ill);
9649 			ipif_refrele(src_ipif);
9650 			return;
9651 		default:
9652 			break;
9653 		}
9654 	} while (multirt_resolve_next);
9655 
9656 err_ret:
9657 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9658 	if (fire != NULL)
9659 		ire_refrele(fire);
9660 	ipif_refrele(ipif);
9661 	/* Did this packet originate externally? */
9662 	if (dst_ill != NULL)
9663 		ill_refrele(dst_ill);
9664 	if (src_ipif != NULL)
9665 		ipif_refrele(src_ipif);
9666 	if (mp->b_prev || mp->b_next) {
9667 		mp->b_next = NULL;
9668 		mp->b_prev = NULL;
9669 	} else {
9670 		/*
9671 		 * Since ip_wput() isn't close to finished, we fill
9672 		 * in enough of the header for credible error reporting.
9673 		 */
9674 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9675 			/* Failed */
9676 			freemsg(first_mp);
9677 			if (ire != NULL)
9678 				ire_refrele(ire);
9679 			return;
9680 		}
9681 	}
9682 	/*
9683 	 * At this point we will have ire only if RTF_BLACKHOLE
9684 	 * or RTF_REJECT flags are set on the IRE. It will not
9685 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9686 	 */
9687 	if (ire != NULL) {
9688 		if (ire->ire_flags & RTF_BLACKHOLE) {
9689 			ire_refrele(ire);
9690 			freemsg(first_mp);
9691 			return;
9692 		}
9693 		ire_refrele(ire);
9694 	}
9695 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9696 }
9697 
9698 /* Name/Value Table Lookup Routine */
9699 char *
9700 ip_nv_lookup(nv_t *nv, int value)
9701 {
9702 	if (!nv)
9703 		return (NULL);
9704 	for (; nv->nv_name; nv++) {
9705 		if (nv->nv_value == value)
9706 			return (nv->nv_name);
9707 	}
9708 	return ("unknown");
9709 }
9710 
9711 /*
9712  * This is a module open, i.e. this is a control stream for access
9713  * to a DLPI device.  We allocate an ill_t as the instance data in
9714  * this case.
9715  */
9716 int
9717 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9718 {
9719 	ill_t	*ill;
9720 	int	err;
9721 	zoneid_t zoneid;
9722 	netstack_t *ns;
9723 	ip_stack_t *ipst;
9724 
9725 	/*
9726 	 * Prevent unprivileged processes from pushing IP so that
9727 	 * they can't send raw IP.
9728 	 */
9729 	if (secpolicy_net_rawaccess(credp) != 0)
9730 		return (EPERM);
9731 
9732 	ns = netstack_find_by_cred(credp);
9733 	ASSERT(ns != NULL);
9734 	ipst = ns->netstack_ip;
9735 	ASSERT(ipst != NULL);
9736 
9737 	/*
9738 	 * For exclusive stacks we set the zoneid to zero
9739 	 * to make IP operate as if in the global zone.
9740 	 */
9741 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9742 		zoneid = GLOBAL_ZONEID;
9743 	else
9744 		zoneid = crgetzoneid(credp);
9745 
9746 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9747 	q->q_ptr = WR(q)->q_ptr = ill;
9748 	ill->ill_ipst = ipst;
9749 	ill->ill_zoneid = zoneid;
9750 
9751 	/*
9752 	 * ill_init initializes the ill fields and then sends down
9753 	 * down a DL_INFO_REQ after calling qprocson.
9754 	 */
9755 	err = ill_init(q, ill);
9756 	if (err != 0) {
9757 		mi_free(ill);
9758 		netstack_rele(ipst->ips_netstack);
9759 		q->q_ptr = NULL;
9760 		WR(q)->q_ptr = NULL;
9761 		return (err);
9762 	}
9763 
9764 	/* ill_init initializes the ipsq marking this thread as writer */
9765 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9766 	/* Wait for the DL_INFO_ACK */
9767 	mutex_enter(&ill->ill_lock);
9768 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9769 		/*
9770 		 * Return value of 0 indicates a pending signal.
9771 		 */
9772 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9773 		if (err == 0) {
9774 			mutex_exit(&ill->ill_lock);
9775 			(void) ip_close(q, 0);
9776 			return (EINTR);
9777 		}
9778 	}
9779 	mutex_exit(&ill->ill_lock);
9780 
9781 	/*
9782 	 * ip_rput_other could have set an error  in ill_error on
9783 	 * receipt of M_ERROR.
9784 	 */
9785 
9786 	err = ill->ill_error;
9787 	if (err != 0) {
9788 		(void) ip_close(q, 0);
9789 		return (err);
9790 	}
9791 
9792 	ill->ill_credp = credp;
9793 	crhold(credp);
9794 
9795 	mutex_enter(&ipst->ips_ip_mi_lock);
9796 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9797 	    credp);
9798 	mutex_exit(&ipst->ips_ip_mi_lock);
9799 	if (err) {
9800 		(void) ip_close(q, 0);
9801 		return (err);
9802 	}
9803 	return (0);
9804 }
9805 
9806 /* For /dev/ip aka AF_INET open */
9807 int
9808 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9809 {
9810 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9811 }
9812 
9813 /* For /dev/ip6 aka AF_INET6 open */
9814 int
9815 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9816 {
9817 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9818 }
9819 
9820 /* IP open routine. */
9821 int
9822 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9823     boolean_t isv6)
9824 {
9825 	conn_t 		*connp;
9826 	major_t		maj;
9827 	zoneid_t	zoneid;
9828 	netstack_t	*ns;
9829 	ip_stack_t	*ipst;
9830 
9831 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9832 
9833 	/* Allow reopen. */
9834 	if (q->q_ptr != NULL)
9835 		return (0);
9836 
9837 	if (sflag & MODOPEN) {
9838 		/* This is a module open */
9839 		return (ip_modopen(q, devp, flag, sflag, credp));
9840 	}
9841 
9842 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9843 		/*
9844 		 * Non streams based socket looking for a stream
9845 		 * to access IP
9846 		 */
9847 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9848 		    credp, isv6));
9849 	}
9850 
9851 	ns = netstack_find_by_cred(credp);
9852 	ASSERT(ns != NULL);
9853 	ipst = ns->netstack_ip;
9854 	ASSERT(ipst != NULL);
9855 
9856 	/*
9857 	 * For exclusive stacks we set the zoneid to zero
9858 	 * to make IP operate as if in the global zone.
9859 	 */
9860 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9861 		zoneid = GLOBAL_ZONEID;
9862 	else
9863 		zoneid = crgetzoneid(credp);
9864 
9865 	/*
9866 	 * We are opening as a device. This is an IP client stream, and we
9867 	 * allocate an conn_t as the instance data.
9868 	 */
9869 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9870 
9871 	/*
9872 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9873 	 * done by netstack_find_by_cred()
9874 	 */
9875 	netstack_rele(ipst->ips_netstack);
9876 
9877 	connp->conn_zoneid = zoneid;
9878 	connp->conn_sqp = NULL;
9879 	connp->conn_initial_sqp = NULL;
9880 	connp->conn_final_sqp = NULL;
9881 
9882 	connp->conn_upq = q;
9883 	q->q_ptr = WR(q)->q_ptr = connp;
9884 
9885 	if (flag & SO_SOCKSTR)
9886 		connp->conn_flags |= IPCL_SOCKET;
9887 
9888 	/* Minor tells us which /dev entry was opened */
9889 	if (isv6) {
9890 		connp->conn_flags |= IPCL_ISV6;
9891 		connp->conn_af_isv6 = B_TRUE;
9892 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9893 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9894 	} else {
9895 		connp->conn_af_isv6 = B_FALSE;
9896 		connp->conn_pkt_isv6 = B_FALSE;
9897 	}
9898 
9899 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9900 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9901 		connp->conn_minor_arena = ip_minor_arena_la;
9902 	} else {
9903 		/*
9904 		 * Either minor numbers in the large arena were exhausted
9905 		 * or a non socket application is doing the open.
9906 		 * Try to allocate from the small arena.
9907 		 */
9908 		if ((connp->conn_dev =
9909 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9910 			/* CONN_DEC_REF takes care of netstack_rele() */
9911 			q->q_ptr = WR(q)->q_ptr = NULL;
9912 			CONN_DEC_REF(connp);
9913 			return (EBUSY);
9914 		}
9915 		connp->conn_minor_arena = ip_minor_arena_sa;
9916 	}
9917 
9918 	maj = getemajor(*devp);
9919 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9920 
9921 	/*
9922 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9923 	 */
9924 	connp->conn_cred = credp;
9925 
9926 	/*
9927 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9928 	 */
9929 	connp->conn_recv = ip_conn_input;
9930 
9931 	crhold(connp->conn_cred);
9932 
9933 	/*
9934 	 * If the caller has the process-wide flag set, then default to MAC
9935 	 * exempt mode.  This allows read-down to unlabeled hosts.
9936 	 */
9937 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9938 		connp->conn_mac_exempt = B_TRUE;
9939 
9940 	connp->conn_rq = q;
9941 	connp->conn_wq = WR(q);
9942 
9943 	/* Non-zero default values */
9944 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9945 
9946 	/*
9947 	 * Make the conn globally visible to walkers
9948 	 */
9949 	ASSERT(connp->conn_ref == 1);
9950 	mutex_enter(&connp->conn_lock);
9951 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9952 	mutex_exit(&connp->conn_lock);
9953 
9954 	qprocson(q);
9955 
9956 	return (0);
9957 }
9958 
9959 /*
9960  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9961  * Note that there is no race since either ip_output function works - it
9962  * is just an optimization to enter the best ip_output routine directly.
9963  */
9964 void
9965 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9966     ip_stack_t *ipst)
9967 {
9968 	if (isv6)  {
9969 		if (bump_mib) {
9970 			BUMP_MIB(&ipst->ips_ip6_mib,
9971 			    ipIfStatsOutSwitchIPVersion);
9972 		}
9973 		connp->conn_send = ip_output_v6;
9974 		connp->conn_pkt_isv6 = B_TRUE;
9975 	} else {
9976 		if (bump_mib) {
9977 			BUMP_MIB(&ipst->ips_ip_mib,
9978 			    ipIfStatsOutSwitchIPVersion);
9979 		}
9980 		connp->conn_send = ip_output;
9981 		connp->conn_pkt_isv6 = B_FALSE;
9982 	}
9983 
9984 }
9985 
9986 /*
9987  * See if IPsec needs loading because of the options in mp.
9988  */
9989 static boolean_t
9990 ipsec_opt_present(mblk_t *mp)
9991 {
9992 	uint8_t *optcp, *next_optcp, *opt_endcp;
9993 	struct opthdr *opt;
9994 	struct T_opthdr *topt;
9995 	int opthdr_len;
9996 	t_uscalar_t optname, optlevel;
9997 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9998 	ipsec_req_t *ipsr;
9999 
10000 	/*
10001 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10002 	 * return TRUE.
10003 	 */
10004 
10005 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10006 	opt_endcp = optcp + tor->OPT_length;
10007 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10008 		opthdr_len = sizeof (struct T_opthdr);
10009 	} else {		/* O_OPTMGMT_REQ */
10010 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10011 		opthdr_len = sizeof (struct opthdr);
10012 	}
10013 	for (; optcp < opt_endcp; optcp = next_optcp) {
10014 		if (optcp + opthdr_len > opt_endcp)
10015 			return (B_FALSE);	/* Not enough option header. */
10016 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10017 			topt = (struct T_opthdr *)optcp;
10018 			optlevel = topt->level;
10019 			optname = topt->name;
10020 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10021 		} else {
10022 			opt = (struct opthdr *)optcp;
10023 			optlevel = opt->level;
10024 			optname = opt->name;
10025 			next_optcp = optcp + opthdr_len +
10026 			    _TPI_ALIGN_OPT(opt->len);
10027 		}
10028 		if ((next_optcp < optcp) || /* wraparound pointer space */
10029 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10030 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10031 			return (B_FALSE); /* bad option buffer */
10032 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10033 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10034 			/*
10035 			 * Check to see if it's an all-bypass or all-zeroes
10036 			 * IPsec request.  Don't bother loading IPsec if
10037 			 * the socket doesn't want to use it.  (A good example
10038 			 * is a bypass request.)
10039 			 *
10040 			 * Basically, if any of the non-NEVER bits are set,
10041 			 * load IPsec.
10042 			 */
10043 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10044 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10045 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10046 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10047 			    != 0)
10048 				return (B_TRUE);
10049 		}
10050 	}
10051 	return (B_FALSE);
10052 }
10053 
10054 /*
10055  * If conn is is waiting for ipsec to finish loading, kick it.
10056  */
10057 /* ARGSUSED */
10058 static void
10059 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10060 {
10061 	t_scalar_t	optreq_prim;
10062 	mblk_t		*mp;
10063 	cred_t		*cr;
10064 	int		err = 0;
10065 
10066 	/*
10067 	 * This function is called, after ipsec loading is complete.
10068 	 * Since IP checks exclusively and atomically (i.e it prevents
10069 	 * ipsec load from completing until ip_optcom_req completes)
10070 	 * whether ipsec load is complete, there cannot be a race with IP
10071 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10072 	 */
10073 	mutex_enter(&connp->conn_lock);
10074 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10075 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10076 		mp = connp->conn_ipsec_opt_mp;
10077 		connp->conn_ipsec_opt_mp = NULL;
10078 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10079 		mutex_exit(&connp->conn_lock);
10080 
10081 		/*
10082 		 * All Solaris components should pass a db_credp
10083 		 * for this TPI message, hence we ASSERT.
10084 		 * But in case there is some other M_PROTO that looks
10085 		 * like a TPI message sent by some other kernel
10086 		 * component, we check and return an error.
10087 		 */
10088 		cr = msg_getcred(mp, NULL);
10089 		ASSERT(cr != NULL);
10090 		if (cr == NULL) {
10091 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10092 			if (mp != NULL)
10093 				qreply(connp->conn_wq, mp);
10094 			return;
10095 		}
10096 
10097 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10098 
10099 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10100 		if (optreq_prim == T_OPTMGMT_REQ) {
10101 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10102 			    &ip_opt_obj, B_FALSE);
10103 		} else {
10104 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10105 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10106 			    &ip_opt_obj, B_FALSE);
10107 		}
10108 		if (err != EINPROGRESS)
10109 			CONN_OPER_PENDING_DONE(connp);
10110 		return;
10111 	}
10112 	mutex_exit(&connp->conn_lock);
10113 }
10114 
10115 /*
10116  * Called from the ipsec_loader thread, outside any perimeter, to tell
10117  * ip qenable any of the queues waiting for the ipsec loader to
10118  * complete.
10119  */
10120 void
10121 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10122 {
10123 	netstack_t *ns = ipss->ipsec_netstack;
10124 
10125 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10126 }
10127 
10128 /*
10129  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10130  * determines the grp on which it has to become exclusive, queues the mp
10131  * and IPSQ draining restarts the optmgmt
10132  */
10133 static boolean_t
10134 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10135 {
10136 	conn_t *connp = Q_TO_CONN(q);
10137 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10138 
10139 	/*
10140 	 * Take IPsec requests and treat them special.
10141 	 */
10142 	if (ipsec_opt_present(mp)) {
10143 		/* First check if IPsec is loaded. */
10144 		mutex_enter(&ipss->ipsec_loader_lock);
10145 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10146 			mutex_exit(&ipss->ipsec_loader_lock);
10147 			return (B_FALSE);
10148 		}
10149 		mutex_enter(&connp->conn_lock);
10150 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10151 
10152 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10153 		connp->conn_ipsec_opt_mp = mp;
10154 		mutex_exit(&connp->conn_lock);
10155 		mutex_exit(&ipss->ipsec_loader_lock);
10156 
10157 		ipsec_loader_loadnow(ipss);
10158 		return (B_TRUE);
10159 	}
10160 	return (B_FALSE);
10161 }
10162 
10163 /*
10164  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10165  * all of them are copied to the conn_t. If the req is "zero", the policy is
10166  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10167  * fields.
10168  * We keep only the latest setting of the policy and thus policy setting
10169  * is not incremental/cumulative.
10170  *
10171  * Requests to set policies with multiple alternative actions will
10172  * go through a different API.
10173  */
10174 int
10175 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10176 {
10177 	uint_t ah_req = 0;
10178 	uint_t esp_req = 0;
10179 	uint_t se_req = 0;
10180 	ipsec_selkey_t sel;
10181 	ipsec_act_t *actp = NULL;
10182 	uint_t nact;
10183 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10184 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10185 	ipsec_policy_root_t *pr;
10186 	ipsec_policy_head_t *ph;
10187 	int fam;
10188 	boolean_t is_pol_reset;
10189 	int error = 0;
10190 	netstack_t	*ns = connp->conn_netstack;
10191 	ip_stack_t	*ipst = ns->netstack_ip;
10192 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10193 
10194 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10195 
10196 	/*
10197 	 * The IP_SEC_OPT option does not allow variable length parameters,
10198 	 * hence a request cannot be NULL.
10199 	 */
10200 	if (req == NULL)
10201 		return (EINVAL);
10202 
10203 	ah_req = req->ipsr_ah_req;
10204 	esp_req = req->ipsr_esp_req;
10205 	se_req = req->ipsr_self_encap_req;
10206 
10207 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10208 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10209 		return (EINVAL);
10210 
10211 	/*
10212 	 * Are we dealing with a request to reset the policy (i.e.
10213 	 * zero requests).
10214 	 */
10215 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10216 	    (esp_req & REQ_MASK) == 0 &&
10217 	    (se_req & REQ_MASK) == 0);
10218 
10219 	if (!is_pol_reset) {
10220 		/*
10221 		 * If we couldn't load IPsec, fail with "protocol
10222 		 * not supported".
10223 		 * IPsec may not have been loaded for a request with zero
10224 		 * policies, so we don't fail in this case.
10225 		 */
10226 		mutex_enter(&ipss->ipsec_loader_lock);
10227 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10228 			mutex_exit(&ipss->ipsec_loader_lock);
10229 			return (EPROTONOSUPPORT);
10230 		}
10231 		mutex_exit(&ipss->ipsec_loader_lock);
10232 
10233 		/*
10234 		 * Test for valid requests. Invalid algorithms
10235 		 * need to be tested by IPsec code because new
10236 		 * algorithms can be added dynamically.
10237 		 */
10238 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10239 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10240 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10241 			return (EINVAL);
10242 		}
10243 
10244 		/*
10245 		 * Only privileged users can issue these
10246 		 * requests.
10247 		 */
10248 		if (((ah_req & IPSEC_PREF_NEVER) ||
10249 		    (esp_req & IPSEC_PREF_NEVER) ||
10250 		    (se_req & IPSEC_PREF_NEVER)) &&
10251 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10252 			return (EPERM);
10253 		}
10254 
10255 		/*
10256 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10257 		 * are mutually exclusive.
10258 		 */
10259 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10260 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10261 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10262 			/* Both of them are set */
10263 			return (EINVAL);
10264 		}
10265 	}
10266 
10267 	mutex_enter(&connp->conn_lock);
10268 
10269 	/*
10270 	 * If we have already cached policies in ip_bind_connected*(), don't
10271 	 * let them change now. We cache policies for connections
10272 	 * whose src,dst [addr, port] is known.
10273 	 */
10274 	if (connp->conn_policy_cached) {
10275 		mutex_exit(&connp->conn_lock);
10276 		return (EINVAL);
10277 	}
10278 
10279 	/*
10280 	 * We have a zero policies, reset the connection policy if already
10281 	 * set. This will cause the connection to inherit the
10282 	 * global policy, if any.
10283 	 */
10284 	if (is_pol_reset) {
10285 		if (connp->conn_policy != NULL) {
10286 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10287 			connp->conn_policy = NULL;
10288 		}
10289 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10290 		connp->conn_in_enforce_policy = B_FALSE;
10291 		connp->conn_out_enforce_policy = B_FALSE;
10292 		mutex_exit(&connp->conn_lock);
10293 		return (0);
10294 	}
10295 
10296 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10297 	    ipst->ips_netstack);
10298 	if (ph == NULL)
10299 		goto enomem;
10300 
10301 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10302 	if (actp == NULL)
10303 		goto enomem;
10304 
10305 	/*
10306 	 * Always allocate IPv4 policy entries, since they can also
10307 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10308 	 */
10309 	bzero(&sel, sizeof (sel));
10310 	sel.ipsl_valid = IPSL_IPV4;
10311 
10312 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10313 	    ipst->ips_netstack);
10314 	if (pin4 == NULL)
10315 		goto enomem;
10316 
10317 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10318 	    ipst->ips_netstack);
10319 	if (pout4 == NULL)
10320 		goto enomem;
10321 
10322 	if (connp->conn_af_isv6) {
10323 		/*
10324 		 * We're looking at a v6 socket, also allocate the
10325 		 * v6-specific entries...
10326 		 */
10327 		sel.ipsl_valid = IPSL_IPV6;
10328 		pin6 = ipsec_policy_create(&sel, actp, nact,
10329 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10330 		if (pin6 == NULL)
10331 			goto enomem;
10332 
10333 		pout6 = ipsec_policy_create(&sel, actp, nact,
10334 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10335 		if (pout6 == NULL)
10336 			goto enomem;
10337 
10338 		/*
10339 		 * .. and file them away in the right place.
10340 		 */
10341 		fam = IPSEC_AF_V6;
10342 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10343 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10344 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10345 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10346 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10347 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10348 	}
10349 
10350 	ipsec_actvec_free(actp, nact);
10351 
10352 	/*
10353 	 * File the v4 policies.
10354 	 */
10355 	fam = IPSEC_AF_V4;
10356 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10357 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10358 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10359 
10360 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10361 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10362 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10363 
10364 	/*
10365 	 * If the requests need security, set enforce_policy.
10366 	 * If the requests are IPSEC_PREF_NEVER, one should
10367 	 * still set conn_out_enforce_policy so that an ipsec_out
10368 	 * gets attached in ip_wput. This is needed so that
10369 	 * for connections that we don't cache policy in ip_bind,
10370 	 * if global policy matches in ip_wput_attach_policy, we
10371 	 * don't wrongly inherit global policy. Similarly, we need
10372 	 * to set conn_in_enforce_policy also so that we don't verify
10373 	 * policy wrongly.
10374 	 */
10375 	if ((ah_req & REQ_MASK) != 0 ||
10376 	    (esp_req & REQ_MASK) != 0 ||
10377 	    (se_req & REQ_MASK) != 0) {
10378 		connp->conn_in_enforce_policy = B_TRUE;
10379 		connp->conn_out_enforce_policy = B_TRUE;
10380 		connp->conn_flags |= IPCL_CHECK_POLICY;
10381 	}
10382 
10383 	mutex_exit(&connp->conn_lock);
10384 	return (error);
10385 #undef REQ_MASK
10386 
10387 	/*
10388 	 * Common memory-allocation-failure exit path.
10389 	 */
10390 enomem:
10391 	mutex_exit(&connp->conn_lock);
10392 	if (actp != NULL)
10393 		ipsec_actvec_free(actp, nact);
10394 	if (pin4 != NULL)
10395 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10396 	if (pout4 != NULL)
10397 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10398 	if (pin6 != NULL)
10399 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10400 	if (pout6 != NULL)
10401 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10402 	return (ENOMEM);
10403 }
10404 
10405 /*
10406  * Only for options that pass in an IP addr. Currently only V4 options
10407  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10408  * So this function assumes level is IPPROTO_IP
10409  */
10410 int
10411 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10412     mblk_t *first_mp)
10413 {
10414 	ipif_t *ipif = NULL;
10415 	int error;
10416 	ill_t *ill;
10417 	int zoneid;
10418 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10419 
10420 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10421 
10422 	if (addr != INADDR_ANY || checkonly) {
10423 		ASSERT(connp != NULL);
10424 		zoneid = IPCL_ZONEID(connp);
10425 		if (option == IP_NEXTHOP) {
10426 			ipif = ipif_lookup_onlink_addr(addr,
10427 			    connp->conn_zoneid, ipst);
10428 		} else {
10429 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10430 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10431 			    &error, ipst);
10432 		}
10433 		if (ipif == NULL) {
10434 			if (error == EINPROGRESS)
10435 				return (error);
10436 			if ((option == IP_MULTICAST_IF) ||
10437 			    (option == IP_NEXTHOP))
10438 				return (EHOSTUNREACH);
10439 			else
10440 				return (EINVAL);
10441 		} else if (checkonly) {
10442 			if (option == IP_MULTICAST_IF) {
10443 				ill = ipif->ipif_ill;
10444 				/* not supported by the virtual network iface */
10445 				if (IS_VNI(ill)) {
10446 					ipif_refrele(ipif);
10447 					return (EINVAL);
10448 				}
10449 			}
10450 			ipif_refrele(ipif);
10451 			return (0);
10452 		}
10453 		ill = ipif->ipif_ill;
10454 		mutex_enter(&connp->conn_lock);
10455 		mutex_enter(&ill->ill_lock);
10456 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10457 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10458 			mutex_exit(&ill->ill_lock);
10459 			mutex_exit(&connp->conn_lock);
10460 			ipif_refrele(ipif);
10461 			return (option == IP_MULTICAST_IF ?
10462 			    EHOSTUNREACH : EINVAL);
10463 		}
10464 	} else {
10465 		mutex_enter(&connp->conn_lock);
10466 	}
10467 
10468 	/* None of the options below are supported on the VNI */
10469 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10470 		mutex_exit(&ill->ill_lock);
10471 		mutex_exit(&connp->conn_lock);
10472 		ipif_refrele(ipif);
10473 		return (EINVAL);
10474 	}
10475 
10476 	switch (option) {
10477 	case IP_MULTICAST_IF:
10478 		connp->conn_multicast_ipif = ipif;
10479 		break;
10480 	case IP_NEXTHOP:
10481 		connp->conn_nexthop_v4 = addr;
10482 		connp->conn_nexthop_set = B_TRUE;
10483 		break;
10484 	}
10485 
10486 	if (ipif != NULL) {
10487 		mutex_exit(&ill->ill_lock);
10488 		mutex_exit(&connp->conn_lock);
10489 		ipif_refrele(ipif);
10490 		return (0);
10491 	}
10492 	mutex_exit(&connp->conn_lock);
10493 	/* We succeded in cleared the option */
10494 	return (0);
10495 }
10496 
10497 /*
10498  * For options that pass in an ifindex specifying the ill. V6 options always
10499  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10500  */
10501 int
10502 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10503     int level, int option, mblk_t *first_mp)
10504 {
10505 	ill_t *ill = NULL;
10506 	int error = 0;
10507 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10508 
10509 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10510 	if (ifindex != 0) {
10511 		ASSERT(connp != NULL);
10512 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10513 		    first_mp, ip_restart_optmgmt, &error, ipst);
10514 		if (ill != NULL) {
10515 			if (checkonly) {
10516 				/* not supported by the virtual network iface */
10517 				if (IS_VNI(ill)) {
10518 					ill_refrele(ill);
10519 					return (EINVAL);
10520 				}
10521 				ill_refrele(ill);
10522 				return (0);
10523 			}
10524 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10525 			    0, NULL)) {
10526 				ill_refrele(ill);
10527 				ill = NULL;
10528 				mutex_enter(&connp->conn_lock);
10529 				goto setit;
10530 			}
10531 			mutex_enter(&connp->conn_lock);
10532 			mutex_enter(&ill->ill_lock);
10533 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10534 				mutex_exit(&ill->ill_lock);
10535 				mutex_exit(&connp->conn_lock);
10536 				ill_refrele(ill);
10537 				ill = NULL;
10538 				mutex_enter(&connp->conn_lock);
10539 			}
10540 			goto setit;
10541 		} else if (error == EINPROGRESS) {
10542 			return (error);
10543 		} else {
10544 			error = 0;
10545 		}
10546 	}
10547 	mutex_enter(&connp->conn_lock);
10548 setit:
10549 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10550 
10551 	/*
10552 	 * The options below assume that the ILL (if any) transmits and/or
10553 	 * receives traffic. Neither of which is true for the virtual network
10554 	 * interface, so fail setting these on a VNI.
10555 	 */
10556 	if (IS_VNI(ill)) {
10557 		ASSERT(ill != NULL);
10558 		mutex_exit(&ill->ill_lock);
10559 		mutex_exit(&connp->conn_lock);
10560 		ill_refrele(ill);
10561 		return (EINVAL);
10562 	}
10563 
10564 	if (level == IPPROTO_IP) {
10565 		switch (option) {
10566 		case IP_BOUND_IF:
10567 			connp->conn_incoming_ill = ill;
10568 			connp->conn_outgoing_ill = ill;
10569 			break;
10570 
10571 		case IP_MULTICAST_IF:
10572 			/*
10573 			 * This option is an internal special. The socket
10574 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10575 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10576 			 * specifies an ifindex and we try first on V6 ill's.
10577 			 * If we don't find one, we they try using on v4 ill's
10578 			 * intenally and we come here.
10579 			 */
10580 			if (!checkonly && ill != NULL) {
10581 				ipif_t	*ipif;
10582 				ipif = ill->ill_ipif;
10583 
10584 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10585 					mutex_exit(&ill->ill_lock);
10586 					mutex_exit(&connp->conn_lock);
10587 					ill_refrele(ill);
10588 					ill = NULL;
10589 					mutex_enter(&connp->conn_lock);
10590 				} else {
10591 					connp->conn_multicast_ipif = ipif;
10592 				}
10593 			}
10594 			break;
10595 
10596 		case IP_DHCPINIT_IF:
10597 			if (connp->conn_dhcpinit_ill != NULL) {
10598 				/*
10599 				 * We've locked the conn so conn_cleanup_ill()
10600 				 * cannot clear conn_dhcpinit_ill -- so it's
10601 				 * safe to access the ill.
10602 				 */
10603 				ill_t *oill = connp->conn_dhcpinit_ill;
10604 
10605 				ASSERT(oill->ill_dhcpinit != 0);
10606 				atomic_dec_32(&oill->ill_dhcpinit);
10607 				connp->conn_dhcpinit_ill = NULL;
10608 			}
10609 
10610 			if (ill != NULL) {
10611 				connp->conn_dhcpinit_ill = ill;
10612 				atomic_inc_32(&ill->ill_dhcpinit);
10613 			}
10614 			break;
10615 		}
10616 	} else {
10617 		switch (option) {
10618 		case IPV6_BOUND_IF:
10619 			connp->conn_incoming_ill = ill;
10620 			connp->conn_outgoing_ill = ill;
10621 			break;
10622 
10623 		case IPV6_MULTICAST_IF:
10624 			/*
10625 			 * Set conn_multicast_ill to be the IPv6 ill.
10626 			 * Set conn_multicast_ipif to be an IPv4 ipif
10627 			 * for ifindex to make IPv4 mapped addresses
10628 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10629 			 * Even if no IPv6 ill exists for the ifindex
10630 			 * we need to check for an IPv4 ifindex in order
10631 			 * for this to work with mapped addresses. In that
10632 			 * case only set conn_multicast_ipif.
10633 			 */
10634 			if (!checkonly) {
10635 				if (ifindex == 0) {
10636 					connp->conn_multicast_ill = NULL;
10637 					connp->conn_multicast_ipif = NULL;
10638 				} else if (ill != NULL) {
10639 					connp->conn_multicast_ill = ill;
10640 				}
10641 			}
10642 			break;
10643 		}
10644 	}
10645 
10646 	if (ill != NULL) {
10647 		mutex_exit(&ill->ill_lock);
10648 		mutex_exit(&connp->conn_lock);
10649 		ill_refrele(ill);
10650 		return (0);
10651 	}
10652 	mutex_exit(&connp->conn_lock);
10653 	/*
10654 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10655 	 * locate the ill and could not set the option (ifindex != 0)
10656 	 */
10657 	return (ifindex == 0 ? 0 : EINVAL);
10658 }
10659 
10660 /* This routine sets socket options. */
10661 /* ARGSUSED */
10662 int
10663 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10664     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10665     void *dummy, cred_t *cr, mblk_t *first_mp)
10666 {
10667 	int		*i1 = (int *)invalp;
10668 	conn_t		*connp = Q_TO_CONN(q);
10669 	int		error = 0;
10670 	boolean_t	checkonly;
10671 	ire_t		*ire;
10672 	boolean_t	found;
10673 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10674 
10675 	switch (optset_context) {
10676 
10677 	case SETFN_OPTCOM_CHECKONLY:
10678 		checkonly = B_TRUE;
10679 		/*
10680 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10681 		 * inlen != 0 implies value supplied and
10682 		 * 	we have to "pretend" to set it.
10683 		 * inlen == 0 implies that there is no
10684 		 * 	value part in T_CHECK request and just validation
10685 		 * done elsewhere should be enough, we just return here.
10686 		 */
10687 		if (inlen == 0) {
10688 			*outlenp = 0;
10689 			return (0);
10690 		}
10691 		break;
10692 	case SETFN_OPTCOM_NEGOTIATE:
10693 	case SETFN_UD_NEGOTIATE:
10694 	case SETFN_CONN_NEGOTIATE:
10695 		checkonly = B_FALSE;
10696 		break;
10697 	default:
10698 		/*
10699 		 * We should never get here
10700 		 */
10701 		*outlenp = 0;
10702 		return (EINVAL);
10703 	}
10704 
10705 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10706 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10707 
10708 	/*
10709 	 * For fixed length options, no sanity check
10710 	 * of passed in length is done. It is assumed *_optcom_req()
10711 	 * routines do the right thing.
10712 	 */
10713 
10714 	switch (level) {
10715 	case SOL_SOCKET:
10716 		/*
10717 		 * conn_lock protects the bitfields, and is used to
10718 		 * set the fields atomically.
10719 		 */
10720 		switch (name) {
10721 		case SO_BROADCAST:
10722 			if (!checkonly) {
10723 				/* TODO: use value someplace? */
10724 				mutex_enter(&connp->conn_lock);
10725 				connp->conn_broadcast = *i1 ? 1 : 0;
10726 				mutex_exit(&connp->conn_lock);
10727 			}
10728 			break;	/* goto sizeof (int) option return */
10729 		case SO_USELOOPBACK:
10730 			if (!checkonly) {
10731 				/* TODO: use value someplace? */
10732 				mutex_enter(&connp->conn_lock);
10733 				connp->conn_loopback = *i1 ? 1 : 0;
10734 				mutex_exit(&connp->conn_lock);
10735 			}
10736 			break;	/* goto sizeof (int) option return */
10737 		case SO_DONTROUTE:
10738 			if (!checkonly) {
10739 				mutex_enter(&connp->conn_lock);
10740 				connp->conn_dontroute = *i1 ? 1 : 0;
10741 				mutex_exit(&connp->conn_lock);
10742 			}
10743 			break;	/* goto sizeof (int) option return */
10744 		case SO_REUSEADDR:
10745 			if (!checkonly) {
10746 				mutex_enter(&connp->conn_lock);
10747 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10748 				mutex_exit(&connp->conn_lock);
10749 			}
10750 			break;	/* goto sizeof (int) option return */
10751 		case SO_PROTOTYPE:
10752 			if (!checkonly) {
10753 				mutex_enter(&connp->conn_lock);
10754 				connp->conn_proto = *i1;
10755 				mutex_exit(&connp->conn_lock);
10756 			}
10757 			break;	/* goto sizeof (int) option return */
10758 		case SO_ALLZONES:
10759 			if (!checkonly) {
10760 				mutex_enter(&connp->conn_lock);
10761 				if (IPCL_IS_BOUND(connp)) {
10762 					mutex_exit(&connp->conn_lock);
10763 					return (EINVAL);
10764 				}
10765 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10766 				mutex_exit(&connp->conn_lock);
10767 			}
10768 			break;	/* goto sizeof (int) option return */
10769 		case SO_ANON_MLP:
10770 			if (!checkonly) {
10771 				mutex_enter(&connp->conn_lock);
10772 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10773 				mutex_exit(&connp->conn_lock);
10774 			}
10775 			break;	/* goto sizeof (int) option return */
10776 		case SO_MAC_EXEMPT:
10777 			if (secpolicy_net_mac_aware(cr) != 0 ||
10778 			    IPCL_IS_BOUND(connp))
10779 				return (EACCES);
10780 			if (!checkonly) {
10781 				mutex_enter(&connp->conn_lock);
10782 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10783 				mutex_exit(&connp->conn_lock);
10784 			}
10785 			break;	/* goto sizeof (int) option return */
10786 		default:
10787 			/*
10788 			 * "soft" error (negative)
10789 			 * option not handled at this level
10790 			 * Note: Do not modify *outlenp
10791 			 */
10792 			return (-EINVAL);
10793 		}
10794 		break;
10795 	case IPPROTO_IP:
10796 		switch (name) {
10797 		case IP_NEXTHOP:
10798 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10799 				return (EPERM);
10800 			/* FALLTHRU */
10801 		case IP_MULTICAST_IF: {
10802 			ipaddr_t addr = *i1;
10803 
10804 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10805 			    first_mp);
10806 			if (error != 0)
10807 				return (error);
10808 			break;	/* goto sizeof (int) option return */
10809 		}
10810 
10811 		case IP_MULTICAST_TTL:
10812 			/* Recorded in transport above IP */
10813 			*outvalp = *invalp;
10814 			*outlenp = sizeof (uchar_t);
10815 			return (0);
10816 		case IP_MULTICAST_LOOP:
10817 			if (!checkonly) {
10818 				mutex_enter(&connp->conn_lock);
10819 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10820 				mutex_exit(&connp->conn_lock);
10821 			}
10822 			*outvalp = *invalp;
10823 			*outlenp = sizeof (uchar_t);
10824 			return (0);
10825 		case IP_ADD_MEMBERSHIP:
10826 		case MCAST_JOIN_GROUP:
10827 		case IP_DROP_MEMBERSHIP:
10828 		case MCAST_LEAVE_GROUP: {
10829 			struct ip_mreq *mreqp;
10830 			struct group_req *greqp;
10831 			ire_t *ire;
10832 			boolean_t done = B_FALSE;
10833 			ipaddr_t group, ifaddr;
10834 			struct sockaddr_in *sin;
10835 			uint32_t *ifindexp;
10836 			boolean_t mcast_opt = B_TRUE;
10837 			mcast_record_t fmode;
10838 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10839 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10840 
10841 			switch (name) {
10842 			case IP_ADD_MEMBERSHIP:
10843 				mcast_opt = B_FALSE;
10844 				/* FALLTHRU */
10845 			case MCAST_JOIN_GROUP:
10846 				fmode = MODE_IS_EXCLUDE;
10847 				optfn = ip_opt_add_group;
10848 				break;
10849 
10850 			case IP_DROP_MEMBERSHIP:
10851 				mcast_opt = B_FALSE;
10852 				/* FALLTHRU */
10853 			case MCAST_LEAVE_GROUP:
10854 				fmode = MODE_IS_INCLUDE;
10855 				optfn = ip_opt_delete_group;
10856 				break;
10857 			}
10858 
10859 			if (mcast_opt) {
10860 				greqp = (struct group_req *)i1;
10861 				sin = (struct sockaddr_in *)&greqp->gr_group;
10862 				if (sin->sin_family != AF_INET) {
10863 					*outlenp = 0;
10864 					return (ENOPROTOOPT);
10865 				}
10866 				group = (ipaddr_t)sin->sin_addr.s_addr;
10867 				ifaddr = INADDR_ANY;
10868 				ifindexp = &greqp->gr_interface;
10869 			} else {
10870 				mreqp = (struct ip_mreq *)i1;
10871 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10872 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10873 				ifindexp = NULL;
10874 			}
10875 
10876 			/*
10877 			 * In the multirouting case, we need to replicate
10878 			 * the request on all interfaces that will take part
10879 			 * in replication.  We do so because multirouting is
10880 			 * reflective, thus we will probably receive multi-
10881 			 * casts on those interfaces.
10882 			 * The ip_multirt_apply_membership() succeeds if the
10883 			 * operation succeeds on at least one interface.
10884 			 */
10885 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10886 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10887 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10888 			if (ire != NULL) {
10889 				if (ire->ire_flags & RTF_MULTIRT) {
10890 					error = ip_multirt_apply_membership(
10891 					    optfn, ire, connp, checkonly, group,
10892 					    fmode, INADDR_ANY, first_mp);
10893 					done = B_TRUE;
10894 				}
10895 				ire_refrele(ire);
10896 			}
10897 			if (!done) {
10898 				error = optfn(connp, checkonly, group, ifaddr,
10899 				    ifindexp, fmode, INADDR_ANY, first_mp);
10900 			}
10901 			if (error) {
10902 				/*
10903 				 * EINPROGRESS is a soft error, needs retry
10904 				 * so don't make *outlenp zero.
10905 				 */
10906 				if (error != EINPROGRESS)
10907 					*outlenp = 0;
10908 				return (error);
10909 			}
10910 			/* OK return - copy input buffer into output buffer */
10911 			if (invalp != outvalp) {
10912 				/* don't trust bcopy for identical src/dst */
10913 				bcopy(invalp, outvalp, inlen);
10914 			}
10915 			*outlenp = inlen;
10916 			return (0);
10917 		}
10918 		case IP_BLOCK_SOURCE:
10919 		case IP_UNBLOCK_SOURCE:
10920 		case IP_ADD_SOURCE_MEMBERSHIP:
10921 		case IP_DROP_SOURCE_MEMBERSHIP:
10922 		case MCAST_BLOCK_SOURCE:
10923 		case MCAST_UNBLOCK_SOURCE:
10924 		case MCAST_JOIN_SOURCE_GROUP:
10925 		case MCAST_LEAVE_SOURCE_GROUP: {
10926 			struct ip_mreq_source *imreqp;
10927 			struct group_source_req *gsreqp;
10928 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10929 			uint32_t ifindex = 0;
10930 			mcast_record_t fmode;
10931 			struct sockaddr_in *sin;
10932 			ire_t *ire;
10933 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10934 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10935 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10936 
10937 			switch (name) {
10938 			case IP_BLOCK_SOURCE:
10939 				mcast_opt = B_FALSE;
10940 				/* FALLTHRU */
10941 			case MCAST_BLOCK_SOURCE:
10942 				fmode = MODE_IS_EXCLUDE;
10943 				optfn = ip_opt_add_group;
10944 				break;
10945 
10946 			case IP_UNBLOCK_SOURCE:
10947 				mcast_opt = B_FALSE;
10948 				/* FALLTHRU */
10949 			case MCAST_UNBLOCK_SOURCE:
10950 				fmode = MODE_IS_EXCLUDE;
10951 				optfn = ip_opt_delete_group;
10952 				break;
10953 
10954 			case IP_ADD_SOURCE_MEMBERSHIP:
10955 				mcast_opt = B_FALSE;
10956 				/* FALLTHRU */
10957 			case MCAST_JOIN_SOURCE_GROUP:
10958 				fmode = MODE_IS_INCLUDE;
10959 				optfn = ip_opt_add_group;
10960 				break;
10961 
10962 			case IP_DROP_SOURCE_MEMBERSHIP:
10963 				mcast_opt = B_FALSE;
10964 				/* FALLTHRU */
10965 			case MCAST_LEAVE_SOURCE_GROUP:
10966 				fmode = MODE_IS_INCLUDE;
10967 				optfn = ip_opt_delete_group;
10968 				break;
10969 			}
10970 
10971 			if (mcast_opt) {
10972 				gsreqp = (struct group_source_req *)i1;
10973 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10974 					*outlenp = 0;
10975 					return (ENOPROTOOPT);
10976 				}
10977 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10978 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10979 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10980 				src = (ipaddr_t)sin->sin_addr.s_addr;
10981 				ifindex = gsreqp->gsr_interface;
10982 			} else {
10983 				imreqp = (struct ip_mreq_source *)i1;
10984 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10985 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10986 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10987 			}
10988 
10989 			/*
10990 			 * In the multirouting case, we need to replicate
10991 			 * the request as noted in the mcast cases above.
10992 			 */
10993 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10994 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10995 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10996 			if (ire != NULL) {
10997 				if (ire->ire_flags & RTF_MULTIRT) {
10998 					error = ip_multirt_apply_membership(
10999 					    optfn, ire, connp, checkonly, grp,
11000 					    fmode, src, first_mp);
11001 					done = B_TRUE;
11002 				}
11003 				ire_refrele(ire);
11004 			}
11005 			if (!done) {
11006 				error = optfn(connp, checkonly, grp, ifaddr,
11007 				    &ifindex, fmode, src, first_mp);
11008 			}
11009 			if (error != 0) {
11010 				/*
11011 				 * EINPROGRESS is a soft error, needs retry
11012 				 * so don't make *outlenp zero.
11013 				 */
11014 				if (error != EINPROGRESS)
11015 					*outlenp = 0;
11016 				return (error);
11017 			}
11018 			/* OK return - copy input buffer into output buffer */
11019 			if (invalp != outvalp) {
11020 				bcopy(invalp, outvalp, inlen);
11021 			}
11022 			*outlenp = inlen;
11023 			return (0);
11024 		}
11025 		case IP_SEC_OPT:
11026 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11027 			if (error != 0) {
11028 				*outlenp = 0;
11029 				return (error);
11030 			}
11031 			break;
11032 		case IP_HDRINCL:
11033 		case IP_OPTIONS:
11034 		case T_IP_OPTIONS:
11035 		case IP_TOS:
11036 		case T_IP_TOS:
11037 		case IP_TTL:
11038 		case IP_RECVDSTADDR:
11039 		case IP_RECVOPTS:
11040 			/* OK return - copy input buffer into output buffer */
11041 			if (invalp != outvalp) {
11042 				/* don't trust bcopy for identical src/dst */
11043 				bcopy(invalp, outvalp, inlen);
11044 			}
11045 			*outlenp = inlen;
11046 			return (0);
11047 		case IP_RECVIF:
11048 			/* Retrieve the inbound interface index */
11049 			if (!checkonly) {
11050 				mutex_enter(&connp->conn_lock);
11051 				connp->conn_recvif = *i1 ? 1 : 0;
11052 				mutex_exit(&connp->conn_lock);
11053 			}
11054 			break;	/* goto sizeof (int) option return */
11055 		case IP_RECVPKTINFO:
11056 			if (!checkonly) {
11057 				mutex_enter(&connp->conn_lock);
11058 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11059 				mutex_exit(&connp->conn_lock);
11060 			}
11061 			break;	/* goto sizeof (int) option return */
11062 		case IP_RECVSLLA:
11063 			/* Retrieve the source link layer address */
11064 			if (!checkonly) {
11065 				mutex_enter(&connp->conn_lock);
11066 				connp->conn_recvslla = *i1 ? 1 : 0;
11067 				mutex_exit(&connp->conn_lock);
11068 			}
11069 			break;	/* goto sizeof (int) option return */
11070 		case MRT_INIT:
11071 		case MRT_DONE:
11072 		case MRT_ADD_VIF:
11073 		case MRT_DEL_VIF:
11074 		case MRT_ADD_MFC:
11075 		case MRT_DEL_MFC:
11076 		case MRT_ASSERT:
11077 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11078 				*outlenp = 0;
11079 				return (error);
11080 			}
11081 			error = ip_mrouter_set((int)name, q, checkonly,
11082 			    (uchar_t *)invalp, inlen, first_mp);
11083 			if (error) {
11084 				*outlenp = 0;
11085 				return (error);
11086 			}
11087 			/* OK return - copy input buffer into output buffer */
11088 			if (invalp != outvalp) {
11089 				/* don't trust bcopy for identical src/dst */
11090 				bcopy(invalp, outvalp, inlen);
11091 			}
11092 			*outlenp = inlen;
11093 			return (0);
11094 		case IP_BOUND_IF:
11095 		case IP_DHCPINIT_IF:
11096 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11097 			    level, name, first_mp);
11098 			if (error != 0)
11099 				return (error);
11100 			break; 		/* goto sizeof (int) option return */
11101 
11102 		case IP_UNSPEC_SRC:
11103 			/* Allow sending with a zero source address */
11104 			if (!checkonly) {
11105 				mutex_enter(&connp->conn_lock);
11106 				connp->conn_unspec_src = *i1 ? 1 : 0;
11107 				mutex_exit(&connp->conn_lock);
11108 			}
11109 			break;	/* goto sizeof (int) option return */
11110 		default:
11111 			/*
11112 			 * "soft" error (negative)
11113 			 * option not handled at this level
11114 			 * Note: Do not modify *outlenp
11115 			 */
11116 			return (-EINVAL);
11117 		}
11118 		break;
11119 	case IPPROTO_IPV6:
11120 		switch (name) {
11121 		case IPV6_BOUND_IF:
11122 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11123 			    level, name, first_mp);
11124 			if (error != 0)
11125 				return (error);
11126 			break; 		/* goto sizeof (int) option return */
11127 
11128 		case IPV6_MULTICAST_IF:
11129 			/*
11130 			 * The only possible errors are EINPROGRESS and
11131 			 * EINVAL. EINPROGRESS will be restarted and is not
11132 			 * a hard error. We call this option on both V4 and V6
11133 			 * If both return EINVAL, then this call returns
11134 			 * EINVAL. If at least one of them succeeds we
11135 			 * return success.
11136 			 */
11137 			found = B_FALSE;
11138 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11139 			    level, name, first_mp);
11140 			if (error == EINPROGRESS)
11141 				return (error);
11142 			if (error == 0)
11143 				found = B_TRUE;
11144 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11145 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11146 			if (error == 0)
11147 				found = B_TRUE;
11148 			if (!found)
11149 				return (error);
11150 			break; 		/* goto sizeof (int) option return */
11151 
11152 		case IPV6_MULTICAST_HOPS:
11153 			/* Recorded in transport above IP */
11154 			break;	/* goto sizeof (int) option return */
11155 		case IPV6_MULTICAST_LOOP:
11156 			if (!checkonly) {
11157 				mutex_enter(&connp->conn_lock);
11158 				connp->conn_multicast_loop = *i1;
11159 				mutex_exit(&connp->conn_lock);
11160 			}
11161 			break;	/* goto sizeof (int) option return */
11162 		case IPV6_JOIN_GROUP:
11163 		case MCAST_JOIN_GROUP:
11164 		case IPV6_LEAVE_GROUP:
11165 		case MCAST_LEAVE_GROUP: {
11166 			struct ipv6_mreq *ip_mreqp;
11167 			struct group_req *greqp;
11168 			ire_t *ire;
11169 			boolean_t done = B_FALSE;
11170 			in6_addr_t groupv6;
11171 			uint32_t ifindex;
11172 			boolean_t mcast_opt = B_TRUE;
11173 			mcast_record_t fmode;
11174 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11175 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11176 
11177 			switch (name) {
11178 			case IPV6_JOIN_GROUP:
11179 				mcast_opt = B_FALSE;
11180 				/* FALLTHRU */
11181 			case MCAST_JOIN_GROUP:
11182 				fmode = MODE_IS_EXCLUDE;
11183 				optfn = ip_opt_add_group_v6;
11184 				break;
11185 
11186 			case IPV6_LEAVE_GROUP:
11187 				mcast_opt = B_FALSE;
11188 				/* FALLTHRU */
11189 			case MCAST_LEAVE_GROUP:
11190 				fmode = MODE_IS_INCLUDE;
11191 				optfn = ip_opt_delete_group_v6;
11192 				break;
11193 			}
11194 
11195 			if (mcast_opt) {
11196 				struct sockaddr_in *sin;
11197 				struct sockaddr_in6 *sin6;
11198 				greqp = (struct group_req *)i1;
11199 				if (greqp->gr_group.ss_family == AF_INET) {
11200 					sin = (struct sockaddr_in *)
11201 					    &(greqp->gr_group);
11202 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11203 					    &groupv6);
11204 				} else {
11205 					sin6 = (struct sockaddr_in6 *)
11206 					    &(greqp->gr_group);
11207 					groupv6 = sin6->sin6_addr;
11208 				}
11209 				ifindex = greqp->gr_interface;
11210 			} else {
11211 				ip_mreqp = (struct ipv6_mreq *)i1;
11212 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11213 				ifindex = ip_mreqp->ipv6mr_interface;
11214 			}
11215 			/*
11216 			 * In the multirouting case, we need to replicate
11217 			 * the request on all interfaces that will take part
11218 			 * in replication.  We do so because multirouting is
11219 			 * reflective, thus we will probably receive multi-
11220 			 * casts on those interfaces.
11221 			 * The ip_multirt_apply_membership_v6() succeeds if
11222 			 * the operation succeeds on at least one interface.
11223 			 */
11224 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11225 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11226 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11227 			if (ire != NULL) {
11228 				if (ire->ire_flags & RTF_MULTIRT) {
11229 					error = ip_multirt_apply_membership_v6(
11230 					    optfn, ire, connp, checkonly,
11231 					    &groupv6, fmode, &ipv6_all_zeros,
11232 					    first_mp);
11233 					done = B_TRUE;
11234 				}
11235 				ire_refrele(ire);
11236 			}
11237 			if (!done) {
11238 				error = optfn(connp, checkonly, &groupv6,
11239 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11240 			}
11241 			if (error) {
11242 				/*
11243 				 * EINPROGRESS is a soft error, needs retry
11244 				 * so don't make *outlenp zero.
11245 				 */
11246 				if (error != EINPROGRESS)
11247 					*outlenp = 0;
11248 				return (error);
11249 			}
11250 			/* OK return - copy input buffer into output buffer */
11251 			if (invalp != outvalp) {
11252 				/* don't trust bcopy for identical src/dst */
11253 				bcopy(invalp, outvalp, inlen);
11254 			}
11255 			*outlenp = inlen;
11256 			return (0);
11257 		}
11258 		case MCAST_BLOCK_SOURCE:
11259 		case MCAST_UNBLOCK_SOURCE:
11260 		case MCAST_JOIN_SOURCE_GROUP:
11261 		case MCAST_LEAVE_SOURCE_GROUP: {
11262 			struct group_source_req *gsreqp;
11263 			in6_addr_t v6grp, v6src;
11264 			uint32_t ifindex;
11265 			mcast_record_t fmode;
11266 			ire_t *ire;
11267 			boolean_t done = B_FALSE;
11268 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11269 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11270 
11271 			switch (name) {
11272 			case MCAST_BLOCK_SOURCE:
11273 				fmode = MODE_IS_EXCLUDE;
11274 				optfn = ip_opt_add_group_v6;
11275 				break;
11276 			case MCAST_UNBLOCK_SOURCE:
11277 				fmode = MODE_IS_EXCLUDE;
11278 				optfn = ip_opt_delete_group_v6;
11279 				break;
11280 			case MCAST_JOIN_SOURCE_GROUP:
11281 				fmode = MODE_IS_INCLUDE;
11282 				optfn = ip_opt_add_group_v6;
11283 				break;
11284 			case MCAST_LEAVE_SOURCE_GROUP:
11285 				fmode = MODE_IS_INCLUDE;
11286 				optfn = ip_opt_delete_group_v6;
11287 				break;
11288 			}
11289 
11290 			gsreqp = (struct group_source_req *)i1;
11291 			ifindex = gsreqp->gsr_interface;
11292 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11293 				struct sockaddr_in *s;
11294 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11295 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11296 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11297 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11298 			} else {
11299 				struct sockaddr_in6 *s6;
11300 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11301 				v6grp = s6->sin6_addr;
11302 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11303 				v6src = s6->sin6_addr;
11304 			}
11305 
11306 			/*
11307 			 * In the multirouting case, we need to replicate
11308 			 * the request as noted in the mcast cases above.
11309 			 */
11310 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11311 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11312 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11313 			if (ire != NULL) {
11314 				if (ire->ire_flags & RTF_MULTIRT) {
11315 					error = ip_multirt_apply_membership_v6(
11316 					    optfn, ire, connp, checkonly,
11317 					    &v6grp, fmode, &v6src, first_mp);
11318 					done = B_TRUE;
11319 				}
11320 				ire_refrele(ire);
11321 			}
11322 			if (!done) {
11323 				error = optfn(connp, checkonly, &v6grp,
11324 				    ifindex, fmode, &v6src, first_mp);
11325 			}
11326 			if (error != 0) {
11327 				/*
11328 				 * EINPROGRESS is a soft error, needs retry
11329 				 * so don't make *outlenp zero.
11330 				 */
11331 				if (error != EINPROGRESS)
11332 					*outlenp = 0;
11333 				return (error);
11334 			}
11335 			/* OK return - copy input buffer into output buffer */
11336 			if (invalp != outvalp) {
11337 				bcopy(invalp, outvalp, inlen);
11338 			}
11339 			*outlenp = inlen;
11340 			return (0);
11341 		}
11342 		case IPV6_UNICAST_HOPS:
11343 			/* Recorded in transport above IP */
11344 			break;	/* goto sizeof (int) option return */
11345 		case IPV6_UNSPEC_SRC:
11346 			/* Allow sending with a zero source address */
11347 			if (!checkonly) {
11348 				mutex_enter(&connp->conn_lock);
11349 				connp->conn_unspec_src = *i1 ? 1 : 0;
11350 				mutex_exit(&connp->conn_lock);
11351 			}
11352 			break;	/* goto sizeof (int) option return */
11353 		case IPV6_RECVPKTINFO:
11354 			if (!checkonly) {
11355 				mutex_enter(&connp->conn_lock);
11356 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11357 				mutex_exit(&connp->conn_lock);
11358 			}
11359 			break;	/* goto sizeof (int) option return */
11360 		case IPV6_RECVTCLASS:
11361 			if (!checkonly) {
11362 				if (*i1 < 0 || *i1 > 1) {
11363 					return (EINVAL);
11364 				}
11365 				mutex_enter(&connp->conn_lock);
11366 				connp->conn_ipv6_recvtclass = *i1;
11367 				mutex_exit(&connp->conn_lock);
11368 			}
11369 			break;
11370 		case IPV6_RECVPATHMTU:
11371 			if (!checkonly) {
11372 				if (*i1 < 0 || *i1 > 1) {
11373 					return (EINVAL);
11374 				}
11375 				mutex_enter(&connp->conn_lock);
11376 				connp->conn_ipv6_recvpathmtu = *i1;
11377 				mutex_exit(&connp->conn_lock);
11378 			}
11379 			break;
11380 		case IPV6_RECVHOPLIMIT:
11381 			if (!checkonly) {
11382 				mutex_enter(&connp->conn_lock);
11383 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11384 				mutex_exit(&connp->conn_lock);
11385 			}
11386 			break;	/* goto sizeof (int) option return */
11387 		case IPV6_RECVHOPOPTS:
11388 			if (!checkonly) {
11389 				mutex_enter(&connp->conn_lock);
11390 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11391 				mutex_exit(&connp->conn_lock);
11392 			}
11393 			break;	/* goto sizeof (int) option return */
11394 		case IPV6_RECVDSTOPTS:
11395 			if (!checkonly) {
11396 				mutex_enter(&connp->conn_lock);
11397 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11398 				mutex_exit(&connp->conn_lock);
11399 			}
11400 			break;	/* goto sizeof (int) option return */
11401 		case IPV6_RECVRTHDR:
11402 			if (!checkonly) {
11403 				mutex_enter(&connp->conn_lock);
11404 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11405 				mutex_exit(&connp->conn_lock);
11406 			}
11407 			break;	/* goto sizeof (int) option return */
11408 		case IPV6_RECVRTHDRDSTOPTS:
11409 			if (!checkonly) {
11410 				mutex_enter(&connp->conn_lock);
11411 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11412 				mutex_exit(&connp->conn_lock);
11413 			}
11414 			break;	/* goto sizeof (int) option return */
11415 		case IPV6_PKTINFO:
11416 			if (inlen == 0)
11417 				return (-EINVAL);	/* clearing option */
11418 			error = ip6_set_pktinfo(cr, connp,
11419 			    (struct in6_pktinfo *)invalp);
11420 			if (error != 0)
11421 				*outlenp = 0;
11422 			else
11423 				*outlenp = inlen;
11424 			return (error);
11425 		case IPV6_NEXTHOP: {
11426 			struct sockaddr_in6 *sin6;
11427 
11428 			/* Verify that the nexthop is reachable */
11429 			if (inlen == 0)
11430 				return (-EINVAL);	/* clearing option */
11431 
11432 			sin6 = (struct sockaddr_in6 *)invalp;
11433 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11434 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11435 			    NULL, MATCH_IRE_DEFAULT, ipst);
11436 
11437 			if (ire == NULL) {
11438 				*outlenp = 0;
11439 				return (EHOSTUNREACH);
11440 			}
11441 			ire_refrele(ire);
11442 			return (-EINVAL);
11443 		}
11444 		case IPV6_SEC_OPT:
11445 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11446 			if (error != 0) {
11447 				*outlenp = 0;
11448 				return (error);
11449 			}
11450 			break;
11451 		case IPV6_SRC_PREFERENCES: {
11452 			/*
11453 			 * This is implemented strictly in the ip module
11454 			 * (here and in tcp_opt_*() to accomodate tcp
11455 			 * sockets).  Modules above ip pass this option
11456 			 * down here since ip is the only one that needs to
11457 			 * be aware of source address preferences.
11458 			 *
11459 			 * This socket option only affects connected
11460 			 * sockets that haven't already bound to a specific
11461 			 * IPv6 address.  In other words, sockets that
11462 			 * don't call bind() with an address other than the
11463 			 * unspecified address and that call connect().
11464 			 * ip_bind_connected_v6() passes these preferences
11465 			 * to the ipif_select_source_v6() function.
11466 			 */
11467 			if (inlen != sizeof (uint32_t))
11468 				return (EINVAL);
11469 			error = ip6_set_src_preferences(connp,
11470 			    *(uint32_t *)invalp);
11471 			if (error != 0) {
11472 				*outlenp = 0;
11473 				return (error);
11474 			} else {
11475 				*outlenp = sizeof (uint32_t);
11476 			}
11477 			break;
11478 		}
11479 		case IPV6_V6ONLY:
11480 			if (*i1 < 0 || *i1 > 1) {
11481 				return (EINVAL);
11482 			}
11483 			mutex_enter(&connp->conn_lock);
11484 			connp->conn_ipv6_v6only = *i1;
11485 			mutex_exit(&connp->conn_lock);
11486 			break;
11487 		default:
11488 			return (-EINVAL);
11489 		}
11490 		break;
11491 	default:
11492 		/*
11493 		 * "soft" error (negative)
11494 		 * option not handled at this level
11495 		 * Note: Do not modify *outlenp
11496 		 */
11497 		return (-EINVAL);
11498 	}
11499 	/*
11500 	 * Common case of return from an option that is sizeof (int)
11501 	 */
11502 	*(int *)outvalp = *i1;
11503 	*outlenp = sizeof (int);
11504 	return (0);
11505 }
11506 
11507 /*
11508  * This routine gets default values of certain options whose default
11509  * values are maintained by protocol specific code
11510  */
11511 /* ARGSUSED */
11512 int
11513 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11514 {
11515 	int *i1 = (int *)ptr;
11516 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11517 
11518 	switch (level) {
11519 	case IPPROTO_IP:
11520 		switch (name) {
11521 		case IP_MULTICAST_TTL:
11522 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11523 			return (sizeof (uchar_t));
11524 		case IP_MULTICAST_LOOP:
11525 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11526 			return (sizeof (uchar_t));
11527 		default:
11528 			return (-1);
11529 		}
11530 	case IPPROTO_IPV6:
11531 		switch (name) {
11532 		case IPV6_UNICAST_HOPS:
11533 			*i1 = ipst->ips_ipv6_def_hops;
11534 			return (sizeof (int));
11535 		case IPV6_MULTICAST_HOPS:
11536 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11537 			return (sizeof (int));
11538 		case IPV6_MULTICAST_LOOP:
11539 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11540 			return (sizeof (int));
11541 		case IPV6_V6ONLY:
11542 			*i1 = 1;
11543 			return (sizeof (int));
11544 		default:
11545 			return (-1);
11546 		}
11547 	default:
11548 		return (-1);
11549 	}
11550 	/* NOTREACHED */
11551 }
11552 
11553 /*
11554  * Given a destination address and a pointer to where to put the information
11555  * this routine fills in the mtuinfo.
11556  */
11557 int
11558 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11559     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11560 {
11561 	ire_t *ire;
11562 	ip_stack_t	*ipst = ns->netstack_ip;
11563 
11564 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11565 		return (-1);
11566 
11567 	bzero(mtuinfo, sizeof (*mtuinfo));
11568 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11569 	mtuinfo->ip6m_addr.sin6_port = port;
11570 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11571 
11572 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11573 	if (ire != NULL) {
11574 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11575 		ire_refrele(ire);
11576 	} else {
11577 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11578 	}
11579 	return (sizeof (struct ip6_mtuinfo));
11580 }
11581 
11582 /*
11583  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11584  * checking of cred and that ip_g_mrouter is set should be done and
11585  * isn't.  This doesn't matter as the error checking is done properly for the
11586  * other MRT options coming in through ip_opt_set.
11587  */
11588 int
11589 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11590 {
11591 	conn_t		*connp = Q_TO_CONN(q);
11592 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11593 
11594 	switch (level) {
11595 	case IPPROTO_IP:
11596 		switch (name) {
11597 		case MRT_VERSION:
11598 		case MRT_ASSERT:
11599 			(void) ip_mrouter_get(name, q, ptr);
11600 			return (sizeof (int));
11601 		case IP_SEC_OPT:
11602 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11603 		case IP_NEXTHOP:
11604 			if (connp->conn_nexthop_set) {
11605 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11606 				return (sizeof (ipaddr_t));
11607 			} else
11608 				return (0);
11609 		case IP_RECVPKTINFO:
11610 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11611 			return (sizeof (int));
11612 		default:
11613 			break;
11614 		}
11615 		break;
11616 	case IPPROTO_IPV6:
11617 		switch (name) {
11618 		case IPV6_SEC_OPT:
11619 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11620 		case IPV6_SRC_PREFERENCES: {
11621 			return (ip6_get_src_preferences(connp,
11622 			    (uint32_t *)ptr));
11623 		}
11624 		case IPV6_V6ONLY:
11625 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11626 			return (sizeof (int));
11627 		case IPV6_PATHMTU:
11628 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11629 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11630 		default:
11631 			break;
11632 		}
11633 		break;
11634 	default:
11635 		break;
11636 	}
11637 	return (-1);
11638 }
11639 /* Named Dispatch routine to get a current value out of our parameter table. */
11640 /* ARGSUSED */
11641 static int
11642 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11643 {
11644 	ipparam_t *ippa = (ipparam_t *)cp;
11645 
11646 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11647 	return (0);
11648 }
11649 
11650 /* ARGSUSED */
11651 static int
11652 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11653 {
11654 
11655 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11656 	return (0);
11657 }
11658 
11659 /*
11660  * Set ip{,6}_forwarding values.  This means walking through all of the
11661  * ill's and toggling their forwarding values.
11662  */
11663 /* ARGSUSED */
11664 static int
11665 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11666 {
11667 	long new_value;
11668 	int *forwarding_value = (int *)cp;
11669 	ill_t *ill;
11670 	boolean_t isv6;
11671 	ill_walk_context_t ctx;
11672 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11673 
11674 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11675 
11676 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11677 	    new_value < 0 || new_value > 1) {
11678 		return (EINVAL);
11679 	}
11680 
11681 	*forwarding_value = new_value;
11682 
11683 	/*
11684 	 * Regardless of the current value of ip_forwarding, set all per-ill
11685 	 * values of ip_forwarding to the value being set.
11686 	 *
11687 	 * Bring all the ill's up to date with the new global value.
11688 	 */
11689 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11690 
11691 	if (isv6)
11692 		ill = ILL_START_WALK_V6(&ctx, ipst);
11693 	else
11694 		ill = ILL_START_WALK_V4(&ctx, ipst);
11695 
11696 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11697 		(void) ill_forward_set(ill, new_value != 0);
11698 
11699 	rw_exit(&ipst->ips_ill_g_lock);
11700 	return (0);
11701 }
11702 
11703 /*
11704  * Walk through the param array specified registering each element with the
11705  * Named Dispatch handler. This is called only during init. So it is ok
11706  * not to acquire any locks
11707  */
11708 static boolean_t
11709 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11710     ipndp_t *ipnd, size_t ipnd_cnt)
11711 {
11712 	for (; ippa_cnt-- > 0; ippa++) {
11713 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11714 			if (!nd_load(ndp, ippa->ip_param_name,
11715 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11716 				nd_free(ndp);
11717 				return (B_FALSE);
11718 			}
11719 		}
11720 	}
11721 
11722 	for (; ipnd_cnt-- > 0; ipnd++) {
11723 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11724 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11725 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11726 			    ipnd->ip_ndp_data)) {
11727 				nd_free(ndp);
11728 				return (B_FALSE);
11729 			}
11730 		}
11731 	}
11732 
11733 	return (B_TRUE);
11734 }
11735 
11736 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11737 /* ARGSUSED */
11738 static int
11739 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11740 {
11741 	long		new_value;
11742 	ipparam_t	*ippa = (ipparam_t *)cp;
11743 
11744 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11745 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11746 		return (EINVAL);
11747 	}
11748 	ippa->ip_param_value = new_value;
11749 	return (0);
11750 }
11751 
11752 /*
11753  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11754  * When an ipf is passed here for the first time, if
11755  * we already have in-order fragments on the queue, we convert from the fast-
11756  * path reassembly scheme to the hard-case scheme.  From then on, additional
11757  * fragments are reassembled here.  We keep track of the start and end offsets
11758  * of each piece, and the number of holes in the chain.  When the hole count
11759  * goes to zero, we are done!
11760  *
11761  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11762  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11763  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11764  * after the call to ip_reassemble().
11765  */
11766 int
11767 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11768     size_t msg_len)
11769 {
11770 	uint_t	end;
11771 	mblk_t	*next_mp;
11772 	mblk_t	*mp1;
11773 	uint_t	offset;
11774 	boolean_t incr_dups = B_TRUE;
11775 	boolean_t offset_zero_seen = B_FALSE;
11776 	boolean_t pkt_boundary_checked = B_FALSE;
11777 
11778 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11779 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11780 
11781 	/* Add in byte count */
11782 	ipf->ipf_count += msg_len;
11783 	if (ipf->ipf_end) {
11784 		/*
11785 		 * We were part way through in-order reassembly, but now there
11786 		 * is a hole.  We walk through messages already queued, and
11787 		 * mark them for hard case reassembly.  We know that up till
11788 		 * now they were in order starting from offset zero.
11789 		 */
11790 		offset = 0;
11791 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11792 			IP_REASS_SET_START(mp1, offset);
11793 			if (offset == 0) {
11794 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11795 				offset = -ipf->ipf_nf_hdr_len;
11796 			}
11797 			offset += mp1->b_wptr - mp1->b_rptr;
11798 			IP_REASS_SET_END(mp1, offset);
11799 		}
11800 		/* One hole at the end. */
11801 		ipf->ipf_hole_cnt = 1;
11802 		/* Brand it as a hard case, forever. */
11803 		ipf->ipf_end = 0;
11804 	}
11805 	/* Walk through all the new pieces. */
11806 	do {
11807 		end = start + (mp->b_wptr - mp->b_rptr);
11808 		/*
11809 		 * If start is 0, decrease 'end' only for the first mblk of
11810 		 * the fragment. Otherwise 'end' can get wrong value in the
11811 		 * second pass of the loop if first mblk is exactly the
11812 		 * size of ipf_nf_hdr_len.
11813 		 */
11814 		if (start == 0 && !offset_zero_seen) {
11815 			/* First segment */
11816 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11817 			end -= ipf->ipf_nf_hdr_len;
11818 			offset_zero_seen = B_TRUE;
11819 		}
11820 		next_mp = mp->b_cont;
11821 		/*
11822 		 * We are checking to see if there is any interesing data
11823 		 * to process.  If there isn't and the mblk isn't the
11824 		 * one which carries the unfragmentable header then we
11825 		 * drop it.  It's possible to have just the unfragmentable
11826 		 * header come through without any data.  That needs to be
11827 		 * saved.
11828 		 *
11829 		 * If the assert at the top of this function holds then the
11830 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11831 		 * is infrequently traveled enough that the test is left in
11832 		 * to protect against future code changes which break that
11833 		 * invariant.
11834 		 */
11835 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11836 			/* Empty.  Blast it. */
11837 			IP_REASS_SET_START(mp, 0);
11838 			IP_REASS_SET_END(mp, 0);
11839 			/*
11840 			 * If the ipf points to the mblk we are about to free,
11841 			 * update ipf to point to the next mblk (or NULL
11842 			 * if none).
11843 			 */
11844 			if (ipf->ipf_mp->b_cont == mp)
11845 				ipf->ipf_mp->b_cont = next_mp;
11846 			freeb(mp);
11847 			continue;
11848 		}
11849 		mp->b_cont = NULL;
11850 		IP_REASS_SET_START(mp, start);
11851 		IP_REASS_SET_END(mp, end);
11852 		if (!ipf->ipf_tail_mp) {
11853 			ipf->ipf_tail_mp = mp;
11854 			ipf->ipf_mp->b_cont = mp;
11855 			if (start == 0 || !more) {
11856 				ipf->ipf_hole_cnt = 1;
11857 				/*
11858 				 * if the first fragment comes in more than one
11859 				 * mblk, this loop will be executed for each
11860 				 * mblk. Need to adjust hole count so exiting
11861 				 * this routine will leave hole count at 1.
11862 				 */
11863 				if (next_mp)
11864 					ipf->ipf_hole_cnt++;
11865 			} else
11866 				ipf->ipf_hole_cnt = 2;
11867 			continue;
11868 		} else if (ipf->ipf_last_frag_seen && !more &&
11869 		    !pkt_boundary_checked) {
11870 			/*
11871 			 * We check datagram boundary only if this fragment
11872 			 * claims to be the last fragment and we have seen a
11873 			 * last fragment in the past too. We do this only
11874 			 * once for a given fragment.
11875 			 *
11876 			 * start cannot be 0 here as fragments with start=0
11877 			 * and MF=0 gets handled as a complete packet. These
11878 			 * fragments should not reach here.
11879 			 */
11880 
11881 			if (start + msgdsize(mp) !=
11882 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11883 				/*
11884 				 * We have two fragments both of which claim
11885 				 * to be the last fragment but gives conflicting
11886 				 * information about the whole datagram size.
11887 				 * Something fishy is going on. Drop the
11888 				 * fragment and free up the reassembly list.
11889 				 */
11890 				return (IP_REASS_FAILED);
11891 			}
11892 
11893 			/*
11894 			 * We shouldn't come to this code block again for this
11895 			 * particular fragment.
11896 			 */
11897 			pkt_boundary_checked = B_TRUE;
11898 		}
11899 
11900 		/* New stuff at or beyond tail? */
11901 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11902 		if (start >= offset) {
11903 			if (ipf->ipf_last_frag_seen) {
11904 				/* current fragment is beyond last fragment */
11905 				return (IP_REASS_FAILED);
11906 			}
11907 			/* Link it on end. */
11908 			ipf->ipf_tail_mp->b_cont = mp;
11909 			ipf->ipf_tail_mp = mp;
11910 			if (more) {
11911 				if (start != offset)
11912 					ipf->ipf_hole_cnt++;
11913 			} else if (start == offset && next_mp == NULL)
11914 					ipf->ipf_hole_cnt--;
11915 			continue;
11916 		}
11917 		mp1 = ipf->ipf_mp->b_cont;
11918 		offset = IP_REASS_START(mp1);
11919 		/* New stuff at the front? */
11920 		if (start < offset) {
11921 			if (start == 0) {
11922 				if (end >= offset) {
11923 					/* Nailed the hole at the begining. */
11924 					ipf->ipf_hole_cnt--;
11925 				}
11926 			} else if (end < offset) {
11927 				/*
11928 				 * A hole, stuff, and a hole where there used
11929 				 * to be just a hole.
11930 				 */
11931 				ipf->ipf_hole_cnt++;
11932 			}
11933 			mp->b_cont = mp1;
11934 			/* Check for overlap. */
11935 			while (end > offset) {
11936 				if (end < IP_REASS_END(mp1)) {
11937 					mp->b_wptr -= end - offset;
11938 					IP_REASS_SET_END(mp, offset);
11939 					BUMP_MIB(ill->ill_ip_mib,
11940 					    ipIfStatsReasmPartDups);
11941 					break;
11942 				}
11943 				/* Did we cover another hole? */
11944 				if ((mp1->b_cont &&
11945 				    IP_REASS_END(mp1) !=
11946 				    IP_REASS_START(mp1->b_cont) &&
11947 				    end >= IP_REASS_START(mp1->b_cont)) ||
11948 				    (!ipf->ipf_last_frag_seen && !more)) {
11949 					ipf->ipf_hole_cnt--;
11950 				}
11951 				/* Clip out mp1. */
11952 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11953 					/*
11954 					 * After clipping out mp1, this guy
11955 					 * is now hanging off the end.
11956 					 */
11957 					ipf->ipf_tail_mp = mp;
11958 				}
11959 				IP_REASS_SET_START(mp1, 0);
11960 				IP_REASS_SET_END(mp1, 0);
11961 				/* Subtract byte count */
11962 				ipf->ipf_count -= mp1->b_datap->db_lim -
11963 				    mp1->b_datap->db_base;
11964 				freeb(mp1);
11965 				BUMP_MIB(ill->ill_ip_mib,
11966 				    ipIfStatsReasmPartDups);
11967 				mp1 = mp->b_cont;
11968 				if (!mp1)
11969 					break;
11970 				offset = IP_REASS_START(mp1);
11971 			}
11972 			ipf->ipf_mp->b_cont = mp;
11973 			continue;
11974 		}
11975 		/*
11976 		 * The new piece starts somewhere between the start of the head
11977 		 * and before the end of the tail.
11978 		 */
11979 		for (; mp1; mp1 = mp1->b_cont) {
11980 			offset = IP_REASS_END(mp1);
11981 			if (start < offset) {
11982 				if (end <= offset) {
11983 					/* Nothing new. */
11984 					IP_REASS_SET_START(mp, 0);
11985 					IP_REASS_SET_END(mp, 0);
11986 					/* Subtract byte count */
11987 					ipf->ipf_count -= mp->b_datap->db_lim -
11988 					    mp->b_datap->db_base;
11989 					if (incr_dups) {
11990 						ipf->ipf_num_dups++;
11991 						incr_dups = B_FALSE;
11992 					}
11993 					freeb(mp);
11994 					BUMP_MIB(ill->ill_ip_mib,
11995 					    ipIfStatsReasmDuplicates);
11996 					break;
11997 				}
11998 				/*
11999 				 * Trim redundant stuff off beginning of new
12000 				 * piece.
12001 				 */
12002 				IP_REASS_SET_START(mp, offset);
12003 				mp->b_rptr += offset - start;
12004 				BUMP_MIB(ill->ill_ip_mib,
12005 				    ipIfStatsReasmPartDups);
12006 				start = offset;
12007 				if (!mp1->b_cont) {
12008 					/*
12009 					 * After trimming, this guy is now
12010 					 * hanging off the end.
12011 					 */
12012 					mp1->b_cont = mp;
12013 					ipf->ipf_tail_mp = mp;
12014 					if (!more) {
12015 						ipf->ipf_hole_cnt--;
12016 					}
12017 					break;
12018 				}
12019 			}
12020 			if (start >= IP_REASS_START(mp1->b_cont))
12021 				continue;
12022 			/* Fill a hole */
12023 			if (start > offset)
12024 				ipf->ipf_hole_cnt++;
12025 			mp->b_cont = mp1->b_cont;
12026 			mp1->b_cont = mp;
12027 			mp1 = mp->b_cont;
12028 			offset = IP_REASS_START(mp1);
12029 			if (end >= offset) {
12030 				ipf->ipf_hole_cnt--;
12031 				/* Check for overlap. */
12032 				while (end > offset) {
12033 					if (end < IP_REASS_END(mp1)) {
12034 						mp->b_wptr -= end - offset;
12035 						IP_REASS_SET_END(mp, offset);
12036 						/*
12037 						 * TODO we might bump
12038 						 * this up twice if there is
12039 						 * overlap at both ends.
12040 						 */
12041 						BUMP_MIB(ill->ill_ip_mib,
12042 						    ipIfStatsReasmPartDups);
12043 						break;
12044 					}
12045 					/* Did we cover another hole? */
12046 					if ((mp1->b_cont &&
12047 					    IP_REASS_END(mp1)
12048 					    != IP_REASS_START(mp1->b_cont) &&
12049 					    end >=
12050 					    IP_REASS_START(mp1->b_cont)) ||
12051 					    (!ipf->ipf_last_frag_seen &&
12052 					    !more)) {
12053 						ipf->ipf_hole_cnt--;
12054 					}
12055 					/* Clip out mp1. */
12056 					if ((mp->b_cont = mp1->b_cont) ==
12057 					    NULL) {
12058 						/*
12059 						 * After clipping out mp1,
12060 						 * this guy is now hanging
12061 						 * off the end.
12062 						 */
12063 						ipf->ipf_tail_mp = mp;
12064 					}
12065 					IP_REASS_SET_START(mp1, 0);
12066 					IP_REASS_SET_END(mp1, 0);
12067 					/* Subtract byte count */
12068 					ipf->ipf_count -=
12069 					    mp1->b_datap->db_lim -
12070 					    mp1->b_datap->db_base;
12071 					freeb(mp1);
12072 					BUMP_MIB(ill->ill_ip_mib,
12073 					    ipIfStatsReasmPartDups);
12074 					mp1 = mp->b_cont;
12075 					if (!mp1)
12076 						break;
12077 					offset = IP_REASS_START(mp1);
12078 				}
12079 			}
12080 			break;
12081 		}
12082 	} while (start = end, mp = next_mp);
12083 
12084 	/* Fragment just processed could be the last one. Remember this fact */
12085 	if (!more)
12086 		ipf->ipf_last_frag_seen = B_TRUE;
12087 
12088 	/* Still got holes? */
12089 	if (ipf->ipf_hole_cnt)
12090 		return (IP_REASS_PARTIAL);
12091 	/* Clean up overloaded fields to avoid upstream disasters. */
12092 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12093 		IP_REASS_SET_START(mp1, 0);
12094 		IP_REASS_SET_END(mp1, 0);
12095 	}
12096 	return (IP_REASS_COMPLETE);
12097 }
12098 
12099 /*
12100  * ipsec processing for the fast path, used for input UDP Packets
12101  * Returns true if ready for passup to UDP.
12102  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12103  * was an ESP-in-UDP packet, etc.).
12104  */
12105 static boolean_t
12106 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12107     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12108 {
12109 	uint32_t	ill_index;
12110 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12111 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12112 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12113 	udp_t		*udp = connp->conn_udp;
12114 
12115 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12116 	/* The ill_index of the incoming ILL */
12117 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12118 
12119 	/* pass packet up to the transport */
12120 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12121 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12122 		    NULL, mctl_present);
12123 		if (*first_mpp == NULL) {
12124 			return (B_FALSE);
12125 		}
12126 	}
12127 
12128 	/* Initiate IPPF processing for fastpath UDP */
12129 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12130 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12131 		if (*mpp == NULL) {
12132 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12133 			    "deferred/dropped during IPPF processing\n"));
12134 			return (B_FALSE);
12135 		}
12136 	}
12137 	/*
12138 	 * Remove 0-spi if it's 0, or move everything behind
12139 	 * the UDP header over it and forward to ESP via
12140 	 * ip_proto_input().
12141 	 */
12142 	if (udp->udp_nat_t_endpoint) {
12143 		if (mctl_present) {
12144 			/* mctl_present *shouldn't* happen. */
12145 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12146 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12147 			    &ipss->ipsec_dropper);
12148 			*first_mpp = NULL;
12149 			return (B_FALSE);
12150 		}
12151 
12152 		/* "ill" is "recv_ill" in actuality. */
12153 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12154 			return (B_FALSE);
12155 
12156 		/* Else continue like a normal UDP packet. */
12157 	}
12158 
12159 	/*
12160 	 * We make the checks as below since we are in the fast path
12161 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12162 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12163 	 */
12164 	if (connp->conn_recvif || connp->conn_recvslla ||
12165 	    connp->conn_ip_recvpktinfo) {
12166 		if (connp->conn_recvif) {
12167 			in_flags = IPF_RECVIF;
12168 		}
12169 		/*
12170 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12171 		 * so the flag passed to ip_add_info is based on IP version
12172 		 * of connp.
12173 		 */
12174 		if (connp->conn_ip_recvpktinfo) {
12175 			if (connp->conn_af_isv6) {
12176 				/*
12177 				 * V6 only needs index
12178 				 */
12179 				in_flags |= IPF_RECVIF;
12180 			} else {
12181 				/*
12182 				 * V4 needs index + matching address.
12183 				 */
12184 				in_flags |= IPF_RECVADDR;
12185 			}
12186 		}
12187 		if (connp->conn_recvslla) {
12188 			in_flags |= IPF_RECVSLLA;
12189 		}
12190 		/*
12191 		 * since in_flags are being set ill will be
12192 		 * referenced in ip_add_info, so it better not
12193 		 * be NULL.
12194 		 */
12195 		/*
12196 		 * the actual data will be contained in b_cont
12197 		 * upon successful return of the following call.
12198 		 * If the call fails then the original mblk is
12199 		 * returned.
12200 		 */
12201 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12202 		    ipst);
12203 	}
12204 
12205 	return (B_TRUE);
12206 }
12207 
12208 /*
12209  * Fragmentation reassembly.  Each ILL has a hash table for
12210  * queuing packets undergoing reassembly for all IPIFs
12211  * associated with the ILL.  The hash is based on the packet
12212  * IP ident field.  The ILL frag hash table was allocated
12213  * as a timer block at the time the ILL was created.  Whenever
12214  * there is anything on the reassembly queue, the timer will
12215  * be running.  Returns B_TRUE if successful else B_FALSE;
12216  * frees mp on failure.
12217  */
12218 static boolean_t
12219 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12220     uint32_t *cksum_val, uint16_t *cksum_flags)
12221 {
12222 	uint32_t	frag_offset_flags;
12223 	mblk_t		*mp = *mpp;
12224 	mblk_t		*t_mp;
12225 	ipaddr_t	dst;
12226 	uint8_t		proto = ipha->ipha_protocol;
12227 	uint32_t	sum_val;
12228 	uint16_t	sum_flags;
12229 	ipf_t		*ipf;
12230 	ipf_t		**ipfp;
12231 	ipfb_t		*ipfb;
12232 	uint16_t	ident;
12233 	uint32_t	offset;
12234 	ipaddr_t	src;
12235 	uint_t		hdr_length;
12236 	uint32_t	end;
12237 	mblk_t		*mp1;
12238 	mblk_t		*tail_mp;
12239 	size_t		count;
12240 	size_t		msg_len;
12241 	uint8_t		ecn_info = 0;
12242 	uint32_t	packet_size;
12243 	boolean_t	pruned = B_FALSE;
12244 	ip_stack_t *ipst = ill->ill_ipst;
12245 
12246 	if (cksum_val != NULL)
12247 		*cksum_val = 0;
12248 	if (cksum_flags != NULL)
12249 		*cksum_flags = 0;
12250 
12251 	/*
12252 	 * Drop the fragmented as early as possible, if
12253 	 * we don't have resource(s) to re-assemble.
12254 	 */
12255 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12256 		freemsg(mp);
12257 		return (B_FALSE);
12258 	}
12259 
12260 	/* Check for fragmentation offset; return if there's none */
12261 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12262 	    (IPH_MF | IPH_OFFSET)) == 0)
12263 		return (B_TRUE);
12264 
12265 	/*
12266 	 * We utilize hardware computed checksum info only for UDP since
12267 	 * IP fragmentation is a normal occurrence for the protocol.  In
12268 	 * addition, checksum offload support for IP fragments carrying
12269 	 * UDP payload is commonly implemented across network adapters.
12270 	 */
12271 	ASSERT(recv_ill != NULL);
12272 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12273 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12274 		mblk_t *mp1 = mp->b_cont;
12275 		int32_t len;
12276 
12277 		/* Record checksum information from the packet */
12278 		sum_val = (uint32_t)DB_CKSUM16(mp);
12279 		sum_flags = DB_CKSUMFLAGS(mp);
12280 
12281 		/* IP payload offset from beginning of mblk */
12282 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12283 
12284 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12285 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12286 		    offset >= DB_CKSUMSTART(mp) &&
12287 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12288 			uint32_t adj;
12289 			/*
12290 			 * Partial checksum has been calculated by hardware
12291 			 * and attached to the packet; in addition, any
12292 			 * prepended extraneous data is even byte aligned.
12293 			 * If any such data exists, we adjust the checksum;
12294 			 * this would also handle any postpended data.
12295 			 */
12296 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12297 			    mp, mp1, len, adj);
12298 
12299 			/* One's complement subtract extraneous checksum */
12300 			if (adj >= sum_val)
12301 				sum_val = ~(adj - sum_val) & 0xFFFF;
12302 			else
12303 				sum_val -= adj;
12304 		}
12305 	} else {
12306 		sum_val = 0;
12307 		sum_flags = 0;
12308 	}
12309 
12310 	/* Clear hardware checksumming flag */
12311 	DB_CKSUMFLAGS(mp) = 0;
12312 
12313 	ident = ipha->ipha_ident;
12314 	offset = (frag_offset_flags << 3) & 0xFFFF;
12315 	src = ipha->ipha_src;
12316 	dst = ipha->ipha_dst;
12317 	hdr_length = IPH_HDR_LENGTH(ipha);
12318 	end = ntohs(ipha->ipha_length) - hdr_length;
12319 
12320 	/* If end == 0 then we have a packet with no data, so just free it */
12321 	if (end == 0) {
12322 		freemsg(mp);
12323 		return (B_FALSE);
12324 	}
12325 
12326 	/* Record the ECN field info. */
12327 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12328 	if (offset != 0) {
12329 		/*
12330 		 * If this isn't the first piece, strip the header, and
12331 		 * add the offset to the end value.
12332 		 */
12333 		mp->b_rptr += hdr_length;
12334 		end += offset;
12335 	}
12336 
12337 	msg_len = MBLKSIZE(mp);
12338 	tail_mp = mp;
12339 	while (tail_mp->b_cont != NULL) {
12340 		tail_mp = tail_mp->b_cont;
12341 		msg_len += MBLKSIZE(tail_mp);
12342 	}
12343 
12344 	/* If the reassembly list for this ILL will get too big, prune it */
12345 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12346 	    ipst->ips_ip_reass_queue_bytes) {
12347 		ill_frag_prune(ill,
12348 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12349 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12350 		pruned = B_TRUE;
12351 	}
12352 
12353 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12354 	mutex_enter(&ipfb->ipfb_lock);
12355 
12356 	ipfp = &ipfb->ipfb_ipf;
12357 	/* Try to find an existing fragment queue for this packet. */
12358 	for (;;) {
12359 		ipf = ipfp[0];
12360 		if (ipf != NULL) {
12361 			/*
12362 			 * It has to match on ident and src/dst address.
12363 			 */
12364 			if (ipf->ipf_ident == ident &&
12365 			    ipf->ipf_src == src &&
12366 			    ipf->ipf_dst == dst &&
12367 			    ipf->ipf_protocol == proto) {
12368 				/*
12369 				 * If we have received too many
12370 				 * duplicate fragments for this packet
12371 				 * free it.
12372 				 */
12373 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12374 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12375 					freemsg(mp);
12376 					mutex_exit(&ipfb->ipfb_lock);
12377 					return (B_FALSE);
12378 				}
12379 				/* Found it. */
12380 				break;
12381 			}
12382 			ipfp = &ipf->ipf_hash_next;
12383 			continue;
12384 		}
12385 
12386 		/*
12387 		 * If we pruned the list, do we want to store this new
12388 		 * fragment?. We apply an optimization here based on the
12389 		 * fact that most fragments will be received in order.
12390 		 * So if the offset of this incoming fragment is zero,
12391 		 * it is the first fragment of a new packet. We will
12392 		 * keep it.  Otherwise drop the fragment, as we have
12393 		 * probably pruned the packet already (since the
12394 		 * packet cannot be found).
12395 		 */
12396 		if (pruned && offset != 0) {
12397 			mutex_exit(&ipfb->ipfb_lock);
12398 			freemsg(mp);
12399 			return (B_FALSE);
12400 		}
12401 
12402 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12403 			/*
12404 			 * Too many fragmented packets in this hash
12405 			 * bucket. Free the oldest.
12406 			 */
12407 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12408 		}
12409 
12410 		/* New guy.  Allocate a frag message. */
12411 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12412 		if (mp1 == NULL) {
12413 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12414 			freemsg(mp);
12415 reass_done:
12416 			mutex_exit(&ipfb->ipfb_lock);
12417 			return (B_FALSE);
12418 		}
12419 
12420 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12421 		mp1->b_cont = mp;
12422 
12423 		/* Initialize the fragment header. */
12424 		ipf = (ipf_t *)mp1->b_rptr;
12425 		ipf->ipf_mp = mp1;
12426 		ipf->ipf_ptphn = ipfp;
12427 		ipfp[0] = ipf;
12428 		ipf->ipf_hash_next = NULL;
12429 		ipf->ipf_ident = ident;
12430 		ipf->ipf_protocol = proto;
12431 		ipf->ipf_src = src;
12432 		ipf->ipf_dst = dst;
12433 		ipf->ipf_nf_hdr_len = 0;
12434 		/* Record reassembly start time. */
12435 		ipf->ipf_timestamp = gethrestime_sec();
12436 		/* Record ipf generation and account for frag header */
12437 		ipf->ipf_gen = ill->ill_ipf_gen++;
12438 		ipf->ipf_count = MBLKSIZE(mp1);
12439 		ipf->ipf_last_frag_seen = B_FALSE;
12440 		ipf->ipf_ecn = ecn_info;
12441 		ipf->ipf_num_dups = 0;
12442 		ipfb->ipfb_frag_pkts++;
12443 		ipf->ipf_checksum = 0;
12444 		ipf->ipf_checksum_flags = 0;
12445 
12446 		/* Store checksum value in fragment header */
12447 		if (sum_flags != 0) {
12448 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12449 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12450 			ipf->ipf_checksum = sum_val;
12451 			ipf->ipf_checksum_flags = sum_flags;
12452 		}
12453 
12454 		/*
12455 		 * We handle reassembly two ways.  In the easy case,
12456 		 * where all the fragments show up in order, we do
12457 		 * minimal bookkeeping, and just clip new pieces on
12458 		 * the end.  If we ever see a hole, then we go off
12459 		 * to ip_reassemble which has to mark the pieces and
12460 		 * keep track of the number of holes, etc.  Obviously,
12461 		 * the point of having both mechanisms is so we can
12462 		 * handle the easy case as efficiently as possible.
12463 		 */
12464 		if (offset == 0) {
12465 			/* Easy case, in-order reassembly so far. */
12466 			ipf->ipf_count += msg_len;
12467 			ipf->ipf_tail_mp = tail_mp;
12468 			/*
12469 			 * Keep track of next expected offset in
12470 			 * ipf_end.
12471 			 */
12472 			ipf->ipf_end = end;
12473 			ipf->ipf_nf_hdr_len = hdr_length;
12474 		} else {
12475 			/* Hard case, hole at the beginning. */
12476 			ipf->ipf_tail_mp = NULL;
12477 			/*
12478 			 * ipf_end == 0 means that we have given up
12479 			 * on easy reassembly.
12480 			 */
12481 			ipf->ipf_end = 0;
12482 
12483 			/* Forget checksum offload from now on */
12484 			ipf->ipf_checksum_flags = 0;
12485 
12486 			/*
12487 			 * ipf_hole_cnt is set by ip_reassemble.
12488 			 * ipf_count is updated by ip_reassemble.
12489 			 * No need to check for return value here
12490 			 * as we don't expect reassembly to complete
12491 			 * or fail for the first fragment itself.
12492 			 */
12493 			(void) ip_reassemble(mp, ipf,
12494 			    (frag_offset_flags & IPH_OFFSET) << 3,
12495 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12496 		}
12497 		/* Update per ipfb and ill byte counts */
12498 		ipfb->ipfb_count += ipf->ipf_count;
12499 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12500 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12501 		/* If the frag timer wasn't already going, start it. */
12502 		mutex_enter(&ill->ill_lock);
12503 		ill_frag_timer_start(ill);
12504 		mutex_exit(&ill->ill_lock);
12505 		goto reass_done;
12506 	}
12507 
12508 	/*
12509 	 * If the packet's flag has changed (it could be coming up
12510 	 * from an interface different than the previous, therefore
12511 	 * possibly different checksum capability), then forget about
12512 	 * any stored checksum states.  Otherwise add the value to
12513 	 * the existing one stored in the fragment header.
12514 	 */
12515 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12516 		sum_val += ipf->ipf_checksum;
12517 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12518 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12519 		ipf->ipf_checksum = sum_val;
12520 	} else if (ipf->ipf_checksum_flags != 0) {
12521 		/* Forget checksum offload from now on */
12522 		ipf->ipf_checksum_flags = 0;
12523 	}
12524 
12525 	/*
12526 	 * We have a new piece of a datagram which is already being
12527 	 * reassembled.  Update the ECN info if all IP fragments
12528 	 * are ECN capable.  If there is one which is not, clear
12529 	 * all the info.  If there is at least one which has CE
12530 	 * code point, IP needs to report that up to transport.
12531 	 */
12532 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12533 		if (ecn_info == IPH_ECN_CE)
12534 			ipf->ipf_ecn = IPH_ECN_CE;
12535 	} else {
12536 		ipf->ipf_ecn = IPH_ECN_NECT;
12537 	}
12538 	if (offset && ipf->ipf_end == offset) {
12539 		/* The new fragment fits at the end */
12540 		ipf->ipf_tail_mp->b_cont = mp;
12541 		/* Update the byte count */
12542 		ipf->ipf_count += msg_len;
12543 		/* Update per ipfb and ill byte counts */
12544 		ipfb->ipfb_count += msg_len;
12545 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12546 		atomic_add_32(&ill->ill_frag_count, msg_len);
12547 		if (frag_offset_flags & IPH_MF) {
12548 			/* More to come. */
12549 			ipf->ipf_end = end;
12550 			ipf->ipf_tail_mp = tail_mp;
12551 			goto reass_done;
12552 		}
12553 	} else {
12554 		/* Go do the hard cases. */
12555 		int ret;
12556 
12557 		if (offset == 0)
12558 			ipf->ipf_nf_hdr_len = hdr_length;
12559 
12560 		/* Save current byte count */
12561 		count = ipf->ipf_count;
12562 		ret = ip_reassemble(mp, ipf,
12563 		    (frag_offset_flags & IPH_OFFSET) << 3,
12564 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12565 		/* Count of bytes added and subtracted (freeb()ed) */
12566 		count = ipf->ipf_count - count;
12567 		if (count) {
12568 			/* Update per ipfb and ill byte counts */
12569 			ipfb->ipfb_count += count;
12570 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12571 			atomic_add_32(&ill->ill_frag_count, count);
12572 		}
12573 		if (ret == IP_REASS_PARTIAL) {
12574 			goto reass_done;
12575 		} else if (ret == IP_REASS_FAILED) {
12576 			/* Reassembly failed. Free up all resources */
12577 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12578 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12579 				IP_REASS_SET_START(t_mp, 0);
12580 				IP_REASS_SET_END(t_mp, 0);
12581 			}
12582 			freemsg(mp);
12583 			goto reass_done;
12584 		}
12585 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12586 	}
12587 	/*
12588 	 * We have completed reassembly.  Unhook the frag header from
12589 	 * the reassembly list.
12590 	 *
12591 	 * Before we free the frag header, record the ECN info
12592 	 * to report back to the transport.
12593 	 */
12594 	ecn_info = ipf->ipf_ecn;
12595 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12596 	ipfp = ipf->ipf_ptphn;
12597 
12598 	/* We need to supply these to caller */
12599 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12600 		sum_val = ipf->ipf_checksum;
12601 	else
12602 		sum_val = 0;
12603 
12604 	mp1 = ipf->ipf_mp;
12605 	count = ipf->ipf_count;
12606 	ipf = ipf->ipf_hash_next;
12607 	if (ipf != NULL)
12608 		ipf->ipf_ptphn = ipfp;
12609 	ipfp[0] = ipf;
12610 	atomic_add_32(&ill->ill_frag_count, -count);
12611 	ASSERT(ipfb->ipfb_count >= count);
12612 	ipfb->ipfb_count -= count;
12613 	ipfb->ipfb_frag_pkts--;
12614 	mutex_exit(&ipfb->ipfb_lock);
12615 	/* Ditch the frag header. */
12616 	mp = mp1->b_cont;
12617 
12618 	freeb(mp1);
12619 
12620 	/* Restore original IP length in header. */
12621 	packet_size = (uint32_t)msgdsize(mp);
12622 	if (packet_size > IP_MAXPACKET) {
12623 		freemsg(mp);
12624 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12625 		return (B_FALSE);
12626 	}
12627 
12628 	if (DB_REF(mp) > 1) {
12629 		mblk_t *mp2 = copymsg(mp);
12630 
12631 		freemsg(mp);
12632 		if (mp2 == NULL) {
12633 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12634 			return (B_FALSE);
12635 		}
12636 		mp = mp2;
12637 	}
12638 	ipha = (ipha_t *)mp->b_rptr;
12639 
12640 	ipha->ipha_length = htons((uint16_t)packet_size);
12641 	/* We're now complete, zip the frag state */
12642 	ipha->ipha_fragment_offset_and_flags = 0;
12643 	/* Record the ECN info. */
12644 	ipha->ipha_type_of_service &= 0xFC;
12645 	ipha->ipha_type_of_service |= ecn_info;
12646 	*mpp = mp;
12647 
12648 	/* Reassembly is successful; return checksum information if needed */
12649 	if (cksum_val != NULL)
12650 		*cksum_val = sum_val;
12651 	if (cksum_flags != NULL)
12652 		*cksum_flags = sum_flags;
12653 
12654 	return (B_TRUE);
12655 }
12656 
12657 /*
12658  * Perform ip header check sum update local options.
12659  * return B_TRUE if all is well, else return B_FALSE and release
12660  * the mp. caller is responsible for decrementing ire ref cnt.
12661  */
12662 static boolean_t
12663 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12664     ip_stack_t *ipst)
12665 {
12666 	mblk_t		*first_mp;
12667 	boolean_t	mctl_present;
12668 	uint16_t	sum;
12669 
12670 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12671 	/*
12672 	 * Don't do the checksum if it has gone through AH/ESP
12673 	 * processing.
12674 	 */
12675 	if (!mctl_present) {
12676 		sum = ip_csum_hdr(ipha);
12677 		if (sum != 0) {
12678 			if (ill != NULL) {
12679 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12680 			} else {
12681 				BUMP_MIB(&ipst->ips_ip_mib,
12682 				    ipIfStatsInCksumErrs);
12683 			}
12684 			freemsg(first_mp);
12685 			return (B_FALSE);
12686 		}
12687 	}
12688 
12689 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12690 		if (mctl_present)
12691 			freeb(first_mp);
12692 		return (B_FALSE);
12693 	}
12694 
12695 	return (B_TRUE);
12696 }
12697 
12698 /*
12699  * All udp packet are delivered to the local host via this routine.
12700  */
12701 void
12702 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12703     ill_t *recv_ill)
12704 {
12705 	uint32_t	sum;
12706 	uint32_t	u1;
12707 	boolean_t	mctl_present;
12708 	conn_t		*connp;
12709 	mblk_t		*first_mp;
12710 	uint16_t	*up;
12711 	ill_t		*ill = (ill_t *)q->q_ptr;
12712 	uint16_t	reass_hck_flags = 0;
12713 	ip_stack_t	*ipst;
12714 
12715 	ASSERT(recv_ill != NULL);
12716 	ipst = recv_ill->ill_ipst;
12717 
12718 #define	rptr    ((uchar_t *)ipha)
12719 
12720 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12721 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12722 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12723 	ASSERT(ill != NULL);
12724 
12725 	/*
12726 	 * FAST PATH for udp packets
12727 	 */
12728 
12729 	/* u1 is # words of IP options */
12730 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12731 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12732 
12733 	/* IP options present */
12734 	if (u1 != 0)
12735 		goto ipoptions;
12736 
12737 	/* Check the IP header checksum.  */
12738 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12739 		/* Clear the IP header h/w cksum flag */
12740 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12741 	} else if (!mctl_present) {
12742 		/*
12743 		 * Don't verify header checksum if this packet is coming
12744 		 * back from AH/ESP as we already did it.
12745 		 */
12746 #define	uph	((uint16_t *)ipha)
12747 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12748 		    uph[6] + uph[7] + uph[8] + uph[9];
12749 #undef	uph
12750 		/* finish doing IP checksum */
12751 		sum = (sum & 0xFFFF) + (sum >> 16);
12752 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12753 		if (sum != 0 && sum != 0xFFFF) {
12754 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12755 			freemsg(first_mp);
12756 			return;
12757 		}
12758 	}
12759 
12760 	/*
12761 	 * Count for SNMP of inbound packets for ire.
12762 	 * if mctl is present this might be a secure packet and
12763 	 * has already been counted for in ip_proto_input().
12764 	 */
12765 	if (!mctl_present) {
12766 		UPDATE_IB_PKT_COUNT(ire);
12767 		ire->ire_last_used_time = lbolt;
12768 	}
12769 
12770 	/* packet part of fragmented IP packet? */
12771 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12772 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12773 		goto fragmented;
12774 	}
12775 
12776 	/* u1 = IP header length (20 bytes) */
12777 	u1 = IP_SIMPLE_HDR_LENGTH;
12778 
12779 	/* packet does not contain complete IP & UDP headers */
12780 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12781 		goto udppullup;
12782 
12783 	/* up points to UDP header */
12784 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12785 #define	iphs    ((uint16_t *)ipha)
12786 
12787 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12788 	if (up[3] != 0) {
12789 		mblk_t *mp1 = mp->b_cont;
12790 		boolean_t cksum_err;
12791 		uint16_t hck_flags = 0;
12792 
12793 		/* Pseudo-header checksum */
12794 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12795 		    iphs[9] + up[2];
12796 
12797 		/*
12798 		 * Revert to software checksum calculation if the interface
12799 		 * isn't capable of checksum offload or if IPsec is present.
12800 		 */
12801 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12802 			hck_flags = DB_CKSUMFLAGS(mp);
12803 
12804 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12805 			IP_STAT(ipst, ip_in_sw_cksum);
12806 
12807 		IP_CKSUM_RECV(hck_flags, u1,
12808 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12809 		    (int32_t)((uchar_t *)up - rptr),
12810 		    mp, mp1, cksum_err);
12811 
12812 		if (cksum_err) {
12813 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12814 			if (hck_flags & HCK_FULLCKSUM)
12815 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12816 			else if (hck_flags & HCK_PARTIALCKSUM)
12817 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12818 			else
12819 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12820 
12821 			freemsg(first_mp);
12822 			return;
12823 		}
12824 	}
12825 
12826 	/* Non-fragmented broadcast or multicast packet? */
12827 	if (ire->ire_type == IRE_BROADCAST)
12828 		goto udpslowpath;
12829 
12830 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12831 	    ire->ire_zoneid, ipst)) != NULL) {
12832 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12833 		IP_STAT(ipst, ip_udp_fast_path);
12834 
12835 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12836 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12837 			freemsg(mp);
12838 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12839 		} else {
12840 			if (!mctl_present) {
12841 				BUMP_MIB(ill->ill_ip_mib,
12842 				    ipIfStatsHCInDelivers);
12843 			}
12844 			/*
12845 			 * mp and first_mp can change.
12846 			 */
12847 			if (ip_udp_check(q, connp, recv_ill,
12848 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12849 				/* Send it upstream */
12850 				(connp->conn_recv)(connp, mp, NULL);
12851 			}
12852 		}
12853 		/*
12854 		 * freeb() cannot deal with null mblk being passed
12855 		 * in and first_mp can be set to null in the call
12856 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12857 		 */
12858 		if (mctl_present && first_mp != NULL) {
12859 			freeb(first_mp);
12860 		}
12861 		CONN_DEC_REF(connp);
12862 		return;
12863 	}
12864 
12865 	/*
12866 	 * if we got here we know the packet is not fragmented and
12867 	 * has no options. The classifier could not find a conn_t and
12868 	 * most likely its an icmp packet so send it through slow path.
12869 	 */
12870 
12871 	goto udpslowpath;
12872 
12873 ipoptions:
12874 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12875 		goto slow_done;
12876 	}
12877 
12878 	UPDATE_IB_PKT_COUNT(ire);
12879 	ire->ire_last_used_time = lbolt;
12880 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12881 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12882 fragmented:
12883 		/*
12884 		 * "sum" and "reass_hck_flags" are non-zero if the
12885 		 * reassembled packet has a valid hardware computed
12886 		 * checksum information associated with it.
12887 		 */
12888 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12889 		    &reass_hck_flags)) {
12890 			goto slow_done;
12891 		}
12892 
12893 		/*
12894 		 * Make sure that first_mp points back to mp as
12895 		 * the mp we came in with could have changed in
12896 		 * ip_rput_fragment().
12897 		 */
12898 		ASSERT(!mctl_present);
12899 		ipha = (ipha_t *)mp->b_rptr;
12900 		first_mp = mp;
12901 	}
12902 
12903 	/* Now we have a complete datagram, destined for this machine. */
12904 	u1 = IPH_HDR_LENGTH(ipha);
12905 	/* Pull up the UDP header, if necessary. */
12906 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12907 udppullup:
12908 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12909 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12910 			freemsg(first_mp);
12911 			goto slow_done;
12912 		}
12913 		ipha = (ipha_t *)mp->b_rptr;
12914 	}
12915 
12916 	/*
12917 	 * Validate the checksum for the reassembled packet; for the
12918 	 * pullup case we calculate the payload checksum in software.
12919 	 */
12920 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12921 	if (up[3] != 0) {
12922 		boolean_t cksum_err;
12923 
12924 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12925 			IP_STAT(ipst, ip_in_sw_cksum);
12926 
12927 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12928 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12929 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12930 		    iphs[9] + up[2], sum, cksum_err);
12931 
12932 		if (cksum_err) {
12933 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12934 
12935 			if (reass_hck_flags & HCK_FULLCKSUM)
12936 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12937 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12938 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12939 			else
12940 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12941 
12942 			freemsg(first_mp);
12943 			goto slow_done;
12944 		}
12945 	}
12946 udpslowpath:
12947 
12948 	/* Clear hardware checksum flag to be safe */
12949 	DB_CKSUMFLAGS(mp) = 0;
12950 
12951 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12952 	    (ire->ire_type == IRE_BROADCAST),
12953 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12954 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12955 
12956 slow_done:
12957 	IP_STAT(ipst, ip_udp_slow_path);
12958 	return;
12959 
12960 #undef  iphs
12961 #undef  rptr
12962 }
12963 
12964 /* ARGSUSED */
12965 static mblk_t *
12966 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12967     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12968     ill_rx_ring_t *ill_ring)
12969 {
12970 	conn_t		*connp;
12971 	uint32_t	sum;
12972 	uint32_t	u1;
12973 	uint16_t	*up;
12974 	int		offset;
12975 	ssize_t		len;
12976 	mblk_t		*mp1;
12977 	boolean_t	syn_present = B_FALSE;
12978 	tcph_t		*tcph;
12979 	uint_t		tcph_flags;
12980 	uint_t		ip_hdr_len;
12981 	ill_t		*ill = (ill_t *)q->q_ptr;
12982 	zoneid_t	zoneid = ire->ire_zoneid;
12983 	boolean_t	cksum_err;
12984 	uint16_t	hck_flags = 0;
12985 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12986 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12987 
12988 #define	rptr	((uchar_t *)ipha)
12989 
12990 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12991 	ASSERT(ill != NULL);
12992 
12993 	/*
12994 	 * FAST PATH for tcp packets
12995 	 */
12996 
12997 	/* u1 is # words of IP options */
12998 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12999 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13000 
13001 	/* IP options present */
13002 	if (u1) {
13003 		goto ipoptions;
13004 	} else if (!mctl_present) {
13005 		/* Check the IP header checksum.  */
13006 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
13007 			/* Clear the IP header h/w cksum flag */
13008 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13009 		} else if (!mctl_present) {
13010 			/*
13011 			 * Don't verify header checksum if this packet
13012 			 * is coming back from AH/ESP as we already did it.
13013 			 */
13014 #define	uph	((uint16_t *)ipha)
13015 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13016 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13017 #undef	uph
13018 			/* finish doing IP checksum */
13019 			sum = (sum & 0xFFFF) + (sum >> 16);
13020 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13021 			if (sum != 0 && sum != 0xFFFF) {
13022 				BUMP_MIB(ill->ill_ip_mib,
13023 				    ipIfStatsInCksumErrs);
13024 				goto error;
13025 			}
13026 		}
13027 	}
13028 
13029 	if (!mctl_present) {
13030 		UPDATE_IB_PKT_COUNT(ire);
13031 		ire->ire_last_used_time = lbolt;
13032 	}
13033 
13034 	/* packet part of fragmented IP packet? */
13035 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13036 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13037 		goto fragmented;
13038 	}
13039 
13040 	/* u1 = IP header length (20 bytes) */
13041 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13042 
13043 	/* does packet contain IP+TCP headers? */
13044 	len = mp->b_wptr - rptr;
13045 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13046 		IP_STAT(ipst, ip_tcppullup);
13047 		goto tcppullup;
13048 	}
13049 
13050 	/* TCP options present? */
13051 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13052 
13053 	/*
13054 	 * If options need to be pulled up, then goto tcpoptions.
13055 	 * otherwise we are still in the fast path
13056 	 */
13057 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13058 		IP_STAT(ipst, ip_tcpoptions);
13059 		goto tcpoptions;
13060 	}
13061 
13062 	/* multiple mblks of tcp data? */
13063 	if ((mp1 = mp->b_cont) != NULL) {
13064 		IP_STAT(ipst, ip_multipkttcp);
13065 		len += msgdsize(mp1);
13066 	}
13067 
13068 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13069 
13070 	/* part of pseudo checksum */
13071 
13072 	/* TCP datagram length */
13073 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13074 
13075 #define	iphs    ((uint16_t *)ipha)
13076 
13077 #ifdef	_BIG_ENDIAN
13078 	u1 += IPPROTO_TCP;
13079 #else
13080 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13081 #endif
13082 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13083 
13084 	/*
13085 	 * Revert to software checksum calculation if the interface
13086 	 * isn't capable of checksum offload or if IPsec is present.
13087 	 */
13088 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13089 		hck_flags = DB_CKSUMFLAGS(mp);
13090 
13091 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13092 		IP_STAT(ipst, ip_in_sw_cksum);
13093 
13094 	IP_CKSUM_RECV(hck_flags, u1,
13095 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13096 	    (int32_t)((uchar_t *)up - rptr),
13097 	    mp, mp1, cksum_err);
13098 
13099 	if (cksum_err) {
13100 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13101 
13102 		if (hck_flags & HCK_FULLCKSUM)
13103 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13104 		else if (hck_flags & HCK_PARTIALCKSUM)
13105 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13106 		else
13107 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13108 
13109 		goto error;
13110 	}
13111 
13112 try_again:
13113 
13114 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13115 	    zoneid, ipst)) == NULL) {
13116 		/* Send the TH_RST */
13117 		goto no_conn;
13118 	}
13119 
13120 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13121 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13122 
13123 	/*
13124 	 * TCP FAST PATH for AF_INET socket.
13125 	 *
13126 	 * TCP fast path to avoid extra work. An AF_INET socket type
13127 	 * does not have facility to receive extra information via
13128 	 * ip_process or ip_add_info. Also, when the connection was
13129 	 * established, we made a check if this connection is impacted
13130 	 * by any global IPsec policy or per connection policy (a
13131 	 * policy that comes in effect later will not apply to this
13132 	 * connection). Since all this can be determined at the
13133 	 * connection establishment time, a quick check of flags
13134 	 * can avoid extra work.
13135 	 */
13136 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13137 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13138 		ASSERT(first_mp == mp);
13139 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13140 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13141 			SET_SQUEUE(mp, tcp_rput_data, connp);
13142 			return (mp);
13143 		}
13144 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13145 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13146 		SET_SQUEUE(mp, tcp_input, connp);
13147 		return (mp);
13148 	}
13149 
13150 	if (tcph_flags == TH_SYN) {
13151 		if (IPCL_IS_TCP(connp)) {
13152 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13153 			DB_CKSUMSTART(mp) =
13154 			    (intptr_t)ip_squeue_get(ill_ring);
13155 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13156 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13157 				BUMP_MIB(ill->ill_ip_mib,
13158 				    ipIfStatsHCInDelivers);
13159 				SET_SQUEUE(mp, connp->conn_recv, connp);
13160 				return (mp);
13161 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13162 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13163 				BUMP_MIB(ill->ill_ip_mib,
13164 				    ipIfStatsHCInDelivers);
13165 				ip_squeue_enter_unbound++;
13166 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13167 				    connp);
13168 				return (mp);
13169 			}
13170 			syn_present = B_TRUE;
13171 		}
13172 	}
13173 
13174 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13175 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13176 
13177 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13178 		/* No need to send this packet to TCP */
13179 		if ((flags & TH_RST) || (flags & TH_URG)) {
13180 			CONN_DEC_REF(connp);
13181 			freemsg(first_mp);
13182 			return (NULL);
13183 		}
13184 		if (flags & TH_ACK) {
13185 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13186 			    ipst->ips_netstack->netstack_tcp, connp);
13187 			CONN_DEC_REF(connp);
13188 			return (NULL);
13189 		}
13190 
13191 		CONN_DEC_REF(connp);
13192 		freemsg(first_mp);
13193 		return (NULL);
13194 	}
13195 
13196 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13197 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13198 		    ipha, NULL, mctl_present);
13199 		if (first_mp == NULL) {
13200 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13201 			CONN_DEC_REF(connp);
13202 			return (NULL);
13203 		}
13204 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13205 			ASSERT(syn_present);
13206 			if (mctl_present) {
13207 				ASSERT(first_mp != mp);
13208 				first_mp->b_datap->db_struioflag |=
13209 				    STRUIO_POLICY;
13210 			} else {
13211 				ASSERT(first_mp == mp);
13212 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13213 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13214 			}
13215 		} else {
13216 			/*
13217 			 * Discard first_mp early since we're dealing with a
13218 			 * fully-connected conn_t and tcp doesn't do policy in
13219 			 * this case.
13220 			 */
13221 			if (mctl_present) {
13222 				freeb(first_mp);
13223 				mctl_present = B_FALSE;
13224 			}
13225 			first_mp = mp;
13226 		}
13227 	}
13228 
13229 	/* Initiate IPPF processing for fastpath */
13230 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13231 		uint32_t	ill_index;
13232 
13233 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13234 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13235 		if (mp == NULL) {
13236 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13237 			    "deferred/dropped during IPPF processing\n"));
13238 			CONN_DEC_REF(connp);
13239 			if (mctl_present)
13240 				freeb(first_mp);
13241 			return (NULL);
13242 		} else if (mctl_present) {
13243 			/*
13244 			 * ip_process might return a new mp.
13245 			 */
13246 			ASSERT(first_mp != mp);
13247 			first_mp->b_cont = mp;
13248 		} else {
13249 			first_mp = mp;
13250 		}
13251 
13252 	}
13253 
13254 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13255 		/*
13256 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13257 		 * make sure IPF_RECVIF is passed to ip_add_info.
13258 		 */
13259 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13260 		    IPCL_ZONEID(connp), ipst);
13261 		if (mp == NULL) {
13262 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13263 			CONN_DEC_REF(connp);
13264 			if (mctl_present)
13265 				freeb(first_mp);
13266 			return (NULL);
13267 		} else if (mctl_present) {
13268 			/*
13269 			 * ip_add_info might return a new mp.
13270 			 */
13271 			ASSERT(first_mp != mp);
13272 			first_mp->b_cont = mp;
13273 		} else {
13274 			first_mp = mp;
13275 		}
13276 	}
13277 
13278 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13279 	if (IPCL_IS_TCP(connp)) {
13280 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13281 		return (first_mp);
13282 	} else {
13283 		/* SOCK_RAW, IPPROTO_TCP case */
13284 		(connp->conn_recv)(connp, first_mp, NULL);
13285 		CONN_DEC_REF(connp);
13286 		return (NULL);
13287 	}
13288 
13289 no_conn:
13290 	/* Initiate IPPf processing, if needed. */
13291 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13292 		uint32_t ill_index;
13293 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13294 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13295 		if (first_mp == NULL) {
13296 			return (NULL);
13297 		}
13298 	}
13299 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13300 
13301 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13302 	    ipst->ips_netstack->netstack_tcp, NULL);
13303 	return (NULL);
13304 ipoptions:
13305 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13306 		goto slow_done;
13307 	}
13308 
13309 	UPDATE_IB_PKT_COUNT(ire);
13310 	ire->ire_last_used_time = lbolt;
13311 
13312 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13313 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13314 fragmented:
13315 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13316 			if (mctl_present)
13317 				freeb(first_mp);
13318 			goto slow_done;
13319 		}
13320 		/*
13321 		 * Make sure that first_mp points back to mp as
13322 		 * the mp we came in with could have changed in
13323 		 * ip_rput_fragment().
13324 		 */
13325 		ASSERT(!mctl_present);
13326 		ipha = (ipha_t *)mp->b_rptr;
13327 		first_mp = mp;
13328 	}
13329 
13330 	/* Now we have a complete datagram, destined for this machine. */
13331 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13332 
13333 	len = mp->b_wptr - mp->b_rptr;
13334 	/* Pull up a minimal TCP header, if necessary. */
13335 	if (len < (u1 + 20)) {
13336 tcppullup:
13337 		if (!pullupmsg(mp, u1 + 20)) {
13338 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13339 			goto error;
13340 		}
13341 		ipha = (ipha_t *)mp->b_rptr;
13342 		len = mp->b_wptr - mp->b_rptr;
13343 	}
13344 
13345 	/*
13346 	 * Extract the offset field from the TCP header.  As usual, we
13347 	 * try to help the compiler more than the reader.
13348 	 */
13349 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13350 	if (offset != 5) {
13351 tcpoptions:
13352 		if (offset < 5) {
13353 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13354 			goto error;
13355 		}
13356 		/*
13357 		 * There must be TCP options.
13358 		 * Make sure we can grab them.
13359 		 */
13360 		offset <<= 2;
13361 		offset += u1;
13362 		if (len < offset) {
13363 			if (!pullupmsg(mp, offset)) {
13364 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13365 				goto error;
13366 			}
13367 			ipha = (ipha_t *)mp->b_rptr;
13368 			len = mp->b_wptr - rptr;
13369 		}
13370 	}
13371 
13372 	/* Get the total packet length in len, including headers. */
13373 	if (mp->b_cont)
13374 		len = msgdsize(mp);
13375 
13376 	/*
13377 	 * Check the TCP checksum by pulling together the pseudo-
13378 	 * header checksum, and passing it to ip_csum to be added in
13379 	 * with the TCP datagram.
13380 	 *
13381 	 * Since we are not using the hwcksum if available we must
13382 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13383 	 * If either of these fails along the way the mblk is freed.
13384 	 * If this logic ever changes and mblk is reused to say send
13385 	 * ICMP's back, then this flag may need to be cleared in
13386 	 * other places as well.
13387 	 */
13388 	DB_CKSUMFLAGS(mp) = 0;
13389 
13390 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13391 
13392 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13393 #ifdef	_BIG_ENDIAN
13394 	u1 += IPPROTO_TCP;
13395 #else
13396 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13397 #endif
13398 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13399 	/*
13400 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13401 	 */
13402 	IP_STAT(ipst, ip_in_sw_cksum);
13403 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13404 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13405 		goto error;
13406 	}
13407 
13408 	IP_STAT(ipst, ip_tcp_slow_path);
13409 	goto try_again;
13410 #undef  iphs
13411 #undef  rptr
13412 
13413 error:
13414 	freemsg(first_mp);
13415 slow_done:
13416 	return (NULL);
13417 }
13418 
13419 /* ARGSUSED */
13420 static void
13421 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13422     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13423 {
13424 	conn_t		*connp;
13425 	uint32_t	sum;
13426 	uint32_t	u1;
13427 	ssize_t		len;
13428 	sctp_hdr_t	*sctph;
13429 	zoneid_t	zoneid = ire->ire_zoneid;
13430 	uint32_t	pktsum;
13431 	uint32_t	calcsum;
13432 	uint32_t	ports;
13433 	in6_addr_t	map_src, map_dst;
13434 	ill_t		*ill = (ill_t *)q->q_ptr;
13435 	ip_stack_t	*ipst;
13436 	sctp_stack_t	*sctps;
13437 	boolean_t	sctp_csum_err = B_FALSE;
13438 
13439 	ASSERT(recv_ill != NULL);
13440 	ipst = recv_ill->ill_ipst;
13441 	sctps = ipst->ips_netstack->netstack_sctp;
13442 
13443 #define	rptr	((uchar_t *)ipha)
13444 
13445 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13446 	ASSERT(ill != NULL);
13447 
13448 	/* u1 is # words of IP options */
13449 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13450 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13451 
13452 	/* IP options present */
13453 	if (u1 > 0) {
13454 		goto ipoptions;
13455 	} else {
13456 		/* Check the IP header checksum.  */
13457 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13458 		    !mctl_present) {
13459 #define	uph	((uint16_t *)ipha)
13460 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13461 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13462 #undef	uph
13463 			/* finish doing IP checksum */
13464 			sum = (sum & 0xFFFF) + (sum >> 16);
13465 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13466 			/*
13467 			 * Don't verify header checksum if this packet
13468 			 * is coming back from AH/ESP as we already did it.
13469 			 */
13470 			if (sum != 0 && sum != 0xFFFF) {
13471 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13472 				goto error;
13473 			}
13474 		}
13475 		/*
13476 		 * Since there is no SCTP h/w cksum support yet, just
13477 		 * clear the flag.
13478 		 */
13479 		DB_CKSUMFLAGS(mp) = 0;
13480 	}
13481 
13482 	/*
13483 	 * Don't verify header checksum if this packet is coming
13484 	 * back from AH/ESP as we already did it.
13485 	 */
13486 	if (!mctl_present) {
13487 		UPDATE_IB_PKT_COUNT(ire);
13488 		ire->ire_last_used_time = lbolt;
13489 	}
13490 
13491 	/* packet part of fragmented IP packet? */
13492 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13493 	if (u1 & (IPH_MF | IPH_OFFSET))
13494 		goto fragmented;
13495 
13496 	/* u1 = IP header length (20 bytes) */
13497 	u1 = IP_SIMPLE_HDR_LENGTH;
13498 
13499 find_sctp_client:
13500 	/* Pullup if we don't have the sctp common header. */
13501 	len = MBLKL(mp);
13502 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13503 		if (mp->b_cont == NULL ||
13504 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13505 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13506 			goto error;
13507 		}
13508 		ipha = (ipha_t *)mp->b_rptr;
13509 		len = MBLKL(mp);
13510 	}
13511 
13512 	sctph = (sctp_hdr_t *)(rptr + u1);
13513 #ifdef	DEBUG
13514 	if (!skip_sctp_cksum) {
13515 #endif
13516 		pktsum = sctph->sh_chksum;
13517 		sctph->sh_chksum = 0;
13518 		calcsum = sctp_cksum(mp, u1);
13519 		sctph->sh_chksum = pktsum;
13520 		if (calcsum != pktsum)
13521 			sctp_csum_err = B_TRUE;
13522 #ifdef	DEBUG	/* skip_sctp_cksum */
13523 	}
13524 #endif
13525 	/* get the ports */
13526 	ports = *(uint32_t *)&sctph->sh_sport;
13527 
13528 	IRE_REFRELE(ire);
13529 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13530 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13531 	if (sctp_csum_err) {
13532 		/*
13533 		 * No potential sctp checksum errors go to the Sun
13534 		 * sctp stack however they might be Adler-32 summed
13535 		 * packets a userland stack bound to a raw IP socket
13536 		 * could reasonably use. Note though that Adler-32 is
13537 		 * a long deprecated algorithm and customer sctp
13538 		 * networks should eventually migrate to CRC-32 at
13539 		 * which time this facility should be removed.
13540 		 */
13541 		flags |= IP_FF_SCTP_CSUM_ERR;
13542 		goto no_conn;
13543 	}
13544 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13545 	    sctps)) == NULL) {
13546 		/* Check for raw socket or OOTB handling */
13547 		goto no_conn;
13548 	}
13549 
13550 	/* Found a client; up it goes */
13551 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13552 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13553 	return;
13554 
13555 no_conn:
13556 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13557 	    ports, mctl_present, flags, B_TRUE, zoneid);
13558 	return;
13559 
13560 ipoptions:
13561 	DB_CKSUMFLAGS(mp) = 0;
13562 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13563 		goto slow_done;
13564 
13565 	UPDATE_IB_PKT_COUNT(ire);
13566 	ire->ire_last_used_time = lbolt;
13567 
13568 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13569 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13570 fragmented:
13571 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13572 			goto slow_done;
13573 		/*
13574 		 * Make sure that first_mp points back to mp as
13575 		 * the mp we came in with could have changed in
13576 		 * ip_rput_fragment().
13577 		 */
13578 		ASSERT(!mctl_present);
13579 		ipha = (ipha_t *)mp->b_rptr;
13580 		first_mp = mp;
13581 	}
13582 
13583 	/* Now we have a complete datagram, destined for this machine. */
13584 	u1 = IPH_HDR_LENGTH(ipha);
13585 	goto find_sctp_client;
13586 #undef  iphs
13587 #undef  rptr
13588 
13589 error:
13590 	freemsg(first_mp);
13591 slow_done:
13592 	IRE_REFRELE(ire);
13593 }
13594 
13595 #define	VER_BITS	0xF0
13596 #define	VERSION_6	0x60
13597 
13598 static boolean_t
13599 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13600     ipaddr_t *dstp, ip_stack_t *ipst)
13601 {
13602 	uint_t	opt_len;
13603 	ipha_t *ipha;
13604 	ssize_t len;
13605 	uint_t	pkt_len;
13606 
13607 	ASSERT(ill != NULL);
13608 	IP_STAT(ipst, ip_ipoptions);
13609 	ipha = *iphapp;
13610 
13611 #define	rptr    ((uchar_t *)ipha)
13612 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13613 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13614 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13615 		freemsg(mp);
13616 		return (B_FALSE);
13617 	}
13618 
13619 	/* multiple mblk or too short */
13620 	pkt_len = ntohs(ipha->ipha_length);
13621 
13622 	/* Get the number of words of IP options in the IP header. */
13623 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13624 	if (opt_len) {
13625 		/* IP Options present!  Validate and process. */
13626 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13627 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13628 			goto done;
13629 		}
13630 		/*
13631 		 * Recompute complete header length and make sure we
13632 		 * have access to all of it.
13633 		 */
13634 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13635 		if (len > (mp->b_wptr - rptr)) {
13636 			if (len > pkt_len) {
13637 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13638 				goto done;
13639 			}
13640 			if (!pullupmsg(mp, len)) {
13641 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13642 				goto done;
13643 			}
13644 			ipha = (ipha_t *)mp->b_rptr;
13645 		}
13646 		/*
13647 		 * Go off to ip_rput_options which returns the next hop
13648 		 * destination address, which may have been affected
13649 		 * by source routing.
13650 		 */
13651 		IP_STAT(ipst, ip_opt);
13652 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13653 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13654 			return (B_FALSE);
13655 		}
13656 	}
13657 	*iphapp = ipha;
13658 	return (B_TRUE);
13659 done:
13660 	/* clear b_prev - used by ip_mroute_decap */
13661 	mp->b_prev = NULL;
13662 	freemsg(mp);
13663 	return (B_FALSE);
13664 #undef  rptr
13665 }
13666 
13667 /*
13668  * Deal with the fact that there is no ire for the destination.
13669  */
13670 static ire_t *
13671 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13672 {
13673 	ipha_t	*ipha;
13674 	ill_t	*ill;
13675 	ire_t	*ire;
13676 	ip_stack_t *ipst;
13677 	enum	ire_forward_action ret_action;
13678 
13679 	ipha = (ipha_t *)mp->b_rptr;
13680 	ill = (ill_t *)q->q_ptr;
13681 
13682 	ASSERT(ill != NULL);
13683 	ipst = ill->ill_ipst;
13684 
13685 	/*
13686 	 * No IRE for this destination, so it can't be for us.
13687 	 * Unless we are forwarding, drop the packet.
13688 	 * We have to let source routed packets through
13689 	 * since we don't yet know if they are 'ping -l'
13690 	 * packets i.e. if they will go out over the
13691 	 * same interface as they came in on.
13692 	 */
13693 	if (ll_multicast) {
13694 		freemsg(mp);
13695 		return (NULL);
13696 	}
13697 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13698 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13699 		freemsg(mp);
13700 		return (NULL);
13701 	}
13702 
13703 	/*
13704 	 * Mark this packet as having originated externally.
13705 	 *
13706 	 * For non-forwarding code path, ire_send later double
13707 	 * checks this interface to see if it is still exists
13708 	 * post-ARP resolution.
13709 	 *
13710 	 * Also, IPQOS uses this to differentiate between
13711 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13712 	 * QOS packet processing in ip_wput_attach_llhdr().
13713 	 * The QoS module can mark the b_band for a fastpath message
13714 	 * or the dl_priority field in a unitdata_req header for
13715 	 * CoS marking. This info can only be found in
13716 	 * ip_wput_attach_llhdr().
13717 	 */
13718 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13719 	/*
13720 	 * Clear the indication that this may have a hardware checksum
13721 	 * as we are not using it
13722 	 */
13723 	DB_CKSUMFLAGS(mp) = 0;
13724 
13725 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13726 	    msg_getlabel(mp), ipst);
13727 
13728 	if (ire == NULL && ret_action == Forward_check_multirt) {
13729 		/* Let ip_newroute handle CGTP  */
13730 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13731 		return (NULL);
13732 	}
13733 
13734 	if (ire != NULL)
13735 		return (ire);
13736 
13737 	mp->b_prev = mp->b_next = 0;
13738 
13739 	if (ret_action == Forward_blackhole) {
13740 		freemsg(mp);
13741 		return (NULL);
13742 	}
13743 	/* send icmp unreachable */
13744 	q = WR(q);
13745 	/* Sent by forwarding path, and router is global zone */
13746 	if (ip_source_routed(ipha, ipst)) {
13747 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13748 		    GLOBAL_ZONEID, ipst);
13749 	} else {
13750 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13751 		    ipst);
13752 	}
13753 
13754 	return (NULL);
13755 
13756 }
13757 
13758 /*
13759  * check ip header length and align it.
13760  */
13761 static boolean_t
13762 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13763 {
13764 	ssize_t len;
13765 	ill_t *ill;
13766 	ipha_t	*ipha;
13767 
13768 	len = MBLKL(mp);
13769 
13770 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13771 		ill = (ill_t *)q->q_ptr;
13772 
13773 		if (!OK_32PTR(mp->b_rptr))
13774 			IP_STAT(ipst, ip_notaligned1);
13775 		else
13776 			IP_STAT(ipst, ip_notaligned2);
13777 		/* Guard against bogus device drivers */
13778 		if (len < 0) {
13779 			/* clear b_prev - used by ip_mroute_decap */
13780 			mp->b_prev = NULL;
13781 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13782 			freemsg(mp);
13783 			return (B_FALSE);
13784 		}
13785 
13786 		if (ip_rput_pullups++ == 0) {
13787 			ipha = (ipha_t *)mp->b_rptr;
13788 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13789 			    "ip_check_and_align_header: %s forced us to "
13790 			    " pullup pkt, hdr len %ld, hdr addr %p",
13791 			    ill->ill_name, len, (void *)ipha);
13792 		}
13793 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13794 			/* clear b_prev - used by ip_mroute_decap */
13795 			mp->b_prev = NULL;
13796 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13797 			freemsg(mp);
13798 			return (B_FALSE);
13799 		}
13800 	}
13801 	return (B_TRUE);
13802 }
13803 
13804 /*
13805  * Handle the situation where a packet came in on `ill' but matched an IRE
13806  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13807  * for interface statistics.
13808  */
13809 ire_t *
13810 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13811 {
13812 	ire_t		*new_ire;
13813 	ill_t		*ire_ill;
13814 	uint_t		ifindex;
13815 	ip_stack_t	*ipst = ill->ill_ipst;
13816 	boolean_t	strict_check = B_FALSE;
13817 
13818 	/*
13819 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13820 	 * issue (e.g. packet received on an underlying interface matched an
13821 	 * IRE_LOCAL on its associated group interface).
13822 	 */
13823 	if (ire->ire_rfq != NULL &&
13824 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13825 		return (ire);
13826 	}
13827 
13828 	/*
13829 	 * Do another ire lookup here, using the ingress ill, to see if the
13830 	 * interface is in a usesrc group.
13831 	 * As long as the ills belong to the same group, we don't consider
13832 	 * them to be arriving on the wrong interface. Thus, if the switch
13833 	 * is doing inbound load spreading, we won't drop packets when the
13834 	 * ip*_strict_dst_multihoming switch is on.
13835 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13836 	 * where the local address may not be unique. In this case we were
13837 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13838 	 * actually returned. The new lookup, which is more specific, should
13839 	 * only find the IRE_LOCAL associated with the ingress ill if one
13840 	 * exists.
13841 	 */
13842 
13843 	if (ire->ire_ipversion == IPV4_VERSION) {
13844 		if (ipst->ips_ip_strict_dst_multihoming)
13845 			strict_check = B_TRUE;
13846 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13847 		    ill->ill_ipif, ALL_ZONES, NULL,
13848 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13849 	} else {
13850 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13851 		if (ipst->ips_ipv6_strict_dst_multihoming)
13852 			strict_check = B_TRUE;
13853 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13854 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13855 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13856 	}
13857 	/*
13858 	 * If the same ire that was returned in ip_input() is found then this
13859 	 * is an indication that usesrc groups are in use. The packet
13860 	 * arrived on a different ill in the group than the one associated with
13861 	 * the destination address.  If a different ire was found then the same
13862 	 * IP address must be hosted on multiple ills. This is possible with
13863 	 * unnumbered point2point interfaces. We switch to use this new ire in
13864 	 * order to have accurate interface statistics.
13865 	 */
13866 	if (new_ire != NULL) {
13867 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13868 			ire_refrele(ire);
13869 			ire = new_ire;
13870 		} else {
13871 			ire_refrele(new_ire);
13872 		}
13873 		return (ire);
13874 	} else if ((ire->ire_rfq == NULL) &&
13875 	    (ire->ire_ipversion == IPV4_VERSION)) {
13876 		/*
13877 		 * The best match could have been the original ire which
13878 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13879 		 * the strict multihoming checks are irrelevant as we consider
13880 		 * local addresses hosted on lo0 to be interface agnostic. We
13881 		 * only expect a null ire_rfq on IREs which are associated with
13882 		 * lo0 hence we can return now.
13883 		 */
13884 		return (ire);
13885 	}
13886 
13887 	/*
13888 	 * Chase pointers once and store locally.
13889 	 */
13890 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13891 	    (ill_t *)(ire->ire_rfq->q_ptr);
13892 	ifindex = ill->ill_usesrc_ifindex;
13893 
13894 	/*
13895 	 * Check if it's a legal address on the 'usesrc' interface.
13896 	 */
13897 	if ((ifindex != 0) && (ire_ill != NULL) &&
13898 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13899 		return (ire);
13900 	}
13901 
13902 	/*
13903 	 * If the ip*_strict_dst_multihoming switch is on then we can
13904 	 * only accept this packet if the interface is marked as routing.
13905 	 */
13906 	if (!(strict_check))
13907 		return (ire);
13908 
13909 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13910 	    ILLF_ROUTER) != 0) {
13911 		return (ire);
13912 	}
13913 
13914 	ire_refrele(ire);
13915 	return (NULL);
13916 }
13917 
13918 /*
13919  *
13920  * This is the fast forward path. If we are here, we dont need to
13921  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13922  * needed to find the nexthop in this case is much simpler
13923  */
13924 ire_t *
13925 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13926 {
13927 	ipha_t	*ipha;
13928 	ire_t	*src_ire;
13929 	ill_t	*stq_ill;
13930 	uint_t	hlen;
13931 	uint_t	pkt_len;
13932 	uint32_t sum;
13933 	queue_t	*dev_q;
13934 	ip_stack_t *ipst = ill->ill_ipst;
13935 	mblk_t *fpmp;
13936 	enum	ire_forward_action ret_action;
13937 
13938 	ipha = (ipha_t *)mp->b_rptr;
13939 
13940 	if (ire != NULL &&
13941 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13942 	    ire->ire_zoneid != ALL_ZONES) {
13943 		/*
13944 		 * Should only use IREs that are visible to the global
13945 		 * zone for forwarding.
13946 		 */
13947 		ire_refrele(ire);
13948 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13949 		/*
13950 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13951 		 * transient cases. In such case, just drop the packet
13952 		 */
13953 		if (ire->ire_type != IRE_CACHE)
13954 			goto drop;
13955 	}
13956 
13957 	/*
13958 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13959 	 * The loopback address check for both src and dst has already
13960 	 * been checked in ip_input
13961 	 */
13962 
13963 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13964 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13965 		goto drop;
13966 	}
13967 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13968 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13969 
13970 	if (src_ire != NULL) {
13971 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13972 		ire_refrele(src_ire);
13973 		goto drop;
13974 	}
13975 
13976 	/* No ire cache of nexthop. So first create one  */
13977 	if (ire == NULL) {
13978 
13979 		ire = ire_forward_simple(dst, &ret_action, ipst);
13980 
13981 		/*
13982 		 * We only come to ip_fast_forward if ip_cgtp_filter
13983 		 * is not set. So ire_forward() should not return with
13984 		 * Forward_check_multirt as the next action.
13985 		 */
13986 		ASSERT(ret_action != Forward_check_multirt);
13987 		if (ire == NULL) {
13988 			/* An attempt was made to forward the packet */
13989 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13990 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13991 			mp->b_prev = mp->b_next = 0;
13992 			/* send icmp unreachable */
13993 			/* Sent by forwarding path, and router is global zone */
13994 			if (ret_action == Forward_ret_icmp_err) {
13995 				if (ip_source_routed(ipha, ipst)) {
13996 					icmp_unreachable(ill->ill_wq, mp,
13997 					    ICMP_SOURCE_ROUTE_FAILED,
13998 					    GLOBAL_ZONEID, ipst);
13999 				} else {
14000 					icmp_unreachable(ill->ill_wq, mp,
14001 					    ICMP_HOST_UNREACHABLE,
14002 					    GLOBAL_ZONEID, ipst);
14003 				}
14004 			} else {
14005 				freemsg(mp);
14006 			}
14007 			return (NULL);
14008 		}
14009 	}
14010 
14011 	/*
14012 	 * Forwarding fastpath exception case:
14013 	 * If any of the following are true, we take the slowpath:
14014 	 *	o forwarding is not enabled
14015 	 *	o incoming and outgoing interface are the same, or in the same
14016 	 *	  IPMP group.
14017 	 *	o corresponding ire is in incomplete state
14018 	 *	o packet needs fragmentation
14019 	 *	o ARP cache is not resolved
14020 	 *
14021 	 * The codeflow from here on is thus:
14022 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14023 	 */
14024 	pkt_len = ntohs(ipha->ipha_length);
14025 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14026 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14027 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
14028 	    (ire->ire_nce == NULL) ||
14029 	    (pkt_len > ire->ire_max_frag) ||
14030 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14031 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14032 	    ipha->ipha_ttl <= 1) {
14033 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14034 		    ipha, ill, B_FALSE, B_TRUE);
14035 		return (ire);
14036 	}
14037 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14038 
14039 	DTRACE_PROBE4(ip4__forwarding__start,
14040 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14041 
14042 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14043 	    ipst->ips_ipv4firewall_forwarding,
14044 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14045 
14046 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14047 
14048 	if (mp == NULL)
14049 		goto drop;
14050 
14051 	mp->b_datap->db_struioun.cksum.flags = 0;
14052 	/* Adjust the checksum to reflect the ttl decrement. */
14053 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14054 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14055 	ipha->ipha_ttl--;
14056 
14057 	/*
14058 	 * Write the link layer header.  We can do this safely here,
14059 	 * because we have already tested to make sure that the IP
14060 	 * policy is not set, and that we have a fast path destination
14061 	 * header.
14062 	 */
14063 	mp->b_rptr -= hlen;
14064 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14065 
14066 	UPDATE_IB_PKT_COUNT(ire);
14067 	ire->ire_last_used_time = lbolt;
14068 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14069 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14070 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14071 
14072 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14073 		dev_q = ire->ire_stq->q_next;
14074 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14075 			goto indiscard;
14076 	}
14077 
14078 	DTRACE_PROBE4(ip4__physical__out__start,
14079 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14080 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14081 	    ipst->ips_ipv4firewall_physical_out,
14082 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14083 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14084 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14085 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14086 	    ip6_t *, NULL, int, 0);
14087 
14088 	if (mp != NULL) {
14089 		if (ipst->ips_ipobs_enabled) {
14090 			zoneid_t szone;
14091 
14092 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14093 			    ipst, ALL_ZONES);
14094 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14095 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14096 		}
14097 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14098 	}
14099 	return (ire);
14100 
14101 indiscard:
14102 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14103 drop:
14104 	if (mp != NULL)
14105 		freemsg(mp);
14106 	return (ire);
14107 
14108 }
14109 
14110 /*
14111  * This function is called in the forwarding slowpath, when
14112  * either the ire lacks the link-layer address, or the packet needs
14113  * further processing(eg. fragmentation), before transmission.
14114  */
14115 
14116 static void
14117 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14118     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14119 {
14120 	queue_t		*dev_q;
14121 	ire_t		*src_ire;
14122 	ip_stack_t	*ipst = ill->ill_ipst;
14123 	boolean_t	same_illgrp = B_FALSE;
14124 
14125 	ASSERT(ire->ire_stq != NULL);
14126 
14127 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14128 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14129 
14130 	/*
14131 	 * If the caller of this function is ip_fast_forward() skip the
14132 	 * next three checks as it does not apply.
14133 	 */
14134 	if (from_ip_fast_forward)
14135 		goto skip;
14136 
14137 	if (ll_multicast != 0) {
14138 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14139 		goto drop_pkt;
14140 	}
14141 
14142 	/*
14143 	 * check if ipha_src is a broadcast address. Note that this
14144 	 * check is redundant when we get here from ip_fast_forward()
14145 	 * which has already done this check. However, since we can
14146 	 * also get here from ip_rput_process_broadcast() or, for
14147 	 * for the slow path through ip_fast_forward(), we perform
14148 	 * the check again for code-reusability
14149 	 */
14150 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14151 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14152 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14153 		if (src_ire != NULL)
14154 			ire_refrele(src_ire);
14155 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14156 		ip2dbg(("ip_rput_process_forward: Received packet with"
14157 		    " bad src/dst address on %s\n", ill->ill_name));
14158 		goto drop_pkt;
14159 	}
14160 
14161 	/*
14162 	 * Check if we want to forward this one at this time.
14163 	 * We allow source routed packets on a host provided that
14164 	 * they go out the same ill or illgrp as they came in on.
14165 	 *
14166 	 * XXX To be quicker, we may wish to not chase pointers to
14167 	 * get the ILLF_ROUTER flag and instead store the
14168 	 * forwarding policy in the ire.  An unfortunate
14169 	 * side-effect of that would be requiring an ire flush
14170 	 * whenever the ILLF_ROUTER flag changes.
14171 	 */
14172 skip:
14173 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14174 
14175 	if (((ill->ill_flags &
14176 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14177 	    !(ip_source_routed(ipha, ipst) &&
14178 	    (ire->ire_rfq == q || same_illgrp))) {
14179 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14180 		if (ip_source_routed(ipha, ipst)) {
14181 			q = WR(q);
14182 			/*
14183 			 * Clear the indication that this may have
14184 			 * hardware checksum as we are not using it.
14185 			 */
14186 			DB_CKSUMFLAGS(mp) = 0;
14187 			/* Sent by forwarding path, and router is global zone */
14188 			icmp_unreachable(q, mp,
14189 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14190 			return;
14191 		}
14192 		goto drop_pkt;
14193 	}
14194 
14195 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14196 
14197 	/* Packet is being forwarded. Turning off hwcksum flag. */
14198 	DB_CKSUMFLAGS(mp) = 0;
14199 	if (ipst->ips_ip_g_send_redirects) {
14200 		/*
14201 		 * Check whether the incoming interface and outgoing
14202 		 * interface is part of the same group. If so,
14203 		 * send redirects.
14204 		 *
14205 		 * Check the source address to see if it originated
14206 		 * on the same logical subnet it is going back out on.
14207 		 * If so, we should be able to send it a redirect.
14208 		 * Avoid sending a redirect if the destination
14209 		 * is directly connected (i.e., ipha_dst is the same
14210 		 * as ire_gateway_addr or the ire_addr of the
14211 		 * nexthop IRE_CACHE ), or if the packet was source
14212 		 * routed out this interface.
14213 		 */
14214 		ipaddr_t src, nhop;
14215 		mblk_t	*mp1;
14216 		ire_t	*nhop_ire = NULL;
14217 
14218 		/*
14219 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14220 		 * If so, send redirects.
14221 		 */
14222 		if ((ire->ire_rfq == q || same_illgrp) &&
14223 		    !ip_source_routed(ipha, ipst)) {
14224 
14225 			nhop = (ire->ire_gateway_addr != 0 ?
14226 			    ire->ire_gateway_addr : ire->ire_addr);
14227 
14228 			if (ipha->ipha_dst == nhop) {
14229 				/*
14230 				 * We avoid sending a redirect if the
14231 				 * destination is directly connected
14232 				 * because it is possible that multiple
14233 				 * IP subnets may have been configured on
14234 				 * the link, and the source may not
14235 				 * be on the same subnet as ip destination,
14236 				 * even though they are on the same
14237 				 * physical link.
14238 				 */
14239 				goto sendit;
14240 			}
14241 
14242 			src = ipha->ipha_src;
14243 
14244 			/*
14245 			 * We look up the interface ire for the nexthop,
14246 			 * to see if ipha_src is in the same subnet
14247 			 * as the nexthop.
14248 			 *
14249 			 * Note that, if, in the future, IRE_CACHE entries
14250 			 * are obsoleted,  this lookup will not be needed,
14251 			 * as the ire passed to this function will be the
14252 			 * same as the nhop_ire computed below.
14253 			 */
14254 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14255 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14256 			    0, NULL, MATCH_IRE_TYPE, ipst);
14257 
14258 			if (nhop_ire != NULL) {
14259 				if ((src & nhop_ire->ire_mask) ==
14260 				    (nhop & nhop_ire->ire_mask)) {
14261 					/*
14262 					 * The source is directly connected.
14263 					 * Just copy the ip header (which is
14264 					 * in the first mblk)
14265 					 */
14266 					mp1 = copyb(mp);
14267 					if (mp1 != NULL) {
14268 						icmp_send_redirect(WR(q), mp1,
14269 						    nhop, ipst);
14270 					}
14271 				}
14272 				ire_refrele(nhop_ire);
14273 			}
14274 		}
14275 	}
14276 sendit:
14277 	dev_q = ire->ire_stq->q_next;
14278 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14279 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14280 		freemsg(mp);
14281 		return;
14282 	}
14283 
14284 	ip_rput_forward(ire, ipha, mp, ill);
14285 	return;
14286 
14287 drop_pkt:
14288 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14289 	freemsg(mp);
14290 }
14291 
14292 ire_t *
14293 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14294     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14295 {
14296 	queue_t		*q;
14297 	uint16_t	hcksumflags;
14298 	ip_stack_t	*ipst = ill->ill_ipst;
14299 
14300 	q = *qp;
14301 
14302 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14303 
14304 	/*
14305 	 * Clear the indication that this may have hardware
14306 	 * checksum as we are not using it for forwarding.
14307 	 */
14308 	hcksumflags = DB_CKSUMFLAGS(mp);
14309 	DB_CKSUMFLAGS(mp) = 0;
14310 
14311 	/*
14312 	 * Directed broadcast forwarding: if the packet came in over a
14313 	 * different interface then it is routed out over we can forward it.
14314 	 */
14315 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14316 		ire_refrele(ire);
14317 		freemsg(mp);
14318 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14319 		return (NULL);
14320 	}
14321 	/*
14322 	 * For multicast we have set dst to be INADDR_BROADCAST
14323 	 * for delivering to all STREAMS.
14324 	 */
14325 	if (!CLASSD(ipha->ipha_dst)) {
14326 		ire_t *new_ire;
14327 		ipif_t *ipif;
14328 
14329 		ipif = ipif_get_next_ipif(NULL, ill);
14330 		if (ipif == NULL) {
14331 discard:		ire_refrele(ire);
14332 			freemsg(mp);
14333 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14334 			return (NULL);
14335 		}
14336 		new_ire = ire_ctable_lookup(dst, 0, 0,
14337 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14338 		ipif_refrele(ipif);
14339 
14340 		if (new_ire != NULL) {
14341 			/*
14342 			 * If the matching IRE_BROADCAST is part of an IPMP
14343 			 * group, then drop the packet unless our ill has been
14344 			 * nominated to receive for the group.
14345 			 */
14346 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14347 			    new_ire->ire_rfq != q) {
14348 				ire_refrele(new_ire);
14349 				goto discard;
14350 			}
14351 
14352 			/*
14353 			 * In the special case of multirouted broadcast
14354 			 * packets, we unconditionally need to "gateway"
14355 			 * them to the appropriate interface here.
14356 			 * In the normal case, this cannot happen, because
14357 			 * there is no broadcast IRE tagged with the
14358 			 * RTF_MULTIRT flag.
14359 			 */
14360 			if (new_ire->ire_flags & RTF_MULTIRT) {
14361 				ire_refrele(new_ire);
14362 				if (ire->ire_rfq != NULL) {
14363 					q = ire->ire_rfq;
14364 					*qp = q;
14365 				}
14366 			} else {
14367 				ire_refrele(ire);
14368 				ire = new_ire;
14369 			}
14370 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14371 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14372 				/*
14373 				 * Free the message if
14374 				 * ip_g_forward_directed_bcast is turned
14375 				 * off for non-local broadcast.
14376 				 */
14377 				ire_refrele(ire);
14378 				freemsg(mp);
14379 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14380 				return (NULL);
14381 			}
14382 		} else {
14383 			/*
14384 			 * This CGTP packet successfully passed the
14385 			 * CGTP filter, but the related CGTP
14386 			 * broadcast IRE has not been found,
14387 			 * meaning that the redundant ipif is
14388 			 * probably down. However, if we discarded
14389 			 * this packet, its duplicate would be
14390 			 * filtered out by the CGTP filter so none
14391 			 * of them would get through. So we keep
14392 			 * going with this one.
14393 			 */
14394 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14395 			if (ire->ire_rfq != NULL) {
14396 				q = ire->ire_rfq;
14397 				*qp = q;
14398 			}
14399 		}
14400 	}
14401 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14402 		/*
14403 		 * Verify that there are not more then one
14404 		 * IRE_BROADCAST with this broadcast address which
14405 		 * has ire_stq set.
14406 		 * TODO: simplify, loop over all IRE's
14407 		 */
14408 		ire_t	*ire1;
14409 		int	num_stq = 0;
14410 		mblk_t	*mp1;
14411 
14412 		/* Find the first one with ire_stq set */
14413 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14414 		for (ire1 = ire; ire1 &&
14415 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14416 		    ire1 = ire1->ire_next)
14417 			;
14418 		if (ire1) {
14419 			ire_refrele(ire);
14420 			ire = ire1;
14421 			IRE_REFHOLD(ire);
14422 		}
14423 
14424 		/* Check if there are additional ones with stq set */
14425 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14426 			if (ire->ire_addr != ire1->ire_addr)
14427 				break;
14428 			if (ire1->ire_stq) {
14429 				num_stq++;
14430 				break;
14431 			}
14432 		}
14433 		rw_exit(&ire->ire_bucket->irb_lock);
14434 		if (num_stq == 1 && ire->ire_stq != NULL) {
14435 			ip1dbg(("ip_rput_process_broadcast: directed "
14436 			    "broadcast to 0x%x\n",
14437 			    ntohl(ire->ire_addr)));
14438 			mp1 = copymsg(mp);
14439 			if (mp1) {
14440 				switch (ipha->ipha_protocol) {
14441 				case IPPROTO_UDP:
14442 					ip_udp_input(q, mp1, ipha, ire, ill);
14443 					break;
14444 				default:
14445 					ip_proto_input(q, mp1, ipha, ire, ill,
14446 					    0);
14447 					break;
14448 				}
14449 			}
14450 			/*
14451 			 * Adjust ttl to 2 (1+1 - the forward engine
14452 			 * will decrement it by one.
14453 			 */
14454 			if (ip_csum_hdr(ipha)) {
14455 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14456 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14457 				freemsg(mp);
14458 				ire_refrele(ire);
14459 				return (NULL);
14460 			}
14461 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14462 			ipha->ipha_hdr_checksum = 0;
14463 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14464 			ip_rput_process_forward(q, mp, ire, ipha,
14465 			    ill, ll_multicast, B_FALSE);
14466 			ire_refrele(ire);
14467 			return (NULL);
14468 		}
14469 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14470 		    ntohl(ire->ire_addr)));
14471 	}
14472 
14473 	/* Restore any hardware checksum flags */
14474 	DB_CKSUMFLAGS(mp) = hcksumflags;
14475 	return (ire);
14476 }
14477 
14478 /* ARGSUSED */
14479 static boolean_t
14480 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14481     int *ll_multicast, ipaddr_t *dstp)
14482 {
14483 	ip_stack_t	*ipst = ill->ill_ipst;
14484 
14485 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14486 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14487 	    ntohs(ipha->ipha_length));
14488 
14489 	/*
14490 	 * So that we don't end up with dups, only one ill in an IPMP group is
14491 	 * nominated to receive multicast traffic.
14492 	 */
14493 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14494 		goto drop_pkt;
14495 
14496 	/*
14497 	 * Forward packets only if we have joined the allmulti
14498 	 * group on this interface.
14499 	 */
14500 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14501 		int retval;
14502 
14503 		/*
14504 		 * Clear the indication that this may have hardware
14505 		 * checksum as we are not using it.
14506 		 */
14507 		DB_CKSUMFLAGS(mp) = 0;
14508 		retval = ip_mforward(ill, ipha, mp);
14509 		/* ip_mforward updates mib variables if needed */
14510 		/* clear b_prev - used by ip_mroute_decap */
14511 		mp->b_prev = NULL;
14512 
14513 		switch (retval) {
14514 		case 0:
14515 			/*
14516 			 * pkt is okay and arrived on phyint.
14517 			 *
14518 			 * If we are running as a multicast router
14519 			 * we need to see all IGMP and/or PIM packets.
14520 			 */
14521 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14522 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14523 				goto done;
14524 			}
14525 			break;
14526 		case -1:
14527 			/* pkt is mal-formed, toss it */
14528 			goto drop_pkt;
14529 		case 1:
14530 			/* pkt is okay and arrived on a tunnel */
14531 			/*
14532 			 * If we are running a multicast router
14533 			 *  we need to see all igmp packets.
14534 			 */
14535 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14536 				*dstp = INADDR_BROADCAST;
14537 				*ll_multicast = 1;
14538 				return (B_FALSE);
14539 			}
14540 
14541 			goto drop_pkt;
14542 		}
14543 	}
14544 
14545 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14546 		/*
14547 		 * This might just be caused by the fact that
14548 		 * multiple IP Multicast addresses map to the same
14549 		 * link layer multicast - no need to increment counter!
14550 		 */
14551 		freemsg(mp);
14552 		return (B_TRUE);
14553 	}
14554 done:
14555 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14556 	/*
14557 	 * This assumes the we deliver to all streams for multicast
14558 	 * and broadcast packets.
14559 	 */
14560 	*dstp = INADDR_BROADCAST;
14561 	*ll_multicast = 1;
14562 	return (B_FALSE);
14563 drop_pkt:
14564 	ip2dbg(("ip_rput: drop pkt\n"));
14565 	freemsg(mp);
14566 	return (B_TRUE);
14567 }
14568 
14569 /*
14570  * This function is used to both return an indication of whether or not
14571  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14572  * and in doing so, determine whether or not it is broadcast vs multicast.
14573  * For it to be a broadcast packet, we must have the appropriate mblk_t
14574  * hanging off the ill_t.  If this is either not present or doesn't match
14575  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14576  * to be multicast.  Thus NICs that have no broadcast address (or no
14577  * capability for one, such as point to point links) cannot return as
14578  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14579  * the return values simplifies the current use of the return value of this
14580  * function, which is to pass through the multicast/broadcast characteristic
14581  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14582  * changing the return value to some other symbol demands the appropriate
14583  * "translation" when hpe_flags is set prior to calling hook_run() for
14584  * packet events.
14585  */
14586 int
14587 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14588 {
14589 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14590 	mblk_t *bmp;
14591 
14592 	if (ind->dl_group_address) {
14593 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14594 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14595 		    MBLKL(mb) &&
14596 		    (bmp = ill->ill_bcast_mp) != NULL) {
14597 			dl_unitdata_req_t *dlur;
14598 			uint8_t *bphys_addr;
14599 
14600 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14601 			if (ill->ill_sap_length < 0)
14602 				bphys_addr = (uchar_t *)dlur +
14603 				    dlur->dl_dest_addr_offset;
14604 			else
14605 				bphys_addr = (uchar_t *)dlur +
14606 				    dlur->dl_dest_addr_offset +
14607 				    ill->ill_sap_length;
14608 
14609 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14610 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14611 				return (HPE_BROADCAST);
14612 			}
14613 			return (HPE_MULTICAST);
14614 		}
14615 		return (HPE_MULTICAST);
14616 	}
14617 	return (0);
14618 }
14619 
14620 static boolean_t
14621 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14622     int *ll_multicast, mblk_t **mpp)
14623 {
14624 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14625 	boolean_t must_copy = B_FALSE;
14626 	struct iocblk   *iocp;
14627 	ipha_t		*ipha;
14628 	ip_stack_t	*ipst = ill->ill_ipst;
14629 
14630 #define	rptr    ((uchar_t *)ipha)
14631 
14632 	first_mp = *first_mpp;
14633 	mp = *mpp;
14634 
14635 	ASSERT(first_mp == mp);
14636 
14637 	/*
14638 	 * if db_ref > 1 then copymsg and free original. Packet may be
14639 	 * changed and do not want other entity who has a reference to this
14640 	 * message to trip over the changes. This is a blind change because
14641 	 * trying to catch all places that might change packet is too
14642 	 * difficult (since it may be a module above this one)
14643 	 *
14644 	 * This corresponds to the non-fast path case. We walk down the full
14645 	 * chain in this case, and check the db_ref count of all the dblks,
14646 	 * and do a copymsg if required. It is possible that the db_ref counts
14647 	 * of the data blocks in the mblk chain can be different.
14648 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14649 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14650 	 * 'snoop' is running.
14651 	 */
14652 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14653 		if (mp1->b_datap->db_ref > 1) {
14654 			must_copy = B_TRUE;
14655 			break;
14656 		}
14657 	}
14658 
14659 	if (must_copy) {
14660 		mp1 = copymsg(mp);
14661 		if (mp1 == NULL) {
14662 			for (mp1 = mp; mp1 != NULL;
14663 			    mp1 = mp1->b_cont) {
14664 				mp1->b_next = NULL;
14665 				mp1->b_prev = NULL;
14666 			}
14667 			freemsg(mp);
14668 			if (ill != NULL) {
14669 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14670 			} else {
14671 				BUMP_MIB(&ipst->ips_ip_mib,
14672 				    ipIfStatsInDiscards);
14673 			}
14674 			return (B_TRUE);
14675 		}
14676 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14677 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14678 			/* Copy b_prev - used by ip_mroute_decap */
14679 			to_mp->b_prev = from_mp->b_prev;
14680 			from_mp->b_prev = NULL;
14681 		}
14682 		*first_mpp = first_mp = mp1;
14683 		freemsg(mp);
14684 		mp = mp1;
14685 		*mpp = mp1;
14686 	}
14687 
14688 	ipha = (ipha_t *)mp->b_rptr;
14689 
14690 	/*
14691 	 * previous code has a case for M_DATA.
14692 	 * We want to check how that happens.
14693 	 */
14694 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14695 	switch (first_mp->b_datap->db_type) {
14696 	case M_PROTO:
14697 	case M_PCPROTO:
14698 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14699 		    DL_UNITDATA_IND) {
14700 			/* Go handle anything other than data elsewhere. */
14701 			ip_rput_dlpi(q, mp);
14702 			return (B_TRUE);
14703 		}
14704 
14705 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14706 		/* Ditch the DLPI header. */
14707 		mp1 = mp->b_cont;
14708 		ASSERT(first_mp == mp);
14709 		*first_mpp = mp1;
14710 		freeb(mp);
14711 		*mpp = mp1;
14712 		return (B_FALSE);
14713 	case M_IOCACK:
14714 		ip1dbg(("got iocack "));
14715 		iocp = (struct iocblk *)mp->b_rptr;
14716 		switch (iocp->ioc_cmd) {
14717 		case DL_IOC_HDR_INFO:
14718 			ill = (ill_t *)q->q_ptr;
14719 			ill_fastpath_ack(ill, mp);
14720 			return (B_TRUE);
14721 		case SIOCSTUNPARAM:
14722 		case OSIOCSTUNPARAM:
14723 			/* Go through qwriter_ip */
14724 			break;
14725 		case SIOCGTUNPARAM:
14726 		case OSIOCGTUNPARAM:
14727 			ip_rput_other(NULL, q, mp, NULL);
14728 			return (B_TRUE);
14729 		default:
14730 			putnext(q, mp);
14731 			return (B_TRUE);
14732 		}
14733 		/* FALLTHRU */
14734 	case M_ERROR:
14735 	case M_HANGUP:
14736 		/*
14737 		 * Since this is on the ill stream we unconditionally
14738 		 * bump up the refcount
14739 		 */
14740 		ill_refhold(ill);
14741 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14742 		return (B_TRUE);
14743 	case M_CTL:
14744 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14745 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14746 		    IPHADA_M_CTL)) {
14747 			/*
14748 			 * It's an IPsec accelerated packet.
14749 			 * Make sure that the ill from which we received the
14750 			 * packet has enabled IPsec hardware acceleration.
14751 			 */
14752 			if (!(ill->ill_capabilities &
14753 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14754 				/* IPsec kstats: bean counter */
14755 				freemsg(mp);
14756 				return (B_TRUE);
14757 			}
14758 
14759 			/*
14760 			 * Make mp point to the mblk following the M_CTL,
14761 			 * then process according to type of mp.
14762 			 * After this processing, first_mp will point to
14763 			 * the data-attributes and mp to the pkt following
14764 			 * the M_CTL.
14765 			 */
14766 			mp = first_mp->b_cont;
14767 			if (mp == NULL) {
14768 				freemsg(first_mp);
14769 				return (B_TRUE);
14770 			}
14771 			/*
14772 			 * A Hardware Accelerated packet can only be M_DATA
14773 			 * ESP or AH packet.
14774 			 */
14775 			if (mp->b_datap->db_type != M_DATA) {
14776 				/* non-M_DATA IPsec accelerated packet */
14777 				IPSECHW_DEBUG(IPSECHW_PKT,
14778 				    ("non-M_DATA IPsec accelerated pkt\n"));
14779 				freemsg(first_mp);
14780 				return (B_TRUE);
14781 			}
14782 			ipha = (ipha_t *)mp->b_rptr;
14783 			if (ipha->ipha_protocol != IPPROTO_AH &&
14784 			    ipha->ipha_protocol != IPPROTO_ESP) {
14785 				IPSECHW_DEBUG(IPSECHW_PKT,
14786 				    ("non-M_DATA IPsec accelerated pkt\n"));
14787 				freemsg(first_mp);
14788 				return (B_TRUE);
14789 			}
14790 			*mpp = mp;
14791 			return (B_FALSE);
14792 		}
14793 		putnext(q, mp);
14794 		return (B_TRUE);
14795 	case M_IOCNAK:
14796 		ip1dbg(("got iocnak "));
14797 		iocp = (struct iocblk *)mp->b_rptr;
14798 		switch (iocp->ioc_cmd) {
14799 		case SIOCSTUNPARAM:
14800 		case OSIOCSTUNPARAM:
14801 			/*
14802 			 * Since this is on the ill stream we unconditionally
14803 			 * bump up the refcount
14804 			 */
14805 			ill_refhold(ill);
14806 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14807 			return (B_TRUE);
14808 		case DL_IOC_HDR_INFO:
14809 		case SIOCGTUNPARAM:
14810 		case OSIOCGTUNPARAM:
14811 			ip_rput_other(NULL, q, mp, NULL);
14812 			return (B_TRUE);
14813 		default:
14814 			break;
14815 		}
14816 		/* FALLTHRU */
14817 	default:
14818 		putnext(q, mp);
14819 		return (B_TRUE);
14820 	}
14821 }
14822 
14823 /* Read side put procedure.  Packets coming from the wire arrive here. */
14824 void
14825 ip_rput(queue_t *q, mblk_t *mp)
14826 {
14827 	ill_t	*ill;
14828 	union DL_primitives *dl;
14829 
14830 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14831 
14832 	ill = (ill_t *)q->q_ptr;
14833 
14834 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14835 		/*
14836 		 * If things are opening or closing, only accept high-priority
14837 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14838 		 * created; on close, things hanging off the ill may have been
14839 		 * freed already.)
14840 		 */
14841 		dl = (union DL_primitives *)mp->b_rptr;
14842 		if (DB_TYPE(mp) != M_PCPROTO ||
14843 		    dl->dl_primitive == DL_UNITDATA_IND) {
14844 			/*
14845 			 * SIOC[GS]TUNPARAM ioctls can come here.
14846 			 */
14847 			inet_freemsg(mp);
14848 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14849 			    "ip_rput_end: q %p (%S)", q, "uninit");
14850 			return;
14851 		}
14852 	}
14853 
14854 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14855 	    "ip_rput_end: q %p (%S)", q, "end");
14856 
14857 	ip_input(ill, NULL, mp, NULL);
14858 }
14859 
14860 static mblk_t *
14861 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14862 {
14863 	mblk_t *mp1;
14864 	boolean_t adjusted = B_FALSE;
14865 	ip_stack_t *ipst = ill->ill_ipst;
14866 
14867 	IP_STAT(ipst, ip_db_ref);
14868 	/*
14869 	 * The IP_RECVSLLA option depends on having the
14870 	 * link layer header. First check that:
14871 	 * a> the underlying device is of type ether,
14872 	 * since this option is currently supported only
14873 	 * over ethernet.
14874 	 * b> there is enough room to copy over the link
14875 	 * layer header.
14876 	 *
14877 	 * Once the checks are done, adjust rptr so that
14878 	 * the link layer header will be copied via
14879 	 * copymsg. Note that, IFT_ETHER may be returned
14880 	 * by some non-ethernet drivers but in this case
14881 	 * the second check will fail.
14882 	 */
14883 	if (ill->ill_type == IFT_ETHER &&
14884 	    (mp->b_rptr - mp->b_datap->db_base) >=
14885 	    sizeof (struct ether_header)) {
14886 		mp->b_rptr -= sizeof (struct ether_header);
14887 		adjusted = B_TRUE;
14888 	}
14889 	mp1 = copymsg(mp);
14890 
14891 	if (mp1 == NULL) {
14892 		mp->b_next = NULL;
14893 		/* clear b_prev - used by ip_mroute_decap */
14894 		mp->b_prev = NULL;
14895 		freemsg(mp);
14896 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14897 		return (NULL);
14898 	}
14899 
14900 	if (adjusted) {
14901 		/*
14902 		 * Copy is done. Restore the pointer in
14903 		 * the _new_ mblk
14904 		 */
14905 		mp1->b_rptr += sizeof (struct ether_header);
14906 	}
14907 
14908 	/* Copy b_prev - used by ip_mroute_decap */
14909 	mp1->b_prev = mp->b_prev;
14910 	mp->b_prev = NULL;
14911 
14912 	/* preserve the hardware checksum flags and data, if present */
14913 	if (DB_CKSUMFLAGS(mp) != 0) {
14914 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14915 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14916 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14917 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14918 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14919 	}
14920 
14921 	freemsg(mp);
14922 	return (mp1);
14923 }
14924 
14925 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14926 	if (tail != NULL)					\
14927 		tail->b_next = mp;				\
14928 	else							\
14929 		head = mp;					\
14930 	tail = mp;						\
14931 	cnt++;							\
14932 }
14933 
14934 /*
14935  * Direct read side procedure capable of dealing with chains. GLDv3 based
14936  * drivers call this function directly with mblk chains while STREAMS
14937  * read side procedure ip_rput() calls this for single packet with ip_ring
14938  * set to NULL to process one packet at a time.
14939  *
14940  * The ill will always be valid if this function is called directly from
14941  * the driver.
14942  *
14943  * If ip_input() is called from GLDv3:
14944  *
14945  *   - This must be a non-VLAN IP stream.
14946  *   - 'mp' is either an untagged or a special priority-tagged packet.
14947  *   - Any VLAN tag that was in the MAC header has been stripped.
14948  *
14949  * If the IP header in packet is not 32-bit aligned, every message in the
14950  * chain will be aligned before further operations. This is required on SPARC
14951  * platform.
14952  */
14953 /* ARGSUSED */
14954 void
14955 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14956     struct mac_header_info_s *mhip)
14957 {
14958 	ipaddr_t		dst = NULL;
14959 	ipaddr_t		prev_dst;
14960 	ire_t			*ire = NULL;
14961 	ipha_t			*ipha;
14962 	uint_t			pkt_len;
14963 	ssize_t			len;
14964 	uint_t			opt_len;
14965 	int			ll_multicast;
14966 	int			cgtp_flt_pkt;
14967 	queue_t			*q = ill->ill_rq;
14968 	squeue_t		*curr_sqp = NULL;
14969 	mblk_t 			*head = NULL;
14970 	mblk_t			*tail = NULL;
14971 	mblk_t			*first_mp;
14972 	int			cnt = 0;
14973 	ip_stack_t		*ipst = ill->ill_ipst;
14974 	mblk_t			*mp;
14975 	mblk_t			*dmp;
14976 	uint8_t			tag;
14977 
14978 	ASSERT(mp_chain != NULL);
14979 	ASSERT(ill != NULL);
14980 
14981 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14982 
14983 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14984 
14985 #define	rptr	((uchar_t *)ipha)
14986 
14987 	while (mp_chain != NULL) {
14988 		mp = mp_chain;
14989 		mp_chain = mp_chain->b_next;
14990 		mp->b_next = NULL;
14991 		ll_multicast = 0;
14992 
14993 		/*
14994 		 * We do ire caching from one iteration to
14995 		 * another. In the event the packet chain contains
14996 		 * all packets from the same dst, this caching saves
14997 		 * an ire_cache_lookup for each of the succeeding
14998 		 * packets in a packet chain.
14999 		 */
15000 		prev_dst = dst;
15001 
15002 		/*
15003 		 * if db_ref > 1 then copymsg and free original. Packet
15004 		 * may be changed and we do not want the other entity
15005 		 * who has a reference to this message to trip over the
15006 		 * changes. This is a blind change because trying to
15007 		 * catch all places that might change the packet is too
15008 		 * difficult.
15009 		 *
15010 		 * This corresponds to the fast path case, where we have
15011 		 * a chain of M_DATA mblks.  We check the db_ref count
15012 		 * of only the 1st data block in the mblk chain. There
15013 		 * doesn't seem to be a reason why a device driver would
15014 		 * send up data with varying db_ref counts in the mblk
15015 		 * chain. In any case the Fast path is a private
15016 		 * interface, and our drivers don't do such a thing.
15017 		 * Given the above assumption, there is no need to walk
15018 		 * down the entire mblk chain (which could have a
15019 		 * potential performance problem)
15020 		 *
15021 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
15022 		 * to here because of exclusive ip stacks and vnics.
15023 		 * Packets transmitted from exclusive stack over vnic
15024 		 * can have db_ref > 1 and when it gets looped back to
15025 		 * another vnic in a different zone, you have ip_input()
15026 		 * getting dblks with db_ref > 1. So if someone
15027 		 * complains of TCP performance under this scenario,
15028 		 * take a serious look here on the impact of copymsg().
15029 		 */
15030 
15031 		if (DB_REF(mp) > 1) {
15032 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
15033 				continue;
15034 		}
15035 
15036 		/*
15037 		 * Check and align the IP header.
15038 		 */
15039 		first_mp = mp;
15040 		if (DB_TYPE(mp) == M_DATA) {
15041 			dmp = mp;
15042 		} else if (DB_TYPE(mp) == M_PROTO &&
15043 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15044 			dmp = mp->b_cont;
15045 		} else {
15046 			dmp = NULL;
15047 		}
15048 		if (dmp != NULL) {
15049 			/*
15050 			 * IP header ptr not aligned?
15051 			 * OR IP header not complete in first mblk
15052 			 */
15053 			if (!OK_32PTR(dmp->b_rptr) ||
15054 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15055 				if (!ip_check_and_align_header(q, dmp, ipst))
15056 					continue;
15057 			}
15058 		}
15059 
15060 		/*
15061 		 * ip_input fast path
15062 		 */
15063 
15064 		/* mblk type is not M_DATA */
15065 		if (DB_TYPE(mp) != M_DATA) {
15066 			if (ip_rput_process_notdata(q, &first_mp, ill,
15067 			    &ll_multicast, &mp))
15068 				continue;
15069 
15070 			/*
15071 			 * The only way we can get here is if we had a
15072 			 * packet that was either a DL_UNITDATA_IND or
15073 			 * an M_CTL for an IPsec accelerated packet.
15074 			 *
15075 			 * In either case, the first_mp will point to
15076 			 * the leading M_PROTO or M_CTL.
15077 			 */
15078 			ASSERT(first_mp != NULL);
15079 		} else if (mhip != NULL) {
15080 			/*
15081 			 * ll_multicast is set here so that it is ready
15082 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15083 			 * manipulates ll_multicast in the same fashion when
15084 			 * called from ip_rput_process_notdata.
15085 			 */
15086 			switch (mhip->mhi_dsttype) {
15087 			case MAC_ADDRTYPE_MULTICAST :
15088 				ll_multicast = HPE_MULTICAST;
15089 				break;
15090 			case MAC_ADDRTYPE_BROADCAST :
15091 				ll_multicast = HPE_BROADCAST;
15092 				break;
15093 			default :
15094 				break;
15095 			}
15096 		}
15097 
15098 		/* Only M_DATA can come here and it is always aligned */
15099 		ASSERT(DB_TYPE(mp) == M_DATA);
15100 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15101 
15102 		ipha = (ipha_t *)mp->b_rptr;
15103 		len = mp->b_wptr - rptr;
15104 		pkt_len = ntohs(ipha->ipha_length);
15105 
15106 		/*
15107 		 * We must count all incoming packets, even if they end
15108 		 * up being dropped later on.
15109 		 */
15110 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15111 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15112 
15113 		/* multiple mblk or too short */
15114 		len -= pkt_len;
15115 		if (len != 0) {
15116 			/*
15117 			 * Make sure we have data length consistent
15118 			 * with the IP header.
15119 			 */
15120 			if (mp->b_cont == NULL) {
15121 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15122 					BUMP_MIB(ill->ill_ip_mib,
15123 					    ipIfStatsInHdrErrors);
15124 					ip2dbg(("ip_input: drop pkt\n"));
15125 					freemsg(mp);
15126 					continue;
15127 				}
15128 				mp->b_wptr = rptr + pkt_len;
15129 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15130 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15131 					BUMP_MIB(ill->ill_ip_mib,
15132 					    ipIfStatsInHdrErrors);
15133 					ip2dbg(("ip_input: drop pkt\n"));
15134 					freemsg(mp);
15135 					continue;
15136 				}
15137 				(void) adjmsg(mp, -len);
15138 				/*
15139 				 * As the message len was adjusted, invalidate
15140 				 * any hw checksum here. This will force IP to
15141 				 * calculate the checksum in sw, but only for
15142 				 * this packet.
15143 				 */
15144 				DB_CKSUMFLAGS(mp) = 0;
15145 				IP_STAT(ipst, ip_multimblk3);
15146 			}
15147 		}
15148 
15149 		/* Obtain the dst of the current packet */
15150 		dst = ipha->ipha_dst;
15151 
15152 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15153 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15154 		    ipha, ip6_t *, NULL, int, 0);
15155 
15156 		/*
15157 		 * The following test for loopback is faster than
15158 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15159 		 * operations.
15160 		 * Note that these addresses are always in network byte order
15161 		 */
15162 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15163 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15164 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15165 			freemsg(mp);
15166 			continue;
15167 		}
15168 
15169 		/*
15170 		 * The event for packets being received from a 'physical'
15171 		 * interface is placed after validation of the source and/or
15172 		 * destination address as being local so that packets can be
15173 		 * redirected to loopback addresses using ipnat.
15174 		 */
15175 		DTRACE_PROBE4(ip4__physical__in__start,
15176 		    ill_t *, ill, ill_t *, NULL,
15177 		    ipha_t *, ipha, mblk_t *, first_mp);
15178 
15179 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15180 		    ipst->ips_ipv4firewall_physical_in,
15181 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15182 
15183 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15184 
15185 		if (first_mp == NULL) {
15186 			continue;
15187 		}
15188 		dst = ipha->ipha_dst;
15189 		/*
15190 		 * Attach any necessary label information to
15191 		 * this packet
15192 		 */
15193 		if (is_system_labeled() &&
15194 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15195 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15196 			freemsg(mp);
15197 			continue;
15198 		}
15199 
15200 		if (ipst->ips_ipobs_enabled) {
15201 			zoneid_t dzone;
15202 
15203 			/*
15204 			 * On the inbound path the src zone will be unknown as
15205 			 * this packet has come from the wire.
15206 			 */
15207 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15208 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15209 			    ill, IPV4_VERSION, 0, ipst);
15210 		}
15211 
15212 		/*
15213 		 * Reuse the cached ire only if the ipha_dst of the previous
15214 		 * packet is the same as the current packet AND it is not
15215 		 * INADDR_ANY.
15216 		 */
15217 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15218 		    (ire != NULL)) {
15219 			ire_refrele(ire);
15220 			ire = NULL;
15221 		}
15222 
15223 		opt_len = ipha->ipha_version_and_hdr_length -
15224 		    IP_SIMPLE_HDR_VERSION;
15225 
15226 		/*
15227 		 * Check to see if we can take the fastpath.
15228 		 * That is possible if the following conditions are met
15229 		 *	o Tsol disabled
15230 		 *	o CGTP disabled
15231 		 *	o ipp_action_count is 0
15232 		 *	o no options in the packet
15233 		 *	o not a RSVP packet
15234 		 * 	o not a multicast packet
15235 		 *	o ill not in IP_DHCPINIT_IF mode
15236 		 */
15237 		if (!is_system_labeled() &&
15238 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15239 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15240 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15241 			if (ire == NULL)
15242 				ire = ire_cache_lookup_simple(dst, ipst);
15243 			/*
15244 			 * Unless forwarding is enabled, dont call
15245 			 * ip_fast_forward(). Incoming packet is for forwarding
15246 			 */
15247 			if ((ill->ill_flags & ILLF_ROUTER) &&
15248 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15249 				ire = ip_fast_forward(ire, dst, ill, mp);
15250 				continue;
15251 			}
15252 			/* incoming packet is for local consumption */
15253 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15254 				goto local;
15255 		}
15256 
15257 		/*
15258 		 * Disable ire caching for anything more complex
15259 		 * than the simple fast path case we checked for above.
15260 		 */
15261 		if (ire != NULL) {
15262 			ire_refrele(ire);
15263 			ire = NULL;
15264 		}
15265 
15266 		/*
15267 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15268 		 * server to unicast DHCP packets to a DHCP client using the
15269 		 * IP address it is offering to the client.  This can be
15270 		 * disabled through the "broadcast bit", but not all DHCP
15271 		 * servers honor that bit.  Therefore, to interoperate with as
15272 		 * many DHCP servers as possible, the DHCP client allows the
15273 		 * server to unicast, but we treat those packets as broadcast
15274 		 * here.  Note that we don't rewrite the packet itself since
15275 		 * (a) that would mess up the checksums and (b) the DHCP
15276 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15277 		 * hand it the packet regardless.
15278 		 */
15279 		if (ill->ill_dhcpinit != 0 &&
15280 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15281 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15282 			udpha_t *udpha;
15283 
15284 			/*
15285 			 * Reload ipha since pullupmsg() can change b_rptr.
15286 			 */
15287 			ipha = (ipha_t *)mp->b_rptr;
15288 			udpha = (udpha_t *)&ipha[1];
15289 
15290 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15291 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15292 				    mblk_t *, mp);
15293 				dst = INADDR_BROADCAST;
15294 			}
15295 		}
15296 
15297 		/* Full-blown slow path */
15298 		if (opt_len != 0) {
15299 			if (len != 0)
15300 				IP_STAT(ipst, ip_multimblk4);
15301 			else
15302 				IP_STAT(ipst, ip_ipoptions);
15303 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15304 			    &dst, ipst))
15305 				continue;
15306 		}
15307 
15308 		/*
15309 		 * Invoke the CGTP (multirouting) filtering module to process
15310 		 * the incoming packet. Packets identified as duplicates
15311 		 * must be discarded. Filtering is active only if the
15312 		 * the ip_cgtp_filter ndd variable is non-zero.
15313 		 */
15314 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15315 		if (ipst->ips_ip_cgtp_filter &&
15316 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15317 			netstackid_t stackid;
15318 
15319 			stackid = ipst->ips_netstack->netstack_stackid;
15320 			cgtp_flt_pkt =
15321 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15322 			    ill->ill_phyint->phyint_ifindex, mp);
15323 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15324 				freemsg(first_mp);
15325 				continue;
15326 			}
15327 		}
15328 
15329 		/*
15330 		 * If rsvpd is running, let RSVP daemon handle its processing
15331 		 * and forwarding of RSVP multicast/unicast packets.
15332 		 * If rsvpd is not running but mrouted is running, RSVP
15333 		 * multicast packets are forwarded as multicast traffic
15334 		 * and RSVP unicast packets are forwarded by unicast router.
15335 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15336 		 * packets are not forwarded, but the unicast packets are
15337 		 * forwarded like unicast traffic.
15338 		 */
15339 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15340 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15341 		    NULL) {
15342 			/* RSVP packet and rsvpd running. Treat as ours */
15343 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15344 			/*
15345 			 * This assumes that we deliver to all streams for
15346 			 * multicast and broadcast packets.
15347 			 * We have to force ll_multicast to 1 to handle the
15348 			 * M_DATA messages passed in from ip_mroute_decap.
15349 			 */
15350 			dst = INADDR_BROADCAST;
15351 			ll_multicast = 1;
15352 		} else if (CLASSD(dst)) {
15353 			/* packet is multicast */
15354 			mp->b_next = NULL;
15355 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15356 			    &ll_multicast, &dst))
15357 				continue;
15358 		}
15359 
15360 		if (ire == NULL) {
15361 			ire = ire_cache_lookup(dst, ALL_ZONES,
15362 			    msg_getlabel(mp), ipst);
15363 		}
15364 
15365 		if (ire != NULL && ire->ire_stq != NULL &&
15366 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15367 		    ire->ire_zoneid != ALL_ZONES) {
15368 			/*
15369 			 * Should only use IREs that are visible from the
15370 			 * global zone for forwarding.
15371 			 */
15372 			ire_refrele(ire);
15373 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15374 			    msg_getlabel(mp), ipst);
15375 		}
15376 
15377 		if (ire == NULL) {
15378 			/*
15379 			 * No IRE for this destination, so it can't be for us.
15380 			 * Unless we are forwarding, drop the packet.
15381 			 * We have to let source routed packets through
15382 			 * since we don't yet know if they are 'ping -l'
15383 			 * packets i.e. if they will go out over the
15384 			 * same interface as they came in on.
15385 			 */
15386 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15387 			if (ire == NULL)
15388 				continue;
15389 		}
15390 
15391 		/*
15392 		 * Broadcast IRE may indicate either broadcast or
15393 		 * multicast packet
15394 		 */
15395 		if (ire->ire_type == IRE_BROADCAST) {
15396 			/*
15397 			 * Skip broadcast checks if packet is UDP multicast;
15398 			 * we'd rather not enter ip_rput_process_broadcast()
15399 			 * unless the packet is broadcast for real, since
15400 			 * that routine is a no-op for multicast.
15401 			 */
15402 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15403 			    !CLASSD(ipha->ipha_dst)) {
15404 				ire = ip_rput_process_broadcast(&q, mp,
15405 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15406 				    ll_multicast);
15407 				if (ire == NULL)
15408 					continue;
15409 			}
15410 		} else if (ire->ire_stq != NULL) {
15411 			/* fowarding? */
15412 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15413 			    ll_multicast, B_FALSE);
15414 			/* ip_rput_process_forward consumed the packet */
15415 			continue;
15416 		}
15417 
15418 local:
15419 		/*
15420 		 * If the queue in the ire is different to the ingress queue
15421 		 * then we need to check to see if we can accept the packet.
15422 		 * Note that for multicast packets and broadcast packets sent
15423 		 * to a broadcast address which is shared between multiple
15424 		 * interfaces we should not do this since we just got a random
15425 		 * broadcast ire.
15426 		 */
15427 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15428 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15429 			if (ire == NULL) {
15430 				/* Drop packet */
15431 				BUMP_MIB(ill->ill_ip_mib,
15432 				    ipIfStatsForwProhibits);
15433 				freemsg(mp);
15434 				continue;
15435 			}
15436 			if (ire->ire_rfq != NULL)
15437 				q = ire->ire_rfq;
15438 		}
15439 
15440 		switch (ipha->ipha_protocol) {
15441 		case IPPROTO_TCP:
15442 			ASSERT(first_mp == mp);
15443 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15444 			    mp, 0, q, ip_ring)) != NULL) {
15445 				if (curr_sqp == NULL) {
15446 					curr_sqp = GET_SQUEUE(mp);
15447 					ASSERT(cnt == 0);
15448 					cnt++;
15449 					head = tail = mp;
15450 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15451 					ASSERT(tail != NULL);
15452 					cnt++;
15453 					tail->b_next = mp;
15454 					tail = mp;
15455 				} else {
15456 					/*
15457 					 * A different squeue. Send the
15458 					 * chain for the previous squeue on
15459 					 * its way. This shouldn't happen
15460 					 * often unless interrupt binding
15461 					 * changes.
15462 					 */
15463 					IP_STAT(ipst, ip_input_multi_squeue);
15464 					SQUEUE_ENTER(curr_sqp, head,
15465 					    tail, cnt, SQ_PROCESS, tag);
15466 					curr_sqp = GET_SQUEUE(mp);
15467 					head = mp;
15468 					tail = mp;
15469 					cnt = 1;
15470 				}
15471 			}
15472 			continue;
15473 		case IPPROTO_UDP:
15474 			ASSERT(first_mp == mp);
15475 			ip_udp_input(q, mp, ipha, ire, ill);
15476 			continue;
15477 		case IPPROTO_SCTP:
15478 			ASSERT(first_mp == mp);
15479 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15480 			    q, dst);
15481 			/* ire has been released by ip_sctp_input */
15482 			ire = NULL;
15483 			continue;
15484 		default:
15485 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15486 			continue;
15487 		}
15488 	}
15489 
15490 	if (ire != NULL)
15491 		ire_refrele(ire);
15492 
15493 	if (head != NULL)
15494 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15495 
15496 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15497 	    "ip_input_end: q %p (%S)", q, "end");
15498 #undef  rptr
15499 }
15500 
15501 /*
15502  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15503  * a chain of packets in the poll mode. The packets have gone through the
15504  * data link processing but not IP processing. For performance and latency
15505  * reasons, the squeue wants to process the chain in line instead of feeding
15506  * it back via ip_input path.
15507  *
15508  * So this is a light weight function which checks to see if the packets
15509  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15510  * but we still do the paranoid check) meant for local machine and we don't
15511  * have labels etc enabled. Packets that meet the criterion are returned to
15512  * the squeue and processed inline while the rest go via ip_input path.
15513  */
15514 /*ARGSUSED*/
15515 mblk_t *
15516 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15517     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15518 {
15519 	mblk_t 		*mp;
15520 	ipaddr_t	dst = NULL;
15521 	ipaddr_t	prev_dst;
15522 	ire_t		*ire = NULL;
15523 	ipha_t		*ipha;
15524 	uint_t		pkt_len;
15525 	ssize_t		len;
15526 	uint_t		opt_len;
15527 	queue_t		*q = ill->ill_rq;
15528 	squeue_t	*curr_sqp;
15529 	mblk_t 		*ahead = NULL;	/* Accepted head */
15530 	mblk_t		*atail = NULL;	/* Accepted tail */
15531 	uint_t		acnt = 0;	/* Accepted count */
15532 	mblk_t		*utail = NULL;	/* Unaccepted head */
15533 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15534 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15535 	ip_stack_t	*ipst = ill->ill_ipst;
15536 
15537 	*cnt = 0;
15538 
15539 	ASSERT(ill != NULL);
15540 	ASSERT(ip_ring != NULL);
15541 
15542 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15543 
15544 #define	rptr	((uchar_t *)ipha)
15545 
15546 	while (mp_chain != NULL) {
15547 		mp = mp_chain;
15548 		mp_chain = mp_chain->b_next;
15549 		mp->b_next = NULL;
15550 
15551 		/*
15552 		 * We do ire caching from one iteration to
15553 		 * another. In the event the packet chain contains
15554 		 * all packets from the same dst, this caching saves
15555 		 * an ire_cache_lookup for each of the succeeding
15556 		 * packets in a packet chain.
15557 		 */
15558 		prev_dst = dst;
15559 
15560 		ipha = (ipha_t *)mp->b_rptr;
15561 		len = mp->b_wptr - rptr;
15562 
15563 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15564 
15565 		/*
15566 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15567 		 * or doesn't have min len, reject.
15568 		 */
15569 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15570 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15571 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15572 			continue;
15573 		}
15574 
15575 		pkt_len = ntohs(ipha->ipha_length);
15576 		if (len != pkt_len) {
15577 			if (len > pkt_len) {
15578 				mp->b_wptr = rptr + pkt_len;
15579 			} else {
15580 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15581 				continue;
15582 			}
15583 		}
15584 
15585 		opt_len = ipha->ipha_version_and_hdr_length -
15586 		    IP_SIMPLE_HDR_VERSION;
15587 		dst = ipha->ipha_dst;
15588 
15589 		/* IP version bad or there are IP options */
15590 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15591 		    mp, &ipha, &dst, ipst)))
15592 			continue;
15593 
15594 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15595 		    (ipst->ips_ip_cgtp_filter &&
15596 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15597 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15598 			continue;
15599 		}
15600 
15601 		/*
15602 		 * Reuse the cached ire only if the ipha_dst of the previous
15603 		 * packet is the same as the current packet AND it is not
15604 		 * INADDR_ANY.
15605 		 */
15606 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15607 		    (ire != NULL)) {
15608 			ire_refrele(ire);
15609 			ire = NULL;
15610 		}
15611 
15612 		if (ire == NULL)
15613 			ire = ire_cache_lookup_simple(dst, ipst);
15614 
15615 		/*
15616 		 * Unless forwarding is enabled, dont call
15617 		 * ip_fast_forward(). Incoming packet is for forwarding
15618 		 */
15619 		if ((ill->ill_flags & ILLF_ROUTER) &&
15620 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15621 
15622 			DTRACE_PROBE4(ip4__physical__in__start,
15623 			    ill_t *, ill, ill_t *, NULL,
15624 			    ipha_t *, ipha, mblk_t *, mp);
15625 
15626 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15627 			    ipst->ips_ipv4firewall_physical_in,
15628 			    ill, NULL, ipha, mp, mp, 0, ipst);
15629 
15630 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15631 
15632 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15633 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15634 			    pkt_len);
15635 
15636 			if (mp != NULL)
15637 				ire = ip_fast_forward(ire, dst, ill, mp);
15638 			continue;
15639 		}
15640 
15641 		/* incoming packet is for local consumption */
15642 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15643 			goto local_accept;
15644 
15645 		/*
15646 		 * Disable ire caching for anything more complex
15647 		 * than the simple fast path case we checked for above.
15648 		 */
15649 		if (ire != NULL) {
15650 			ire_refrele(ire);
15651 			ire = NULL;
15652 		}
15653 
15654 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15655 		    ipst);
15656 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15657 		    ire->ire_stq != NULL) {
15658 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15659 			if (ire != NULL) {
15660 				ire_refrele(ire);
15661 				ire = NULL;
15662 			}
15663 			continue;
15664 		}
15665 
15666 local_accept:
15667 
15668 		if (ire->ire_rfq != q) {
15669 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15670 			if (ire != NULL) {
15671 				ire_refrele(ire);
15672 				ire = NULL;
15673 			}
15674 			continue;
15675 		}
15676 
15677 		/*
15678 		 * The event for packets being received from a 'physical'
15679 		 * interface is placed after validation of the source and/or
15680 		 * destination address as being local so that packets can be
15681 		 * redirected to loopback addresses using ipnat.
15682 		 */
15683 		DTRACE_PROBE4(ip4__physical__in__start,
15684 		    ill_t *, ill, ill_t *, NULL,
15685 		    ipha_t *, ipha, mblk_t *, mp);
15686 
15687 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15688 		    ipst->ips_ipv4firewall_physical_in,
15689 		    ill, NULL, ipha, mp, mp, 0, ipst);
15690 
15691 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15692 
15693 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15694 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15695 
15696 		if (mp != NULL &&
15697 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15698 		    0, q, ip_ring)) != NULL) {
15699 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15700 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15701 			} else {
15702 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15703 				    SQ_FILL, SQTAG_IP_INPUT);
15704 			}
15705 		}
15706 	}
15707 
15708 	if (ire != NULL)
15709 		ire_refrele(ire);
15710 
15711 	if (uhead != NULL)
15712 		ip_input(ill, ip_ring, uhead, NULL);
15713 
15714 	if (ahead != NULL) {
15715 		*last = atail;
15716 		*cnt = acnt;
15717 		return (ahead);
15718 	}
15719 
15720 	return (NULL);
15721 #undef  rptr
15722 }
15723 
15724 static void
15725 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15726     t_uscalar_t err)
15727 {
15728 	if (dl_err == DL_SYSERR) {
15729 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15730 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15731 		    ill->ill_name, dl_primstr(prim), err);
15732 		return;
15733 	}
15734 
15735 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15736 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15737 	    dl_errstr(dl_err));
15738 }
15739 
15740 /*
15741  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15742  * than DL_UNITDATA_IND messages. If we need to process this message
15743  * exclusively, we call qwriter_ip, in which case we also need to call
15744  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15745  */
15746 void
15747 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15748 {
15749 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15750 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15751 	ill_t		*ill = q->q_ptr;
15752 	t_uscalar_t	prim = dloa->dl_primitive;
15753 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15754 
15755 	ip1dbg(("ip_rput_dlpi"));
15756 
15757 	/*
15758 	 * If we received an ACK but didn't send a request for it, then it
15759 	 * can't be part of any pending operation; discard up-front.
15760 	 */
15761 	switch (prim) {
15762 	case DL_ERROR_ACK:
15763 		reqprim = dlea->dl_error_primitive;
15764 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15765 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15766 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15767 		    dlea->dl_unix_errno));
15768 		break;
15769 	case DL_OK_ACK:
15770 		reqprim = dloa->dl_correct_primitive;
15771 		break;
15772 	case DL_INFO_ACK:
15773 		reqprim = DL_INFO_REQ;
15774 		break;
15775 	case DL_BIND_ACK:
15776 		reqprim = DL_BIND_REQ;
15777 		break;
15778 	case DL_PHYS_ADDR_ACK:
15779 		reqprim = DL_PHYS_ADDR_REQ;
15780 		break;
15781 	case DL_NOTIFY_ACK:
15782 		reqprim = DL_NOTIFY_REQ;
15783 		break;
15784 	case DL_CONTROL_ACK:
15785 		reqprim = DL_CONTROL_REQ;
15786 		break;
15787 	case DL_CAPABILITY_ACK:
15788 		reqprim = DL_CAPABILITY_REQ;
15789 		break;
15790 	}
15791 
15792 	if (prim != DL_NOTIFY_IND) {
15793 		if (reqprim == DL_PRIM_INVAL ||
15794 		    !ill_dlpi_pending(ill, reqprim)) {
15795 			/* Not a DLPI message we support or expected */
15796 			freemsg(mp);
15797 			return;
15798 		}
15799 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15800 		    dl_primstr(reqprim)));
15801 	}
15802 
15803 	switch (reqprim) {
15804 	case DL_UNBIND_REQ:
15805 		/*
15806 		 * NOTE: we mark the unbind as complete even if we got a
15807 		 * DL_ERROR_ACK, since there's not much else we can do.
15808 		 */
15809 		mutex_enter(&ill->ill_lock);
15810 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15811 		cv_signal(&ill->ill_cv);
15812 		mutex_exit(&ill->ill_lock);
15813 		break;
15814 
15815 	case DL_ENABMULTI_REQ:
15816 		if (prim == DL_OK_ACK) {
15817 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15818 				ill->ill_dlpi_multicast_state = IDS_OK;
15819 		}
15820 		break;
15821 	}
15822 
15823 	/*
15824 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15825 	 * need to become writer to continue to process it.  Because an
15826 	 * exclusive operation doesn't complete until replies to all queued
15827 	 * DLPI messages have been received, we know we're in the middle of an
15828 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15829 	 *
15830 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15831 	 * Since this is on the ill stream we unconditionally bump up the
15832 	 * refcount without doing ILL_CAN_LOOKUP().
15833 	 */
15834 	ill_refhold(ill);
15835 	if (prim == DL_NOTIFY_IND)
15836 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15837 	else
15838 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15839 }
15840 
15841 /*
15842  * Handling of DLPI messages that require exclusive access to the ipsq.
15843  *
15844  * Need to do ill_pending_mp_release on ioctl completion, which could
15845  * happen here. (along with mi_copy_done)
15846  */
15847 /* ARGSUSED */
15848 static void
15849 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15850 {
15851 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15852 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15853 	int		err = 0;
15854 	ill_t		*ill;
15855 	ipif_t		*ipif = NULL;
15856 	mblk_t		*mp1 = NULL;
15857 	conn_t		*connp = NULL;
15858 	t_uscalar_t	paddrreq;
15859 	mblk_t		*mp_hw;
15860 	boolean_t	success;
15861 	boolean_t	ioctl_aborted = B_FALSE;
15862 	boolean_t	log = B_TRUE;
15863 	ip_stack_t		*ipst;
15864 
15865 	ip1dbg(("ip_rput_dlpi_writer .."));
15866 	ill = (ill_t *)q->q_ptr;
15867 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15868 	ASSERT(IAM_WRITER_ILL(ill));
15869 
15870 	ipst = ill->ill_ipst;
15871 
15872 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15873 	/*
15874 	 * The current ioctl could have been aborted by the user and a new
15875 	 * ioctl to bring up another ill could have started. We could still
15876 	 * get a response from the driver later.
15877 	 */
15878 	if (ipif != NULL && ipif->ipif_ill != ill)
15879 		ioctl_aborted = B_TRUE;
15880 
15881 	switch (dloa->dl_primitive) {
15882 	case DL_ERROR_ACK:
15883 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15884 		    dl_primstr(dlea->dl_error_primitive)));
15885 
15886 		switch (dlea->dl_error_primitive) {
15887 		case DL_DISABMULTI_REQ:
15888 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15889 			break;
15890 		case DL_PROMISCON_REQ:
15891 		case DL_PROMISCOFF_REQ:
15892 		case DL_UNBIND_REQ:
15893 		case DL_ATTACH_REQ:
15894 		case DL_INFO_REQ:
15895 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15896 			break;
15897 		case DL_NOTIFY_REQ:
15898 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15899 			log = B_FALSE;
15900 			break;
15901 		case DL_PHYS_ADDR_REQ:
15902 			/*
15903 			 * For IPv6 only, there are two additional
15904 			 * phys_addr_req's sent to the driver to get the
15905 			 * IPv6 token and lla. This allows IP to acquire
15906 			 * the hardware address format for a given interface
15907 			 * without having built in knowledge of the hardware
15908 			 * address. ill_phys_addr_pend keeps track of the last
15909 			 * DL_PAR sent so we know which response we are
15910 			 * dealing with. ill_dlpi_done will update
15911 			 * ill_phys_addr_pend when it sends the next req.
15912 			 * We don't complete the IOCTL until all three DL_PARs
15913 			 * have been attempted, so set *_len to 0 and break.
15914 			 */
15915 			paddrreq = ill->ill_phys_addr_pend;
15916 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15917 			if (paddrreq == DL_IPV6_TOKEN) {
15918 				ill->ill_token_length = 0;
15919 				log = B_FALSE;
15920 				break;
15921 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15922 				ill->ill_nd_lla_len = 0;
15923 				log = B_FALSE;
15924 				break;
15925 			}
15926 			/*
15927 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15928 			 * We presumably have an IOCTL hanging out waiting
15929 			 * for completion. Find it and complete the IOCTL
15930 			 * with the error noted.
15931 			 * However, ill_dl_phys was called on an ill queue
15932 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15933 			 * set. But the ioctl is known to be pending on ill_wq.
15934 			 */
15935 			if (!ill->ill_ifname_pending)
15936 				break;
15937 			ill->ill_ifname_pending = 0;
15938 			if (!ioctl_aborted)
15939 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15940 			if (mp1 != NULL) {
15941 				/*
15942 				 * This operation (SIOCSLIFNAME) must have
15943 				 * happened on the ill. Assert there is no conn
15944 				 */
15945 				ASSERT(connp == NULL);
15946 				q = ill->ill_wq;
15947 			}
15948 			break;
15949 		case DL_BIND_REQ:
15950 			ill_dlpi_done(ill, DL_BIND_REQ);
15951 			if (ill->ill_ifname_pending)
15952 				break;
15953 			/*
15954 			 * Something went wrong with the bind.  We presumably
15955 			 * have an IOCTL hanging out waiting for completion.
15956 			 * Find it, take down the interface that was coming
15957 			 * up, and complete the IOCTL with the error noted.
15958 			 */
15959 			if (!ioctl_aborted)
15960 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15961 			if (mp1 != NULL) {
15962 				/*
15963 				 * This might be a result of a DL_NOTE_REPLUMB
15964 				 * notification. In that case, connp is NULL.
15965 				 */
15966 				if (connp != NULL)
15967 					q = CONNP_TO_WQ(connp);
15968 
15969 				(void) ipif_down(ipif, NULL, NULL);
15970 				/* error is set below the switch */
15971 			}
15972 			break;
15973 		case DL_ENABMULTI_REQ:
15974 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15975 
15976 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15977 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15978 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15979 				ipif_t *ipif;
15980 
15981 				printf("ip: joining multicasts failed (%d)"
15982 				    " on %s - will use link layer "
15983 				    "broadcasts for multicast\n",
15984 				    dlea->dl_errno, ill->ill_name);
15985 
15986 				/*
15987 				 * Set up the multicast mapping alone.
15988 				 * writer, so ok to access ill->ill_ipif
15989 				 * without any lock.
15990 				 */
15991 				ipif = ill->ill_ipif;
15992 				mutex_enter(&ill->ill_phyint->phyint_lock);
15993 				ill->ill_phyint->phyint_flags |=
15994 				    PHYI_MULTI_BCAST;
15995 				mutex_exit(&ill->ill_phyint->phyint_lock);
15996 
15997 				if (!ill->ill_isv6) {
15998 					(void) ipif_arp_setup_multicast(ipif,
15999 					    NULL);
16000 				} else {
16001 					(void) ipif_ndp_setup_multicast(ipif,
16002 					    NULL);
16003 				}
16004 			}
16005 			freemsg(mp);	/* Don't want to pass this up */
16006 			return;
16007 		case DL_CONTROL_REQ:
16008 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16009 			    "DL_CONTROL_REQ\n"));
16010 			ill_dlpi_done(ill, dlea->dl_error_primitive);
16011 			freemsg(mp);
16012 			return;
16013 		case DL_CAPABILITY_REQ:
16014 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16015 			    "DL_CAPABILITY REQ\n"));
16016 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
16017 				ill->ill_dlpi_capab_state = IDCS_FAILED;
16018 			ill_capability_done(ill);
16019 			freemsg(mp);
16020 			return;
16021 		}
16022 		/*
16023 		 * Note the error for IOCTL completion (mp1 is set when
16024 		 * ready to complete ioctl). If ill_ifname_pending_err is
16025 		 * set, an error occured during plumbing (ill_ifname_pending),
16026 		 * so we want to report that error.
16027 		 *
16028 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
16029 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
16030 		 * expected to get errack'd if the driver doesn't support
16031 		 * these flags (e.g. ethernet). log will be set to B_FALSE
16032 		 * if these error conditions are encountered.
16033 		 */
16034 		if (mp1 != NULL) {
16035 			if (ill->ill_ifname_pending_err != 0)  {
16036 				err = ill->ill_ifname_pending_err;
16037 				ill->ill_ifname_pending_err = 0;
16038 			} else {
16039 				err = dlea->dl_unix_errno ?
16040 				    dlea->dl_unix_errno : ENXIO;
16041 			}
16042 		/*
16043 		 * If we're plumbing an interface and an error hasn't already
16044 		 * been saved, set ill_ifname_pending_err to the error passed
16045 		 * up. Ignore the error if log is B_FALSE (see comment above).
16046 		 */
16047 		} else if (log && ill->ill_ifname_pending &&
16048 		    ill->ill_ifname_pending_err == 0) {
16049 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
16050 			    dlea->dl_unix_errno : ENXIO;
16051 		}
16052 
16053 		if (log)
16054 			ip_dlpi_error(ill, dlea->dl_error_primitive,
16055 			    dlea->dl_errno, dlea->dl_unix_errno);
16056 		break;
16057 	case DL_CAPABILITY_ACK:
16058 		ill_capability_ack(ill, mp);
16059 		/*
16060 		 * The message has been handed off to ill_capability_ack
16061 		 * and must not be freed below
16062 		 */
16063 		mp = NULL;
16064 		break;
16065 
16066 	case DL_CONTROL_ACK:
16067 		/* We treat all of these as "fire and forget" */
16068 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16069 		break;
16070 	case DL_INFO_ACK:
16071 		/* Call a routine to handle this one. */
16072 		ill_dlpi_done(ill, DL_INFO_REQ);
16073 		ip_ll_subnet_defaults(ill, mp);
16074 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16075 		return;
16076 	case DL_BIND_ACK:
16077 		/*
16078 		 * We should have an IOCTL waiting on this unless
16079 		 * sent by ill_dl_phys, in which case just return
16080 		 */
16081 		ill_dlpi_done(ill, DL_BIND_REQ);
16082 		if (ill->ill_ifname_pending)
16083 			break;
16084 
16085 		if (!ioctl_aborted)
16086 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16087 		if (mp1 == NULL)
16088 			break;
16089 		/*
16090 		 * mp1 was added by ill_dl_up(). if that is a result of
16091 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16092 		 */
16093 		if (connp != NULL)
16094 			q = CONNP_TO_WQ(connp);
16095 
16096 		/*
16097 		 * We are exclusive. So nothing can change even after
16098 		 * we get the pending mp. If need be we can put it back
16099 		 * and restart, as in calling ipif_arp_up()  below.
16100 		 */
16101 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16102 
16103 		mutex_enter(&ill->ill_lock);
16104 		ill->ill_dl_up = 1;
16105 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16106 		mutex_exit(&ill->ill_lock);
16107 
16108 		/*
16109 		 * Now bring up the resolver; when that is complete, we'll
16110 		 * create IREs.  Note that we intentionally mirror what
16111 		 * ipif_up() would have done, because we got here by way of
16112 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16113 		 */
16114 		if (ill->ill_isv6) {
16115 			if (ill->ill_flags & ILLF_XRESOLV) {
16116 				if (connp != NULL)
16117 					mutex_enter(&connp->conn_lock);
16118 				mutex_enter(&ill->ill_lock);
16119 				success = ipsq_pending_mp_add(connp, ipif, q,
16120 				    mp1, 0);
16121 				mutex_exit(&ill->ill_lock);
16122 				if (connp != NULL)
16123 					mutex_exit(&connp->conn_lock);
16124 				if (success) {
16125 					err = ipif_resolver_up(ipif,
16126 					    Res_act_initial);
16127 					if (err == EINPROGRESS) {
16128 						freemsg(mp);
16129 						return;
16130 					}
16131 					ASSERT(err != 0);
16132 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16133 					ASSERT(mp1 != NULL);
16134 				} else {
16135 					/* conn has started closing */
16136 					err = EINTR;
16137 				}
16138 			} else { /* Non XRESOLV interface */
16139 				(void) ipif_resolver_up(ipif, Res_act_initial);
16140 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16141 					err = ipif_up_done_v6(ipif);
16142 			}
16143 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16144 			/*
16145 			 * ARP and other v4 external resolvers.
16146 			 * Leave the pending mblk intact so that
16147 			 * the ioctl completes in ip_rput().
16148 			 */
16149 			if (connp != NULL)
16150 				mutex_enter(&connp->conn_lock);
16151 			mutex_enter(&ill->ill_lock);
16152 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16153 			mutex_exit(&ill->ill_lock);
16154 			if (connp != NULL)
16155 				mutex_exit(&connp->conn_lock);
16156 			if (success) {
16157 				err = ipif_resolver_up(ipif, Res_act_initial);
16158 				if (err == EINPROGRESS) {
16159 					freemsg(mp);
16160 					return;
16161 				}
16162 				ASSERT(err != 0);
16163 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16164 			} else {
16165 				/* The conn has started closing */
16166 				err = EINTR;
16167 			}
16168 		} else {
16169 			/*
16170 			 * This one is complete. Reply to pending ioctl.
16171 			 */
16172 			(void) ipif_resolver_up(ipif, Res_act_initial);
16173 			err = ipif_up_done(ipif);
16174 		}
16175 
16176 		if ((err == 0) && (ill->ill_up_ipifs)) {
16177 			err = ill_up_ipifs(ill, q, mp1);
16178 			if (err == EINPROGRESS) {
16179 				freemsg(mp);
16180 				return;
16181 			}
16182 		}
16183 
16184 		/*
16185 		 * If we have a moved ipif to bring up, and everything has
16186 		 * succeeded to this point, bring it up on the IPMP ill.
16187 		 * Otherwise, leave it down -- the admin can try to bring it
16188 		 * up by hand if need be.
16189 		 */
16190 		if (ill->ill_move_ipif != NULL) {
16191 			if (err != 0) {
16192 				ill->ill_move_ipif = NULL;
16193 			} else {
16194 				ipif = ill->ill_move_ipif;
16195 				ill->ill_move_ipif = NULL;
16196 				err = ipif_up(ipif, q, mp1);
16197 				if (err == EINPROGRESS) {
16198 					freemsg(mp);
16199 					return;
16200 				}
16201 			}
16202 		}
16203 		break;
16204 
16205 	case DL_NOTIFY_IND: {
16206 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16207 		ire_t *ire;
16208 		uint_t orig_mtu;
16209 		boolean_t need_ire_walk_v4 = B_FALSE;
16210 		boolean_t need_ire_walk_v6 = B_FALSE;
16211 
16212 		switch (notify->dl_notification) {
16213 		case DL_NOTE_PHYS_ADDR:
16214 			err = ill_set_phys_addr(ill, mp);
16215 			break;
16216 
16217 		case DL_NOTE_REPLUMB:
16218 			/*
16219 			 * Directly return after calling ill_replumb().
16220 			 * Note that we should not free mp as it is reused
16221 			 * in the ill_replumb() function.
16222 			 */
16223 			err = ill_replumb(ill, mp);
16224 			return;
16225 
16226 		case DL_NOTE_FASTPATH_FLUSH:
16227 			ill_fastpath_flush(ill);
16228 			break;
16229 
16230 		case DL_NOTE_SDU_SIZE:
16231 			/*
16232 			 * Change the MTU size of the interface, of all
16233 			 * attached ipif's, and of all relevant ire's.  The
16234 			 * new value's a uint32_t at notify->dl_data.
16235 			 * Mtu change Vs. new ire creation - protocol below.
16236 			 *
16237 			 * a Mark the ipif as IPIF_CHANGING.
16238 			 * b Set the new mtu in the ipif.
16239 			 * c Change the ire_max_frag on all affected ires
16240 			 * d Unmark the IPIF_CHANGING
16241 			 *
16242 			 * To see how the protocol works, assume an interface
16243 			 * route is also being added simultaneously by
16244 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16245 			 * the ire. If the ire is created before step a,
16246 			 * it will be cleaned up by step c. If the ire is
16247 			 * created after step d, it will see the new value of
16248 			 * ipif_mtu. Any attempt to create the ire between
16249 			 * steps a to d will fail because of the IPIF_CHANGING
16250 			 * flag. Note that ire_create() is passed a pointer to
16251 			 * the ipif_mtu, and not the value. During ire_add
16252 			 * under the bucket lock, the ire_max_frag of the
16253 			 * new ire being created is set from the ipif/ire from
16254 			 * which it is being derived.
16255 			 */
16256 			mutex_enter(&ill->ill_lock);
16257 
16258 			orig_mtu = ill->ill_max_mtu;
16259 			ill->ill_max_frag = (uint_t)notify->dl_data;
16260 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16261 
16262 			/*
16263 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16264 			 * clamp ill_max_mtu at it.
16265 			 */
16266 			if (ill->ill_user_mtu != 0 &&
16267 			    ill->ill_user_mtu < ill->ill_max_mtu)
16268 				ill->ill_max_mtu = ill->ill_user_mtu;
16269 
16270 			/*
16271 			 * If the MTU is unchanged, we're done.
16272 			 */
16273 			if (orig_mtu == ill->ill_max_mtu) {
16274 				mutex_exit(&ill->ill_lock);
16275 				break;
16276 			}
16277 
16278 			if (ill->ill_isv6) {
16279 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16280 					ill->ill_max_mtu = IPV6_MIN_MTU;
16281 			} else {
16282 				if (ill->ill_max_mtu < IP_MIN_MTU)
16283 					ill->ill_max_mtu = IP_MIN_MTU;
16284 			}
16285 			for (ipif = ill->ill_ipif; ipif != NULL;
16286 			    ipif = ipif->ipif_next) {
16287 				/*
16288 				 * Don't override the mtu if the user
16289 				 * has explicitly set it.
16290 				 */
16291 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16292 					continue;
16293 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16294 				if (ipif->ipif_isv6)
16295 					ire = ipif_to_ire_v6(ipif);
16296 				else
16297 					ire = ipif_to_ire(ipif);
16298 				if (ire != NULL) {
16299 					ire->ire_max_frag = ipif->ipif_mtu;
16300 					ire_refrele(ire);
16301 				}
16302 				if (ipif->ipif_flags & IPIF_UP) {
16303 					if (ill->ill_isv6)
16304 						need_ire_walk_v6 = B_TRUE;
16305 					else
16306 						need_ire_walk_v4 = B_TRUE;
16307 				}
16308 			}
16309 			mutex_exit(&ill->ill_lock);
16310 			if (need_ire_walk_v4)
16311 				ire_walk_v4(ill_mtu_change, (char *)ill,
16312 				    ALL_ZONES, ipst);
16313 			if (need_ire_walk_v6)
16314 				ire_walk_v6(ill_mtu_change, (char *)ill,
16315 				    ALL_ZONES, ipst);
16316 
16317 			/*
16318 			 * Refresh IPMP meta-interface MTU if necessary.
16319 			 */
16320 			if (IS_UNDER_IPMP(ill))
16321 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16322 			break;
16323 
16324 		case DL_NOTE_LINK_UP:
16325 		case DL_NOTE_LINK_DOWN: {
16326 			/*
16327 			 * We are writer. ill / phyint / ipsq assocs stable.
16328 			 * The RUNNING flag reflects the state of the link.
16329 			 */
16330 			phyint_t *phyint = ill->ill_phyint;
16331 			uint64_t new_phyint_flags;
16332 			boolean_t changed = B_FALSE;
16333 			boolean_t went_up;
16334 
16335 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16336 			mutex_enter(&phyint->phyint_lock);
16337 
16338 			new_phyint_flags = went_up ?
16339 			    phyint->phyint_flags | PHYI_RUNNING :
16340 			    phyint->phyint_flags & ~PHYI_RUNNING;
16341 
16342 			if (IS_IPMP(ill)) {
16343 				new_phyint_flags = went_up ?
16344 				    new_phyint_flags & ~PHYI_FAILED :
16345 				    new_phyint_flags | PHYI_FAILED;
16346 			}
16347 
16348 			if (new_phyint_flags != phyint->phyint_flags) {
16349 				phyint->phyint_flags = new_phyint_flags;
16350 				changed = B_TRUE;
16351 			}
16352 			mutex_exit(&phyint->phyint_lock);
16353 			/*
16354 			 * ill_restart_dad handles the DAD restart and routing
16355 			 * socket notification logic.
16356 			 */
16357 			if (changed) {
16358 				ill_restart_dad(phyint->phyint_illv4, went_up);
16359 				ill_restart_dad(phyint->phyint_illv6, went_up);
16360 			}
16361 			break;
16362 		}
16363 		case DL_NOTE_PROMISC_ON_PHYS: {
16364 			phyint_t *phyint = ill->ill_phyint;
16365 
16366 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16367 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16368 			mutex_enter(&phyint->phyint_lock);
16369 			phyint->phyint_flags |= PHYI_PROMISC;
16370 			mutex_exit(&phyint->phyint_lock);
16371 			break;
16372 		}
16373 		case DL_NOTE_PROMISC_OFF_PHYS: {
16374 			phyint_t *phyint = ill->ill_phyint;
16375 
16376 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16377 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16378 			mutex_enter(&phyint->phyint_lock);
16379 			phyint->phyint_flags &= ~PHYI_PROMISC;
16380 			mutex_exit(&phyint->phyint_lock);
16381 			break;
16382 		}
16383 		case DL_NOTE_CAPAB_RENEG:
16384 			/*
16385 			 * Something changed on the driver side.
16386 			 * It wants us to renegotiate the capabilities
16387 			 * on this ill. One possible cause is the aggregation
16388 			 * interface under us where a port got added or
16389 			 * went away.
16390 			 *
16391 			 * If the capability negotiation is already done
16392 			 * or is in progress, reset the capabilities and
16393 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16394 			 * so that when the ack comes back, we can start
16395 			 * the renegotiation process.
16396 			 *
16397 			 * Note that if ill_capab_reneg is already B_TRUE
16398 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16399 			 * the capability resetting request has been sent
16400 			 * and the renegotiation has not been started yet;
16401 			 * nothing needs to be done in this case.
16402 			 */
16403 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16404 			ill_capability_reset(ill, B_TRUE);
16405 			ipsq_current_finish(ipsq);
16406 			break;
16407 		default:
16408 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16409 			    "type 0x%x for DL_NOTIFY_IND\n",
16410 			    notify->dl_notification));
16411 			break;
16412 		}
16413 
16414 		/*
16415 		 * As this is an asynchronous operation, we
16416 		 * should not call ill_dlpi_done
16417 		 */
16418 		break;
16419 	}
16420 	case DL_NOTIFY_ACK: {
16421 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16422 
16423 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16424 			ill->ill_note_link = 1;
16425 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16426 		break;
16427 	}
16428 	case DL_PHYS_ADDR_ACK: {
16429 		/*
16430 		 * As part of plumbing the interface via SIOCSLIFNAME,
16431 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16432 		 * whose answers we receive here.  As each answer is received,
16433 		 * we call ill_dlpi_done() to dispatch the next request as
16434 		 * we're processing the current one.  Once all answers have
16435 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16436 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16437 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16438 		 * available, but we know the ioctl is pending on ill_wq.)
16439 		 */
16440 		uint_t	paddrlen, paddroff;
16441 
16442 		paddrreq = ill->ill_phys_addr_pend;
16443 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16444 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16445 
16446 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16447 		if (paddrreq == DL_IPV6_TOKEN) {
16448 			/*
16449 			 * bcopy to low-order bits of ill_token
16450 			 *
16451 			 * XXX Temporary hack - currently, all known tokens
16452 			 * are 64 bits, so I'll cheat for the moment.
16453 			 */
16454 			bcopy(mp->b_rptr + paddroff,
16455 			    &ill->ill_token.s6_addr32[2], paddrlen);
16456 			ill->ill_token_length = paddrlen;
16457 			break;
16458 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16459 			ASSERT(ill->ill_nd_lla_mp == NULL);
16460 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16461 			mp = NULL;
16462 			break;
16463 		}
16464 
16465 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16466 		ASSERT(ill->ill_phys_addr_mp == NULL);
16467 		if (!ill->ill_ifname_pending)
16468 			break;
16469 		ill->ill_ifname_pending = 0;
16470 		if (!ioctl_aborted)
16471 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16472 		if (mp1 != NULL) {
16473 			ASSERT(connp == NULL);
16474 			q = ill->ill_wq;
16475 		}
16476 		/*
16477 		 * If any error acks received during the plumbing sequence,
16478 		 * ill_ifname_pending_err will be set. Break out and send up
16479 		 * the error to the pending ioctl.
16480 		 */
16481 		if (ill->ill_ifname_pending_err != 0) {
16482 			err = ill->ill_ifname_pending_err;
16483 			ill->ill_ifname_pending_err = 0;
16484 			break;
16485 		}
16486 
16487 		ill->ill_phys_addr_mp = mp;
16488 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16489 		mp = NULL;
16490 
16491 		/*
16492 		 * If paddrlen is zero, the DLPI provider doesn't support
16493 		 * physical addresses.  The other two tests were historical
16494 		 * workarounds for bugs in our former PPP implementation, but
16495 		 * now other things have grown dependencies on them -- e.g.,
16496 		 * the tun module specifies a dl_addr_length of zero in its
16497 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16498 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16499 		 * but only after careful testing ensures that all dependent
16500 		 * broken DLPI providers have been fixed.
16501 		 */
16502 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16503 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16504 			ill->ill_phys_addr = NULL;
16505 		} else if (paddrlen != ill->ill_phys_addr_length) {
16506 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16507 			    paddrlen, ill->ill_phys_addr_length));
16508 			err = EINVAL;
16509 			break;
16510 		}
16511 
16512 		if (ill->ill_nd_lla_mp == NULL) {
16513 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16514 				err = ENOMEM;
16515 				break;
16516 			}
16517 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16518 		}
16519 
16520 		/*
16521 		 * Set the interface token.  If the zeroth interface address
16522 		 * is unspecified, then set it to the link local address.
16523 		 */
16524 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16525 			(void) ill_setdefaulttoken(ill);
16526 
16527 		ASSERT(ill->ill_ipif->ipif_id == 0);
16528 		if (ipif != NULL &&
16529 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16530 			(void) ipif_setlinklocal(ipif);
16531 		}
16532 		break;
16533 	}
16534 	case DL_OK_ACK:
16535 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16536 		    dl_primstr((int)dloa->dl_correct_primitive),
16537 		    dloa->dl_correct_primitive));
16538 		switch (dloa->dl_correct_primitive) {
16539 		case DL_ENABMULTI_REQ:
16540 		case DL_DISABMULTI_REQ:
16541 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16542 			break;
16543 		case DL_PROMISCON_REQ:
16544 		case DL_PROMISCOFF_REQ:
16545 		case DL_UNBIND_REQ:
16546 		case DL_ATTACH_REQ:
16547 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16548 			break;
16549 		}
16550 		break;
16551 	default:
16552 		break;
16553 	}
16554 
16555 	freemsg(mp);
16556 	if (mp1 == NULL)
16557 		return;
16558 
16559 	/*
16560 	 * The operation must complete without EINPROGRESS since
16561 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16562 	 * the operation will be stuck forever inside the IPSQ.
16563 	 */
16564 	ASSERT(err != EINPROGRESS);
16565 
16566 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16567 	case 0:
16568 		ipsq_current_finish(ipsq);
16569 		break;
16570 
16571 	case SIOCSLIFNAME:
16572 	case IF_UNITSEL: {
16573 		ill_t *ill_other = ILL_OTHER(ill);
16574 
16575 		/*
16576 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16577 		 * ill has a peer which is in an IPMP group, then place ill
16578 		 * into the same group.  One catch: although ifconfig plumbs
16579 		 * the appropriate IPMP meta-interface prior to plumbing this
16580 		 * ill, it is possible for multiple ifconfig applications to
16581 		 * race (or for another application to adjust plumbing), in
16582 		 * which case the IPMP meta-interface we need will be missing.
16583 		 * If so, kick the phyint out of the group.
16584 		 */
16585 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16586 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16587 			ipmp_illgrp_t	*illg;
16588 
16589 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16590 			if (illg == NULL)
16591 				ipmp_phyint_leave_grp(ill->ill_phyint);
16592 			else
16593 				ipmp_ill_join_illgrp(ill, illg);
16594 		}
16595 
16596 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16597 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16598 		else
16599 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16600 		break;
16601 	}
16602 	case SIOCLIFADDIF:
16603 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16604 		break;
16605 
16606 	default:
16607 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16608 		break;
16609 	}
16610 }
16611 
16612 /*
16613  * ip_rput_other is called by ip_rput to handle messages modifying the global
16614  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16615  */
16616 /* ARGSUSED */
16617 void
16618 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16619 {
16620 	ill_t		*ill = q->q_ptr;
16621 	struct iocblk	*iocp;
16622 	mblk_t		*mp1;
16623 	conn_t		*connp = NULL;
16624 
16625 	ip1dbg(("ip_rput_other "));
16626 	if (ipsq != NULL) {
16627 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16628 		ASSERT(ipsq->ipsq_xop ==
16629 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16630 	}
16631 
16632 	switch (mp->b_datap->db_type) {
16633 	case M_ERROR:
16634 	case M_HANGUP:
16635 		/*
16636 		 * The device has a problem.  We force the ILL down.  It can
16637 		 * be brought up again manually using SIOCSIFFLAGS (via
16638 		 * ifconfig or equivalent).
16639 		 */
16640 		ASSERT(ipsq != NULL);
16641 		if (mp->b_rptr < mp->b_wptr)
16642 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16643 		if (ill->ill_error == 0)
16644 			ill->ill_error = ENXIO;
16645 		if (!ill_down_start(q, mp))
16646 			return;
16647 		ipif_all_down_tail(ipsq, q, mp, NULL);
16648 		break;
16649 	case M_IOCACK:
16650 		iocp = (struct iocblk *)mp->b_rptr;
16651 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16652 		switch (iocp->ioc_cmd) {
16653 		case SIOCSTUNPARAM:
16654 		case OSIOCSTUNPARAM:
16655 			ASSERT(ipsq != NULL);
16656 			/*
16657 			 * Finish socket ioctl passed through to tun.
16658 			 * We should have an IOCTL waiting on this.
16659 			 */
16660 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16661 			if (ill->ill_isv6) {
16662 				struct iftun_req *ta;
16663 
16664 				/*
16665 				 * if a source or destination is
16666 				 * being set, try and set the link
16667 				 * local address for the tunnel
16668 				 */
16669 				ta = (struct iftun_req *)mp->b_cont->
16670 				    b_cont->b_rptr;
16671 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16672 					ipif_set_tun_llink(ill, ta);
16673 				}
16674 
16675 			}
16676 			if (mp1 != NULL) {
16677 				/*
16678 				 * Now copy back the b_next/b_prev used by
16679 				 * mi code for the mi_copy* functions.
16680 				 * See ip_sioctl_tunparam() for the reason.
16681 				 * Also protect against missing b_cont.
16682 				 */
16683 				if (mp->b_cont != NULL) {
16684 					mp->b_cont->b_next =
16685 					    mp1->b_cont->b_next;
16686 					mp->b_cont->b_prev =
16687 					    mp1->b_cont->b_prev;
16688 				}
16689 				inet_freemsg(mp1);
16690 				ASSERT(connp != NULL);
16691 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16692 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16693 			} else {
16694 				ASSERT(connp == NULL);
16695 				putnext(q, mp);
16696 			}
16697 			break;
16698 		case SIOCGTUNPARAM:
16699 		case OSIOCGTUNPARAM:
16700 			/*
16701 			 * This is really M_IOCDATA from the tunnel driver.
16702 			 * convert back and complete the ioctl.
16703 			 * We should have an IOCTL waiting on this.
16704 			 */
16705 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16706 			if (mp1) {
16707 				/*
16708 				 * Now copy back the b_next/b_prev used by
16709 				 * mi code for the mi_copy* functions.
16710 				 * See ip_sioctl_tunparam() for the reason.
16711 				 * Also protect against missing b_cont.
16712 				 */
16713 				if (mp->b_cont != NULL) {
16714 					mp->b_cont->b_next =
16715 					    mp1->b_cont->b_next;
16716 					mp->b_cont->b_prev =
16717 					    mp1->b_cont->b_prev;
16718 				}
16719 				inet_freemsg(mp1);
16720 				if (iocp->ioc_error == 0)
16721 					mp->b_datap->db_type = M_IOCDATA;
16722 				ASSERT(connp != NULL);
16723 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16724 				    iocp->ioc_error, COPYOUT, NULL);
16725 			} else {
16726 				ASSERT(connp == NULL);
16727 				putnext(q, mp);
16728 			}
16729 			break;
16730 		default:
16731 			break;
16732 		}
16733 		break;
16734 	case M_IOCNAK:
16735 		iocp = (struct iocblk *)mp->b_rptr;
16736 
16737 		switch (iocp->ioc_cmd) {
16738 			int mode;
16739 
16740 		case DL_IOC_HDR_INFO:
16741 			/*
16742 			 * If this was the first attempt, turn off the
16743 			 * fastpath probing.
16744 			 */
16745 			mutex_enter(&ill->ill_lock);
16746 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16747 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16748 				mutex_exit(&ill->ill_lock);
16749 				ill_fastpath_nack(ill);
16750 				ip1dbg(("ip_rput: DLPI fastpath off on "
16751 				    "interface %s\n",
16752 				    ill->ill_name));
16753 			} else {
16754 				mutex_exit(&ill->ill_lock);
16755 			}
16756 			freemsg(mp);
16757 			break;
16758 			case SIOCSTUNPARAM:
16759 		case OSIOCSTUNPARAM:
16760 			ASSERT(ipsq != NULL);
16761 			/*
16762 			 * Finish socket ioctl passed through to tun
16763 			 * We should have an IOCTL waiting on this.
16764 			 */
16765 			/* FALLTHRU */
16766 		case SIOCGTUNPARAM:
16767 		case OSIOCGTUNPARAM:
16768 			/*
16769 			 * This is really M_IOCDATA from the tunnel driver.
16770 			 * convert back and complete the ioctl.
16771 			 * We should have an IOCTL waiting on this.
16772 			 */
16773 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16774 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16775 				mp1 = ill_pending_mp_get(ill, &connp,
16776 				    iocp->ioc_id);
16777 				mode = COPYOUT;
16778 				ipsq = NULL;
16779 			} else {
16780 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16781 				mode = NO_COPYOUT;
16782 			}
16783 			if (mp1 != NULL) {
16784 				/*
16785 				 * Now copy back the b_next/b_prev used by
16786 				 * mi code for the mi_copy* functions.
16787 				 * See ip_sioctl_tunparam() for the reason.
16788 				 * Also protect against missing b_cont.
16789 				 */
16790 				if (mp->b_cont != NULL) {
16791 					mp->b_cont->b_next =
16792 					    mp1->b_cont->b_next;
16793 					mp->b_cont->b_prev =
16794 					    mp1->b_cont->b_prev;
16795 				}
16796 				inet_freemsg(mp1);
16797 				if (iocp->ioc_error == 0)
16798 					iocp->ioc_error = EINVAL;
16799 				ASSERT(connp != NULL);
16800 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16801 				    iocp->ioc_error, mode, ipsq);
16802 			} else {
16803 				ASSERT(connp == NULL);
16804 				putnext(q, mp);
16805 			}
16806 			break;
16807 		default:
16808 			break;
16809 		}
16810 	default:
16811 		break;
16812 	}
16813 }
16814 
16815 /*
16816  * NOTE : This function does not ire_refrele the ire argument passed in.
16817  *
16818  * IPQoS notes
16819  * IP policy is invoked twice for a forwarded packet, once on the read side
16820  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16821  * enabled. An additional parameter, in_ill, has been added for this purpose.
16822  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16823  * because ip_mroute drops this information.
16824  *
16825  */
16826 void
16827 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16828 {
16829 	uint32_t	old_pkt_len;
16830 	uint32_t	pkt_len;
16831 	queue_t	*q;
16832 	uint32_t	sum;
16833 #define	rptr	((uchar_t *)ipha)
16834 	uint32_t	max_frag;
16835 	uint32_t	ill_index;
16836 	ill_t		*out_ill;
16837 	mib2_ipIfStatsEntry_t *mibptr;
16838 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16839 
16840 	/* Get the ill_index of the incoming ILL */
16841 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16842 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16843 
16844 	/* Initiate Read side IPPF processing */
16845 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16846 		ip_process(IPP_FWD_IN, &mp, ill_index);
16847 		if (mp == NULL) {
16848 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16849 			    "during IPPF processing\n"));
16850 			return;
16851 		}
16852 	}
16853 
16854 	/* Adjust the checksum to reflect the ttl decrement. */
16855 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16856 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16857 
16858 	if (ipha->ipha_ttl-- <= 1) {
16859 		if (ip_csum_hdr(ipha)) {
16860 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16861 			goto drop_pkt;
16862 		}
16863 		/*
16864 		 * Note: ire_stq this will be NULL for multicast
16865 		 * datagrams using the long path through arp (the IRE
16866 		 * is not an IRE_CACHE). This should not cause
16867 		 * problems since we don't generate ICMP errors for
16868 		 * multicast packets.
16869 		 */
16870 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16871 		q = ire->ire_stq;
16872 		if (q != NULL) {
16873 			/* Sent by forwarding path, and router is global zone */
16874 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16875 			    GLOBAL_ZONEID, ipst);
16876 		} else
16877 			freemsg(mp);
16878 		return;
16879 	}
16880 
16881 	/*
16882 	 * Don't forward if the interface is down
16883 	 */
16884 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16885 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16886 		ip2dbg(("ip_rput_forward:interface is down\n"));
16887 		goto drop_pkt;
16888 	}
16889 
16890 	/* Get the ill_index of the outgoing ILL */
16891 	out_ill = ire_to_ill(ire);
16892 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16893 
16894 	DTRACE_PROBE4(ip4__forwarding__start,
16895 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16896 
16897 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16898 	    ipst->ips_ipv4firewall_forwarding,
16899 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16900 
16901 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16902 
16903 	if (mp == NULL)
16904 		return;
16905 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16906 
16907 	if (is_system_labeled()) {
16908 		mblk_t *mp1;
16909 
16910 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16911 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16912 			goto drop_pkt;
16913 		}
16914 		/* Size may have changed */
16915 		mp = mp1;
16916 		ipha = (ipha_t *)mp->b_rptr;
16917 		pkt_len = ntohs(ipha->ipha_length);
16918 	}
16919 
16920 	/* Check if there are options to update */
16921 	if (!IS_SIMPLE_IPH(ipha)) {
16922 		if (ip_csum_hdr(ipha)) {
16923 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16924 			goto drop_pkt;
16925 		}
16926 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16927 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16928 			return;
16929 		}
16930 
16931 		ipha->ipha_hdr_checksum = 0;
16932 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16933 	}
16934 	max_frag = ire->ire_max_frag;
16935 	if (pkt_len > max_frag) {
16936 		/*
16937 		 * It needs fragging on its way out.  We haven't
16938 		 * verified the header checksum yet.  Since we
16939 		 * are going to put a surely good checksum in the
16940 		 * outgoing header, we have to make sure that it
16941 		 * was good coming in.
16942 		 */
16943 		if (ip_csum_hdr(ipha)) {
16944 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16945 			goto drop_pkt;
16946 		}
16947 		/* Initiate Write side IPPF processing */
16948 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16949 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16950 			if (mp == NULL) {
16951 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16952 				    " during IPPF processing\n"));
16953 				return;
16954 			}
16955 		}
16956 		/*
16957 		 * Handle labeled packet resizing.
16958 		 *
16959 		 * If we have added a label, inform ip_wput_frag() of its
16960 		 * effect on the MTU for ICMP messages.
16961 		 */
16962 		if (pkt_len > old_pkt_len) {
16963 			uint32_t secopt_size;
16964 
16965 			secopt_size = pkt_len - old_pkt_len;
16966 			if (secopt_size < max_frag)
16967 				max_frag -= secopt_size;
16968 		}
16969 
16970 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16971 		    GLOBAL_ZONEID, ipst, NULL);
16972 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16973 		return;
16974 	}
16975 
16976 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16977 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16978 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16979 	    ipst->ips_ipv4firewall_physical_out,
16980 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16981 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16982 	if (mp == NULL)
16983 		return;
16984 
16985 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16986 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16987 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16988 	/* ip_xmit_v4 always consumes the packet */
16989 	return;
16990 
16991 drop_pkt:;
16992 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16993 	freemsg(mp);
16994 #undef	rptr
16995 }
16996 
16997 void
16998 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16999 {
17000 	ire_t	*ire;
17001 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
17002 
17003 	ASSERT(!ipif->ipif_isv6);
17004 	/*
17005 	 * Find an IRE which matches the destination and the outgoing
17006 	 * queue in the cache table. All we need is an IRE_CACHE which
17007 	 * is pointing at ipif->ipif_ill.
17008 	 */
17009 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
17010 		dst = ipif->ipif_pp_dst_addr;
17011 
17012 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
17013 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
17014 	if (ire == NULL) {
17015 		/*
17016 		 * Mark this packet to make it be delivered to
17017 		 * ip_rput_forward after the new ire has been
17018 		 * created.
17019 		 */
17020 		mp->b_prev = NULL;
17021 		mp->b_next = mp;
17022 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
17023 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
17024 	} else {
17025 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
17026 		IRE_REFRELE(ire);
17027 	}
17028 }
17029 
17030 /* Update any source route, record route or timestamp options */
17031 static int
17032 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
17033 {
17034 	ipoptp_t	opts;
17035 	uchar_t		*opt;
17036 	uint8_t		optval;
17037 	uint8_t		optlen;
17038 	ipaddr_t	dst;
17039 	uint32_t	ts;
17040 	ire_t		*dst_ire = NULL;
17041 	ire_t		*tmp_ire = NULL;
17042 	timestruc_t	now;
17043 
17044 	ip2dbg(("ip_rput_forward_options\n"));
17045 	dst = ipha->ipha_dst;
17046 	for (optval = ipoptp_first(&opts, ipha);
17047 	    optval != IPOPT_EOL;
17048 	    optval = ipoptp_next(&opts)) {
17049 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17050 		opt = opts.ipoptp_cur;
17051 		optlen = opts.ipoptp_len;
17052 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
17053 		    optval, opts.ipoptp_len));
17054 		switch (optval) {
17055 			uint32_t off;
17056 		case IPOPT_SSRR:
17057 		case IPOPT_LSRR:
17058 			/* Check if adminstratively disabled */
17059 			if (!ipst->ips_ip_forward_src_routed) {
17060 				if (ire->ire_stq != NULL) {
17061 					/*
17062 					 * Sent by forwarding path, and router
17063 					 * is global zone
17064 					 */
17065 					icmp_unreachable(ire->ire_stq, mp,
17066 					    ICMP_SOURCE_ROUTE_FAILED,
17067 					    GLOBAL_ZONEID, ipst);
17068 				} else {
17069 					ip0dbg(("ip_rput_forward_options: "
17070 					    "unable to send unreach\n"));
17071 					freemsg(mp);
17072 				}
17073 				return (-1);
17074 			}
17075 
17076 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17077 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17078 			if (dst_ire == NULL) {
17079 				/*
17080 				 * Must be partial since ip_rput_options
17081 				 * checked for strict.
17082 				 */
17083 				break;
17084 			}
17085 			off = opt[IPOPT_OFFSET];
17086 			off--;
17087 		redo_srr:
17088 			if (optlen < IP_ADDR_LEN ||
17089 			    off > optlen - IP_ADDR_LEN) {
17090 				/* End of source route */
17091 				ip1dbg((
17092 				    "ip_rput_forward_options: end of SR\n"));
17093 				ire_refrele(dst_ire);
17094 				break;
17095 			}
17096 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17097 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17098 			    IP_ADDR_LEN);
17099 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17100 			    ntohl(dst)));
17101 
17102 			/*
17103 			 * Check if our address is present more than
17104 			 * once as consecutive hops in source route.
17105 			 */
17106 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17107 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17108 			if (tmp_ire != NULL) {
17109 				ire_refrele(tmp_ire);
17110 				off += IP_ADDR_LEN;
17111 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17112 				goto redo_srr;
17113 			}
17114 			ipha->ipha_dst = dst;
17115 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17116 			ire_refrele(dst_ire);
17117 			break;
17118 		case IPOPT_RR:
17119 			off = opt[IPOPT_OFFSET];
17120 			off--;
17121 			if (optlen < IP_ADDR_LEN ||
17122 			    off > optlen - IP_ADDR_LEN) {
17123 				/* No more room - ignore */
17124 				ip1dbg((
17125 				    "ip_rput_forward_options: end of RR\n"));
17126 				break;
17127 			}
17128 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17129 			    IP_ADDR_LEN);
17130 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17131 			break;
17132 		case IPOPT_TS:
17133 			/* Insert timestamp if there is room */
17134 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17135 			case IPOPT_TS_TSONLY:
17136 				off = IPOPT_TS_TIMELEN;
17137 				break;
17138 			case IPOPT_TS_PRESPEC:
17139 			case IPOPT_TS_PRESPEC_RFC791:
17140 				/* Verify that the address matched */
17141 				off = opt[IPOPT_OFFSET] - 1;
17142 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17143 				dst_ire = ire_ctable_lookup(dst, 0,
17144 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17145 				    MATCH_IRE_TYPE, ipst);
17146 				if (dst_ire == NULL) {
17147 					/* Not for us */
17148 					break;
17149 				}
17150 				ire_refrele(dst_ire);
17151 				/* FALLTHRU */
17152 			case IPOPT_TS_TSANDADDR:
17153 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17154 				break;
17155 			default:
17156 				/*
17157 				 * ip_*put_options should have already
17158 				 * dropped this packet.
17159 				 */
17160 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17161 				    "unknown IT - bug in ip_rput_options?\n");
17162 				return (0);	/* Keep "lint" happy */
17163 			}
17164 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17165 				/* Increase overflow counter */
17166 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17167 				opt[IPOPT_POS_OV_FLG] =
17168 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17169 				    (off << 4));
17170 				break;
17171 			}
17172 			off = opt[IPOPT_OFFSET] - 1;
17173 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17174 			case IPOPT_TS_PRESPEC:
17175 			case IPOPT_TS_PRESPEC_RFC791:
17176 			case IPOPT_TS_TSANDADDR:
17177 				bcopy(&ire->ire_src_addr,
17178 				    (char *)opt + off, IP_ADDR_LEN);
17179 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17180 				/* FALLTHRU */
17181 			case IPOPT_TS_TSONLY:
17182 				off = opt[IPOPT_OFFSET] - 1;
17183 				/* Compute # of milliseconds since midnight */
17184 				gethrestime(&now);
17185 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17186 				    now.tv_nsec / (NANOSEC / MILLISEC);
17187 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17188 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17189 				break;
17190 			}
17191 			break;
17192 		}
17193 	}
17194 	return (0);
17195 }
17196 
17197 /*
17198  * This is called after processing at least one of AH/ESP headers.
17199  *
17200  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17201  * the actual, physical interface on which the packet was received,
17202  * but, when ip_strict_dst_multihoming is set to 1, could be the
17203  * interface which had the ipha_dst configured when the packet went
17204  * through ip_rput. The ill_index corresponding to the recv_ill
17205  * is saved in ipsec_in_rill_index
17206  *
17207  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17208  * cannot assume "ire" points to valid data for any IPv6 cases.
17209  */
17210 void
17211 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17212 {
17213 	mblk_t *mp;
17214 	ipaddr_t dst;
17215 	in6_addr_t *v6dstp;
17216 	ipha_t *ipha;
17217 	ip6_t *ip6h;
17218 	ipsec_in_t *ii;
17219 	boolean_t ill_need_rele = B_FALSE;
17220 	boolean_t rill_need_rele = B_FALSE;
17221 	boolean_t ire_need_rele = B_FALSE;
17222 	netstack_t	*ns;
17223 	ip_stack_t	*ipst;
17224 
17225 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17226 	ASSERT(ii->ipsec_in_ill_index != 0);
17227 	ns = ii->ipsec_in_ns;
17228 	ASSERT(ii->ipsec_in_ns != NULL);
17229 	ipst = ns->netstack_ip;
17230 
17231 	mp = ipsec_mp->b_cont;
17232 	ASSERT(mp != NULL);
17233 
17234 	if (ill == NULL) {
17235 		ASSERT(recv_ill == NULL);
17236 		/*
17237 		 * We need to get the original queue on which ip_rput_local
17238 		 * or ip_rput_data_v6 was called.
17239 		 */
17240 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17241 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17242 		ill_need_rele = B_TRUE;
17243 
17244 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17245 			recv_ill = ill_lookup_on_ifindex(
17246 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17247 			    NULL, NULL, NULL, NULL, ipst);
17248 			rill_need_rele = B_TRUE;
17249 		} else {
17250 			recv_ill = ill;
17251 		}
17252 
17253 		if ((ill == NULL) || (recv_ill == NULL)) {
17254 			ip0dbg(("ip_fanout_proto_again: interface "
17255 			    "disappeared\n"));
17256 			if (ill != NULL)
17257 				ill_refrele(ill);
17258 			if (recv_ill != NULL)
17259 				ill_refrele(recv_ill);
17260 			freemsg(ipsec_mp);
17261 			return;
17262 		}
17263 	}
17264 
17265 	ASSERT(ill != NULL && recv_ill != NULL);
17266 
17267 	if (mp->b_datap->db_type == M_CTL) {
17268 		/*
17269 		 * AH/ESP is returning the ICMP message after
17270 		 * removing their headers. Fanout again till
17271 		 * it gets to the right protocol.
17272 		 */
17273 		if (ii->ipsec_in_v4) {
17274 			icmph_t *icmph;
17275 			int iph_hdr_length;
17276 			int hdr_length;
17277 
17278 			ipha = (ipha_t *)mp->b_rptr;
17279 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17280 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17281 			ipha = (ipha_t *)&icmph[1];
17282 			hdr_length = IPH_HDR_LENGTH(ipha);
17283 			/*
17284 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17285 			 * Reset the type to M_DATA.
17286 			 */
17287 			mp->b_datap->db_type = M_DATA;
17288 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17289 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17290 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17291 		} else {
17292 			icmp6_t *icmp6;
17293 			int hdr_length;
17294 
17295 			ip6h = (ip6_t *)mp->b_rptr;
17296 			/* Don't call hdr_length_v6() unless you have to. */
17297 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17298 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17299 			else
17300 				hdr_length = IPV6_HDR_LEN;
17301 
17302 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17303 			/*
17304 			 * icmp_inbound_error_fanout_v6 may need to do
17305 			 * pullupmsg.  Reset the type to M_DATA.
17306 			 */
17307 			mp->b_datap->db_type = M_DATA;
17308 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17309 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17310 			    ii->ipsec_in_zoneid);
17311 		}
17312 		if (ill_need_rele)
17313 			ill_refrele(ill);
17314 		if (rill_need_rele)
17315 			ill_refrele(recv_ill);
17316 		return;
17317 	}
17318 
17319 	if (ii->ipsec_in_v4) {
17320 		ipha = (ipha_t *)mp->b_rptr;
17321 		dst = ipha->ipha_dst;
17322 		if (CLASSD(dst)) {
17323 			/*
17324 			 * Multicast has to be delivered to all streams.
17325 			 */
17326 			dst = INADDR_BROADCAST;
17327 		}
17328 
17329 		if (ire == NULL) {
17330 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17331 			    msg_getlabel(mp), ipst);
17332 			if (ire == NULL) {
17333 				if (ill_need_rele)
17334 					ill_refrele(ill);
17335 				if (rill_need_rele)
17336 					ill_refrele(recv_ill);
17337 				ip1dbg(("ip_fanout_proto_again: "
17338 				    "IRE not found"));
17339 				freemsg(ipsec_mp);
17340 				return;
17341 			}
17342 			ire_need_rele = B_TRUE;
17343 		}
17344 
17345 		switch (ipha->ipha_protocol) {
17346 		case IPPROTO_UDP:
17347 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17348 			    recv_ill);
17349 			if (ire_need_rele)
17350 				ire_refrele(ire);
17351 			break;
17352 		case IPPROTO_TCP:
17353 			if (!ire_need_rele)
17354 				IRE_REFHOLD(ire);
17355 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17356 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17357 			IRE_REFRELE(ire);
17358 			if (mp != NULL) {
17359 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17360 				    mp, 1, SQ_PROCESS,
17361 				    SQTAG_IP_PROTO_AGAIN);
17362 			}
17363 			break;
17364 		case IPPROTO_SCTP:
17365 			if (!ire_need_rele)
17366 				IRE_REFHOLD(ire);
17367 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17368 			    ipsec_mp, 0, ill->ill_rq, dst);
17369 			break;
17370 		default:
17371 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17372 			    recv_ill, 0);
17373 			if (ire_need_rele)
17374 				ire_refrele(ire);
17375 			break;
17376 		}
17377 	} else {
17378 		uint32_t rput_flags = 0;
17379 
17380 		ip6h = (ip6_t *)mp->b_rptr;
17381 		v6dstp = &ip6h->ip6_dst;
17382 		/*
17383 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17384 		 * address.
17385 		 *
17386 		 * Currently, we don't store that state in the IPSEC_IN
17387 		 * message, and we may need to.
17388 		 */
17389 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17390 		    IP6_IN_LLMCAST : 0);
17391 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17392 		    NULL, NULL);
17393 	}
17394 	if (ill_need_rele)
17395 		ill_refrele(ill);
17396 	if (rill_need_rele)
17397 		ill_refrele(recv_ill);
17398 }
17399 
17400 /*
17401  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17402  * returns 'true' if there are still fragments left on the queue, in
17403  * which case we restart the timer.
17404  */
17405 void
17406 ill_frag_timer(void *arg)
17407 {
17408 	ill_t	*ill = (ill_t *)arg;
17409 	boolean_t frag_pending;
17410 	ip_stack_t	*ipst = ill->ill_ipst;
17411 	time_t	timeout;
17412 
17413 	mutex_enter(&ill->ill_lock);
17414 	ASSERT(!ill->ill_fragtimer_executing);
17415 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17416 		ill->ill_frag_timer_id = 0;
17417 		mutex_exit(&ill->ill_lock);
17418 		return;
17419 	}
17420 	ill->ill_fragtimer_executing = 1;
17421 	mutex_exit(&ill->ill_lock);
17422 
17423 	if (ill->ill_isv6)
17424 		timeout = ipst->ips_ipv6_frag_timeout;
17425 	else
17426 		timeout = ipst->ips_ip_g_frag_timeout;
17427 
17428 	frag_pending = ill_frag_timeout(ill, timeout);
17429 
17430 	/*
17431 	 * Restart the timer, if we have fragments pending or if someone
17432 	 * wanted us to be scheduled again.
17433 	 */
17434 	mutex_enter(&ill->ill_lock);
17435 	ill->ill_fragtimer_executing = 0;
17436 	ill->ill_frag_timer_id = 0;
17437 	if (frag_pending || ill->ill_fragtimer_needrestart)
17438 		ill_frag_timer_start(ill);
17439 	mutex_exit(&ill->ill_lock);
17440 }
17441 
17442 void
17443 ill_frag_timer_start(ill_t *ill)
17444 {
17445 	ip_stack_t	*ipst = ill->ill_ipst;
17446 	clock_t	timeo_ms;
17447 
17448 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17449 
17450 	/* If the ill is closing or opening don't proceed */
17451 	if (ill->ill_state_flags & ILL_CONDEMNED)
17452 		return;
17453 
17454 	if (ill->ill_fragtimer_executing) {
17455 		/*
17456 		 * ill_frag_timer is currently executing. Just record the
17457 		 * the fact that we want the timer to be restarted.
17458 		 * ill_frag_timer will post a timeout before it returns,
17459 		 * ensuring it will be called again.
17460 		 */
17461 		ill->ill_fragtimer_needrestart = 1;
17462 		return;
17463 	}
17464 
17465 	if (ill->ill_frag_timer_id == 0) {
17466 		if (ill->ill_isv6)
17467 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17468 		else
17469 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17470 		/*
17471 		 * The timer is neither running nor is the timeout handler
17472 		 * executing. Post a timeout so that ill_frag_timer will be
17473 		 * called
17474 		 */
17475 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17476 		    MSEC_TO_TICK(timeo_ms >> 1));
17477 		ill->ill_fragtimer_needrestart = 0;
17478 	}
17479 }
17480 
17481 /*
17482  * This routine is needed for loopback when forwarding multicasts.
17483  *
17484  * IPQoS Notes:
17485  * IPPF processing is done in fanout routines.
17486  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17487  * processing for IPsec packets is done when it comes back in clear.
17488  * NOTE : The callers of this function need to do the ire_refrele for the
17489  *	  ire that is being passed in.
17490  */
17491 void
17492 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17493     ill_t *recv_ill, uint32_t esp_udp_ports)
17494 {
17495 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17496 	ill_t	*ill = (ill_t *)q->q_ptr;
17497 	uint32_t	sum;
17498 	uint32_t	u1;
17499 	uint32_t	u2;
17500 	int		hdr_length;
17501 	boolean_t	mctl_present;
17502 	mblk_t		*first_mp = mp;
17503 	mblk_t		*hada_mp = NULL;
17504 	ipha_t		*inner_ipha;
17505 	ip_stack_t	*ipst;
17506 
17507 	ASSERT(recv_ill != NULL);
17508 	ipst = recv_ill->ill_ipst;
17509 
17510 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17511 	    "ip_rput_locl_start: q %p", q);
17512 
17513 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17514 	ASSERT(ill != NULL);
17515 
17516 #define	rptr	((uchar_t *)ipha)
17517 #define	iphs	((uint16_t *)ipha)
17518 
17519 	/*
17520 	 * no UDP or TCP packet should come here anymore.
17521 	 */
17522 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17523 	    ipha->ipha_protocol != IPPROTO_UDP);
17524 
17525 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17526 	if (mctl_present &&
17527 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17528 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17529 
17530 		/*
17531 		 * It's an IPsec accelerated packet.
17532 		 * Keep a pointer to the data attributes around until
17533 		 * we allocate the ipsec_info_t.
17534 		 */
17535 		IPSECHW_DEBUG(IPSECHW_PKT,
17536 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17537 		hada_mp = first_mp;
17538 		hada_mp->b_cont = NULL;
17539 		/*
17540 		 * Since it is accelerated, it comes directly from
17541 		 * the ill and the data attributes is followed by
17542 		 * the packet data.
17543 		 */
17544 		ASSERT(mp->b_datap->db_type != M_CTL);
17545 		first_mp = mp;
17546 		mctl_present = B_FALSE;
17547 	}
17548 
17549 	/*
17550 	 * IF M_CTL is not present, then ipsec_in_is_secure
17551 	 * should return B_TRUE. There is a case where loopback
17552 	 * packets has an M_CTL in the front with all the
17553 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17554 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17555 	 * packets never comes here, it is safe to ASSERT the
17556 	 * following.
17557 	 */
17558 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17559 
17560 	/*
17561 	 * Also, we should never have an mctl_present if this is an
17562 	 * ESP-in-UDP packet.
17563 	 */
17564 	ASSERT(!mctl_present || !esp_in_udp_packet);
17565 
17566 	/* u1 is # words of IP options */
17567 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17568 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17569 
17570 	/*
17571 	 * Don't verify header checksum if we just removed UDP header or
17572 	 * packet is coming back from AH/ESP.
17573 	 */
17574 	if (!esp_in_udp_packet && !mctl_present) {
17575 		if (u1) {
17576 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17577 				if (hada_mp != NULL)
17578 					freemsg(hada_mp);
17579 				return;
17580 			}
17581 		} else {
17582 			/* Check the IP header checksum.  */
17583 #define	uph	((uint16_t *)ipha)
17584 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17585 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17586 #undef  uph
17587 			/* finish doing IP checksum */
17588 			sum = (sum & 0xFFFF) + (sum >> 16);
17589 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17590 			if (sum && sum != 0xFFFF) {
17591 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17592 				goto drop_pkt;
17593 			}
17594 		}
17595 	}
17596 
17597 	/*
17598 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17599 	 * might be called more than once for secure packets, count only
17600 	 * the first time.
17601 	 */
17602 	if (!mctl_present) {
17603 		UPDATE_IB_PKT_COUNT(ire);
17604 		ire->ire_last_used_time = lbolt;
17605 	}
17606 
17607 	/* Check for fragmentation offset. */
17608 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17609 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17610 	if (u1) {
17611 		/*
17612 		 * We re-assemble fragments before we do the AH/ESP
17613 		 * processing. Thus, M_CTL should not be present
17614 		 * while we are re-assembling.
17615 		 */
17616 		ASSERT(!mctl_present);
17617 		ASSERT(first_mp == mp);
17618 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17619 			return;
17620 
17621 		/*
17622 		 * Make sure that first_mp points back to mp as
17623 		 * the mp we came in with could have changed in
17624 		 * ip_rput_fragment().
17625 		 */
17626 		ipha = (ipha_t *)mp->b_rptr;
17627 		first_mp = mp;
17628 	}
17629 
17630 	/*
17631 	 * Clear hardware checksumming flag as it is currently only
17632 	 * used by TCP and UDP.
17633 	 */
17634 	DB_CKSUMFLAGS(mp) = 0;
17635 
17636 	/* Now we have a complete datagram, destined for this machine. */
17637 	u1 = IPH_HDR_LENGTH(ipha);
17638 	switch (ipha->ipha_protocol) {
17639 	case IPPROTO_ICMP: {
17640 		ire_t		*ire_zone;
17641 		ilm_t		*ilm;
17642 		mblk_t		*mp1;
17643 		zoneid_t	last_zoneid;
17644 		ilm_walker_t	ilw;
17645 
17646 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17647 			ASSERT(ire->ire_type == IRE_BROADCAST);
17648 
17649 			/*
17650 			 * In the multicast case, applications may have joined
17651 			 * the group from different zones, so we need to deliver
17652 			 * the packet to each of them. Loop through the
17653 			 * multicast memberships structures (ilm) on the receive
17654 			 * ill and send a copy of the packet up each matching
17655 			 * one. However, we don't do this for multicasts sent on
17656 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17657 			 * they must stay in the sender's zone.
17658 			 *
17659 			 * ilm_add_v6() ensures that ilms in the same zone are
17660 			 * contiguous in the ill_ilm list. We use this property
17661 			 * to avoid sending duplicates needed when two
17662 			 * applications in the same zone join the same group on
17663 			 * different logical interfaces: we ignore the ilm if
17664 			 * its zoneid is the same as the last matching one.
17665 			 * In addition, the sending of the packet for
17666 			 * ire_zoneid is delayed until all of the other ilms
17667 			 * have been exhausted.
17668 			 */
17669 			last_zoneid = -1;
17670 			ilm = ilm_walker_start(&ilw, recv_ill);
17671 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17672 				if (ipha->ipha_dst != ilm->ilm_addr ||
17673 				    ilm->ilm_zoneid == last_zoneid ||
17674 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17675 				    ilm->ilm_zoneid == ALL_ZONES ||
17676 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17677 					continue;
17678 				mp1 = ip_copymsg(first_mp);
17679 				if (mp1 == NULL)
17680 					continue;
17681 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17682 				    0, sum, mctl_present, B_TRUE,
17683 				    recv_ill, ilm->ilm_zoneid);
17684 				last_zoneid = ilm->ilm_zoneid;
17685 			}
17686 			ilm_walker_finish(&ilw);
17687 		} else if (ire->ire_type == IRE_BROADCAST) {
17688 			/*
17689 			 * In the broadcast case, there may be many zones
17690 			 * which need a copy of the packet delivered to them.
17691 			 * There is one IRE_BROADCAST per broadcast address
17692 			 * and per zone; we walk those using a helper function.
17693 			 * In addition, the sending of the packet for ire is
17694 			 * delayed until all of the other ires have been
17695 			 * processed.
17696 			 */
17697 			IRB_REFHOLD(ire->ire_bucket);
17698 			ire_zone = NULL;
17699 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17700 			    ire)) != NULL) {
17701 				mp1 = ip_copymsg(first_mp);
17702 				if (mp1 == NULL)
17703 					continue;
17704 
17705 				UPDATE_IB_PKT_COUNT(ire_zone);
17706 				ire_zone->ire_last_used_time = lbolt;
17707 				icmp_inbound(q, mp1, B_TRUE, ill,
17708 				    0, sum, mctl_present, B_TRUE,
17709 				    recv_ill, ire_zone->ire_zoneid);
17710 			}
17711 			IRB_REFRELE(ire->ire_bucket);
17712 		}
17713 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17714 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17715 		    ire->ire_zoneid);
17716 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17717 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17718 		return;
17719 	}
17720 	case IPPROTO_IGMP:
17721 		/*
17722 		 * If we are not willing to accept IGMP packets in clear,
17723 		 * then check with global policy.
17724 		 */
17725 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17726 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17727 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17728 			if (first_mp == NULL)
17729 				return;
17730 		}
17731 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17732 			freemsg(first_mp);
17733 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17734 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17735 			return;
17736 		}
17737 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17738 			/* Bad packet - discarded by igmp_input */
17739 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17740 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17741 			if (mctl_present)
17742 				freeb(first_mp);
17743 			return;
17744 		}
17745 		/*
17746 		 * igmp_input() may have returned the pulled up message.
17747 		 * So first_mp and ipha need to be reinitialized.
17748 		 */
17749 		ipha = (ipha_t *)mp->b_rptr;
17750 		if (mctl_present)
17751 			first_mp->b_cont = mp;
17752 		else
17753 			first_mp = mp;
17754 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17755 		    connf_head != NULL) {
17756 			/* No user-level listener for IGMP packets */
17757 			goto drop_pkt;
17758 		}
17759 		/* deliver to local raw users */
17760 		break;
17761 	case IPPROTO_PIM:
17762 		/*
17763 		 * If we are not willing to accept PIM packets in clear,
17764 		 * then check with global policy.
17765 		 */
17766 		if (ipst->ips_pim_accept_clear_messages == 0) {
17767 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17768 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17769 			if (first_mp == NULL)
17770 				return;
17771 		}
17772 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17773 			freemsg(first_mp);
17774 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17775 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17776 			return;
17777 		}
17778 		if (pim_input(q, mp, ill) != 0) {
17779 			/* Bad packet - discarded by pim_input */
17780 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17781 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17782 			if (mctl_present)
17783 				freeb(first_mp);
17784 			return;
17785 		}
17786 
17787 		/*
17788 		 * pim_input() may have pulled up the message so ipha needs to
17789 		 * be reinitialized.
17790 		 */
17791 		ipha = (ipha_t *)mp->b_rptr;
17792 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17793 		    connf_head != NULL) {
17794 			/* No user-level listener for PIM packets */
17795 			goto drop_pkt;
17796 		}
17797 		/* deliver to local raw users */
17798 		break;
17799 	case IPPROTO_ENCAP:
17800 		/*
17801 		 * Handle self-encapsulated packets (IP-in-IP where
17802 		 * the inner addresses == the outer addresses).
17803 		 */
17804 		hdr_length = IPH_HDR_LENGTH(ipha);
17805 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17806 		    mp->b_wptr) {
17807 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17808 			    sizeof (ipha_t) - mp->b_rptr)) {
17809 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17810 				freemsg(first_mp);
17811 				return;
17812 			}
17813 			ipha = (ipha_t *)mp->b_rptr;
17814 		}
17815 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17816 		/*
17817 		 * Check the sanity of the inner IP header.
17818 		 */
17819 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17820 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17821 			freemsg(first_mp);
17822 			return;
17823 		}
17824 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17825 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17826 			freemsg(first_mp);
17827 			return;
17828 		}
17829 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17830 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17831 			ipsec_in_t *ii;
17832 
17833 			/*
17834 			 * Self-encapsulated tunnel packet. Remove
17835 			 * the outer IP header and fanout again.
17836 			 * We also need to make sure that the inner
17837 			 * header is pulled up until options.
17838 			 */
17839 			mp->b_rptr = (uchar_t *)inner_ipha;
17840 			ipha = inner_ipha;
17841 			hdr_length = IPH_HDR_LENGTH(ipha);
17842 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17843 				if (!pullupmsg(mp, (uchar_t *)ipha +
17844 				    + hdr_length - mp->b_rptr)) {
17845 					freemsg(first_mp);
17846 					return;
17847 				}
17848 				ipha = (ipha_t *)mp->b_rptr;
17849 			}
17850 			if (hdr_length > sizeof (ipha_t)) {
17851 				/* We got options on the inner packet. */
17852 				ipaddr_t dst = ipha->ipha_dst;
17853 
17854 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17855 				    -1) {
17856 					/* Bad options! */
17857 					return;
17858 				}
17859 				if (dst != ipha->ipha_dst) {
17860 					/*
17861 					 * Someone put a source-route in
17862 					 * the inside header of a self-
17863 					 * encapsulated packet.  Drop it
17864 					 * with extreme prejudice and let
17865 					 * the sender know.
17866 					 */
17867 					icmp_unreachable(q, first_mp,
17868 					    ICMP_SOURCE_ROUTE_FAILED,
17869 					    recv_ill->ill_zoneid, ipst);
17870 					return;
17871 				}
17872 			}
17873 			if (!mctl_present) {
17874 				ASSERT(first_mp == mp);
17875 				/*
17876 				 * This means that somebody is sending
17877 				 * Self-encapsualted packets without AH/ESP.
17878 				 * If AH/ESP was present, we would have already
17879 				 * allocated the first_mp.
17880 				 *
17881 				 * Send this packet to find a tunnel endpoint.
17882 				 * if I can't find one, an ICMP
17883 				 * PROTOCOL_UNREACHABLE will get sent.
17884 				 */
17885 				goto fanout;
17886 			}
17887 			/*
17888 			 * We generally store the ill_index if we need to
17889 			 * do IPsec processing as we lose the ill queue when
17890 			 * we come back. But in this case, we never should
17891 			 * have to store the ill_index here as it should have
17892 			 * been stored previously when we processed the
17893 			 * AH/ESP header in this routine or for non-ipsec
17894 			 * cases, we still have the queue. But for some bad
17895 			 * packets from the wire, we can get to IPsec after
17896 			 * this and we better store the index for that case.
17897 			 */
17898 			ill = (ill_t *)q->q_ptr;
17899 			ii = (ipsec_in_t *)first_mp->b_rptr;
17900 			ii->ipsec_in_ill_index =
17901 			    ill->ill_phyint->phyint_ifindex;
17902 			ii->ipsec_in_rill_index =
17903 			    recv_ill->ill_phyint->phyint_ifindex;
17904 			if (ii->ipsec_in_decaps) {
17905 				/*
17906 				 * This packet is self-encapsulated multiple
17907 				 * times. We don't want to recurse infinitely.
17908 				 * To keep it simple, drop the packet.
17909 				 */
17910 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17911 				freemsg(first_mp);
17912 				return;
17913 			}
17914 			ii->ipsec_in_decaps = B_TRUE;
17915 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17916 			    ire);
17917 			return;
17918 		}
17919 		break;
17920 	case IPPROTO_AH:
17921 	case IPPROTO_ESP: {
17922 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17923 
17924 		/*
17925 		 * Fast path for AH/ESP. If this is the first time
17926 		 * we are sending a datagram to AH/ESP, allocate
17927 		 * a IPSEC_IN message and prepend it. Otherwise,
17928 		 * just fanout.
17929 		 */
17930 
17931 		int ipsec_rc;
17932 		ipsec_in_t *ii;
17933 		netstack_t *ns = ipst->ips_netstack;
17934 
17935 		IP_STAT(ipst, ipsec_proto_ahesp);
17936 		if (!mctl_present) {
17937 			ASSERT(first_mp == mp);
17938 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17939 			if (first_mp == NULL) {
17940 				ip1dbg(("ip_proto_input: IPSEC_IN "
17941 				    "allocation failure.\n"));
17942 				freemsg(hada_mp); /* okay ifnull */
17943 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17944 				freemsg(mp);
17945 				return;
17946 			}
17947 			/*
17948 			 * Store the ill_index so that when we come back
17949 			 * from IPsec we ride on the same queue.
17950 			 */
17951 			ill = (ill_t *)q->q_ptr;
17952 			ii = (ipsec_in_t *)first_mp->b_rptr;
17953 			ii->ipsec_in_ill_index =
17954 			    ill->ill_phyint->phyint_ifindex;
17955 			ii->ipsec_in_rill_index =
17956 			    recv_ill->ill_phyint->phyint_ifindex;
17957 			first_mp->b_cont = mp;
17958 			/*
17959 			 * Cache hardware acceleration info.
17960 			 */
17961 			if (hada_mp != NULL) {
17962 				IPSECHW_DEBUG(IPSECHW_PKT,
17963 				    ("ip_rput_local: caching data attr.\n"));
17964 				ii->ipsec_in_accelerated = B_TRUE;
17965 				ii->ipsec_in_da = hada_mp;
17966 				hada_mp = NULL;
17967 			}
17968 		} else {
17969 			ii = (ipsec_in_t *)first_mp->b_rptr;
17970 		}
17971 
17972 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17973 
17974 		if (!ipsec_loaded(ipss)) {
17975 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17976 			    ire->ire_zoneid, ipst);
17977 			return;
17978 		}
17979 
17980 		ns = ipst->ips_netstack;
17981 		/* select inbound SA and have IPsec process the pkt */
17982 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17983 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17984 			boolean_t esp_in_udp_sa;
17985 			if (esph == NULL)
17986 				return;
17987 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17988 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17989 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17990 			    IPSA_F_NATT) != 0);
17991 			/*
17992 			 * The following is a fancy, but quick, way of saying:
17993 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17994 			 *    OR
17995 			 * ESP SA and ESP-in-UDP packet --> drop
17996 			 */
17997 			if (esp_in_udp_sa != esp_in_udp_packet) {
17998 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17999 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
18000 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
18001 				    &ns->netstack_ipsec->ipsec_dropper);
18002 				return;
18003 			}
18004 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
18005 			    first_mp, esph);
18006 		} else {
18007 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
18008 			if (ah == NULL)
18009 				return;
18010 			ASSERT(ii->ipsec_in_ah_sa != NULL);
18011 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
18012 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
18013 			    first_mp, ah);
18014 		}
18015 
18016 		switch (ipsec_rc) {
18017 		case IPSEC_STATUS_SUCCESS:
18018 			break;
18019 		case IPSEC_STATUS_FAILED:
18020 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
18021 			/* FALLTHRU */
18022 		case IPSEC_STATUS_PENDING:
18023 			return;
18024 		}
18025 		/* we're done with IPsec processing, send it up */
18026 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
18027 		return;
18028 	}
18029 	default:
18030 		break;
18031 	}
18032 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
18033 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
18034 		    ire->ire_zoneid));
18035 		goto drop_pkt;
18036 	}
18037 	/*
18038 	 * Handle protocols with which IP is less intimate.  There
18039 	 * can be more than one stream bound to a particular
18040 	 * protocol.  When this is the case, each one gets a copy
18041 	 * of any incoming packets.
18042 	 */
18043 fanout:
18044 	ip_fanout_proto(q, first_mp, ill, ipha,
18045 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
18046 	    B_TRUE, recv_ill, ire->ire_zoneid);
18047 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18048 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
18049 	return;
18050 
18051 drop_pkt:
18052 	freemsg(first_mp);
18053 	if (hada_mp != NULL)
18054 		freeb(hada_mp);
18055 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18056 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
18057 #undef	rptr
18058 #undef  iphs
18059 
18060 }
18061 
18062 /*
18063  * Update any source route, record route or timestamp options.
18064  * Check that we are at end of strict source route.
18065  * The options have already been checked for sanity in ip_rput_options().
18066  */
18067 static boolean_t
18068 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
18069     ip_stack_t *ipst)
18070 {
18071 	ipoptp_t	opts;
18072 	uchar_t		*opt;
18073 	uint8_t		optval;
18074 	uint8_t		optlen;
18075 	ipaddr_t	dst;
18076 	uint32_t	ts;
18077 	ire_t		*dst_ire;
18078 	timestruc_t	now;
18079 	zoneid_t	zoneid;
18080 	ill_t		*ill;
18081 
18082 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18083 
18084 	ip2dbg(("ip_rput_local_options\n"));
18085 
18086 	for (optval = ipoptp_first(&opts, ipha);
18087 	    optval != IPOPT_EOL;
18088 	    optval = ipoptp_next(&opts)) {
18089 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18090 		opt = opts.ipoptp_cur;
18091 		optlen = opts.ipoptp_len;
18092 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18093 		    optval, optlen));
18094 		switch (optval) {
18095 			uint32_t off;
18096 		case IPOPT_SSRR:
18097 		case IPOPT_LSRR:
18098 			off = opt[IPOPT_OFFSET];
18099 			off--;
18100 			if (optlen < IP_ADDR_LEN ||
18101 			    off > optlen - IP_ADDR_LEN) {
18102 				/* End of source route */
18103 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18104 				break;
18105 			}
18106 			/*
18107 			 * This will only happen if two consecutive entries
18108 			 * in the source route contains our address or if
18109 			 * it is a packet with a loose source route which
18110 			 * reaches us before consuming the whole source route
18111 			 */
18112 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18113 			if (optval == IPOPT_SSRR) {
18114 				goto bad_src_route;
18115 			}
18116 			/*
18117 			 * Hack: instead of dropping the packet truncate the
18118 			 * source route to what has been used by filling the
18119 			 * rest with IPOPT_NOP.
18120 			 */
18121 			opt[IPOPT_OLEN] = (uint8_t)off;
18122 			while (off < optlen) {
18123 				opt[off++] = IPOPT_NOP;
18124 			}
18125 			break;
18126 		case IPOPT_RR:
18127 			off = opt[IPOPT_OFFSET];
18128 			off--;
18129 			if (optlen < IP_ADDR_LEN ||
18130 			    off > optlen - IP_ADDR_LEN) {
18131 				/* No more room - ignore */
18132 				ip1dbg((
18133 				    "ip_rput_local_options: end of RR\n"));
18134 				break;
18135 			}
18136 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18137 			    IP_ADDR_LEN);
18138 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18139 			break;
18140 		case IPOPT_TS:
18141 			/* Insert timestamp if there is romm */
18142 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18143 			case IPOPT_TS_TSONLY:
18144 				off = IPOPT_TS_TIMELEN;
18145 				break;
18146 			case IPOPT_TS_PRESPEC:
18147 			case IPOPT_TS_PRESPEC_RFC791:
18148 				/* Verify that the address matched */
18149 				off = opt[IPOPT_OFFSET] - 1;
18150 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18151 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18152 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18153 				    ipst);
18154 				if (dst_ire == NULL) {
18155 					/* Not for us */
18156 					break;
18157 				}
18158 				ire_refrele(dst_ire);
18159 				/* FALLTHRU */
18160 			case IPOPT_TS_TSANDADDR:
18161 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18162 				break;
18163 			default:
18164 				/*
18165 				 * ip_*put_options should have already
18166 				 * dropped this packet.
18167 				 */
18168 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18169 				    "unknown IT - bug in ip_rput_options?\n");
18170 				return (B_TRUE);	/* Keep "lint" happy */
18171 			}
18172 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18173 				/* Increase overflow counter */
18174 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18175 				opt[IPOPT_POS_OV_FLG] =
18176 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18177 				    (off << 4));
18178 				break;
18179 			}
18180 			off = opt[IPOPT_OFFSET] - 1;
18181 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18182 			case IPOPT_TS_PRESPEC:
18183 			case IPOPT_TS_PRESPEC_RFC791:
18184 			case IPOPT_TS_TSANDADDR:
18185 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18186 				    IP_ADDR_LEN);
18187 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18188 				/* FALLTHRU */
18189 			case IPOPT_TS_TSONLY:
18190 				off = opt[IPOPT_OFFSET] - 1;
18191 				/* Compute # of milliseconds since midnight */
18192 				gethrestime(&now);
18193 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18194 				    now.tv_nsec / (NANOSEC / MILLISEC);
18195 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18196 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18197 				break;
18198 			}
18199 			break;
18200 		}
18201 	}
18202 	return (B_TRUE);
18203 
18204 bad_src_route:
18205 	q = WR(q);
18206 	if (q->q_next != NULL)
18207 		ill = q->q_ptr;
18208 	else
18209 		ill = NULL;
18210 
18211 	/* make sure we clear any indication of a hardware checksum */
18212 	DB_CKSUMFLAGS(mp) = 0;
18213 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18214 	if (zoneid == ALL_ZONES)
18215 		freemsg(mp);
18216 	else
18217 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18218 	return (B_FALSE);
18219 
18220 }
18221 
18222 /*
18223  * Process IP options in an inbound packet.  If an option affects the
18224  * effective destination address, return the next hop address via dstp.
18225  * Returns -1 if something fails in which case an ICMP error has been sent
18226  * and mp freed.
18227  */
18228 static int
18229 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18230     ip_stack_t *ipst)
18231 {
18232 	ipoptp_t	opts;
18233 	uchar_t		*opt;
18234 	uint8_t		optval;
18235 	uint8_t		optlen;
18236 	ipaddr_t	dst;
18237 	intptr_t	code = 0;
18238 	ire_t		*ire = NULL;
18239 	zoneid_t	zoneid;
18240 	ill_t		*ill;
18241 
18242 	ip2dbg(("ip_rput_options\n"));
18243 	dst = ipha->ipha_dst;
18244 	for (optval = ipoptp_first(&opts, ipha);
18245 	    optval != IPOPT_EOL;
18246 	    optval = ipoptp_next(&opts)) {
18247 		opt = opts.ipoptp_cur;
18248 		optlen = opts.ipoptp_len;
18249 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18250 		    optval, optlen));
18251 		/*
18252 		 * Note: we need to verify the checksum before we
18253 		 * modify anything thus this routine only extracts the next
18254 		 * hop dst from any source route.
18255 		 */
18256 		switch (optval) {
18257 			uint32_t off;
18258 		case IPOPT_SSRR:
18259 		case IPOPT_LSRR:
18260 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18261 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18262 			if (ire == NULL) {
18263 				if (optval == IPOPT_SSRR) {
18264 					ip1dbg(("ip_rput_options: not next"
18265 					    " strict source route 0x%x\n",
18266 					    ntohl(dst)));
18267 					code = (char *)&ipha->ipha_dst -
18268 					    (char *)ipha;
18269 					goto param_prob; /* RouterReq's */
18270 				}
18271 				ip2dbg(("ip_rput_options: "
18272 				    "not next source route 0x%x\n",
18273 				    ntohl(dst)));
18274 				break;
18275 			}
18276 			ire_refrele(ire);
18277 
18278 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18279 				ip1dbg((
18280 				    "ip_rput_options: bad option offset\n"));
18281 				code = (char *)&opt[IPOPT_OLEN] -
18282 				    (char *)ipha;
18283 				goto param_prob;
18284 			}
18285 			off = opt[IPOPT_OFFSET];
18286 			off--;
18287 		redo_srr:
18288 			if (optlen < IP_ADDR_LEN ||
18289 			    off > optlen - IP_ADDR_LEN) {
18290 				/* End of source route */
18291 				ip1dbg(("ip_rput_options: end of SR\n"));
18292 				break;
18293 			}
18294 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18295 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18296 			    ntohl(dst)));
18297 
18298 			/*
18299 			 * Check if our address is present more than
18300 			 * once as consecutive hops in source route.
18301 			 * XXX verify per-interface ip_forwarding
18302 			 * for source route?
18303 			 */
18304 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18305 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18306 
18307 			if (ire != NULL) {
18308 				ire_refrele(ire);
18309 				off += IP_ADDR_LEN;
18310 				goto redo_srr;
18311 			}
18312 
18313 			if (dst == htonl(INADDR_LOOPBACK)) {
18314 				ip1dbg(("ip_rput_options: loopback addr in "
18315 				    "source route!\n"));
18316 				goto bad_src_route;
18317 			}
18318 			/*
18319 			 * For strict: verify that dst is directly
18320 			 * reachable.
18321 			 */
18322 			if (optval == IPOPT_SSRR) {
18323 				ire = ire_ftable_lookup(dst, 0, 0,
18324 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18325 				    msg_getlabel(mp),
18326 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18327 				if (ire == NULL) {
18328 					ip1dbg(("ip_rput_options: SSRR not "
18329 					    "directly reachable: 0x%x\n",
18330 					    ntohl(dst)));
18331 					goto bad_src_route;
18332 				}
18333 				ire_refrele(ire);
18334 			}
18335 			/*
18336 			 * Defer update of the offset and the record route
18337 			 * until the packet is forwarded.
18338 			 */
18339 			break;
18340 		case IPOPT_RR:
18341 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18342 				ip1dbg((
18343 				    "ip_rput_options: bad option offset\n"));
18344 				code = (char *)&opt[IPOPT_OLEN] -
18345 				    (char *)ipha;
18346 				goto param_prob;
18347 			}
18348 			break;
18349 		case IPOPT_TS:
18350 			/*
18351 			 * Verify that length >= 5 and that there is either
18352 			 * room for another timestamp or that the overflow
18353 			 * counter is not maxed out.
18354 			 */
18355 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18356 			if (optlen < IPOPT_MINLEN_IT) {
18357 				goto param_prob;
18358 			}
18359 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18360 				ip1dbg((
18361 				    "ip_rput_options: bad option offset\n"));
18362 				code = (char *)&opt[IPOPT_OFFSET] -
18363 				    (char *)ipha;
18364 				goto param_prob;
18365 			}
18366 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18367 			case IPOPT_TS_TSONLY:
18368 				off = IPOPT_TS_TIMELEN;
18369 				break;
18370 			case IPOPT_TS_TSANDADDR:
18371 			case IPOPT_TS_PRESPEC:
18372 			case IPOPT_TS_PRESPEC_RFC791:
18373 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18374 				break;
18375 			default:
18376 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18377 				    (char *)ipha;
18378 				goto param_prob;
18379 			}
18380 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18381 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18382 				/*
18383 				 * No room and the overflow counter is 15
18384 				 * already.
18385 				 */
18386 				goto param_prob;
18387 			}
18388 			break;
18389 		}
18390 	}
18391 
18392 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18393 		*dstp = dst;
18394 		return (0);
18395 	}
18396 
18397 	ip1dbg(("ip_rput_options: error processing IP options."));
18398 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18399 
18400 param_prob:
18401 	q = WR(q);
18402 	if (q->q_next != NULL)
18403 		ill = q->q_ptr;
18404 	else
18405 		ill = NULL;
18406 
18407 	/* make sure we clear any indication of a hardware checksum */
18408 	DB_CKSUMFLAGS(mp) = 0;
18409 	/* Don't know whether this is for non-global or global/forwarding */
18410 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18411 	if (zoneid == ALL_ZONES)
18412 		freemsg(mp);
18413 	else
18414 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18415 	return (-1);
18416 
18417 bad_src_route:
18418 	q = WR(q);
18419 	if (q->q_next != NULL)
18420 		ill = q->q_ptr;
18421 	else
18422 		ill = NULL;
18423 
18424 	/* make sure we clear any indication of a hardware checksum */
18425 	DB_CKSUMFLAGS(mp) = 0;
18426 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18427 	if (zoneid == ALL_ZONES)
18428 		freemsg(mp);
18429 	else
18430 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18431 	return (-1);
18432 }
18433 
18434 /*
18435  * IP & ICMP info in >=14 msg's ...
18436  *  - ip fixed part (mib2_ip_t)
18437  *  - icmp fixed part (mib2_icmp_t)
18438  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18439  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18440  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18441  *  - ipRouteAttributeTable (ip 102)	labeled routes
18442  *  - ip multicast membership (ip_member_t)
18443  *  - ip multicast source filtering (ip_grpsrc_t)
18444  *  - igmp fixed part (struct igmpstat)
18445  *  - multicast routing stats (struct mrtstat)
18446  *  - multicast routing vifs (array of struct vifctl)
18447  *  - multicast routing routes (array of struct mfcctl)
18448  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18449  *					One per ill plus one generic
18450  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18451  *					One per ill plus one generic
18452  *  - ipv6RouteEntry			all IPv6 IREs
18453  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18454  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18455  *  - ipv6AddrEntry			all IPv6 ipifs
18456  *  - ipv6 multicast membership (ipv6_member_t)
18457  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18458  *
18459  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18460  *
18461  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18462  * already filled in by the caller.
18463  * Return value of 0 indicates that no messages were sent and caller
18464  * should free mpctl.
18465  */
18466 int
18467 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18468 {
18469 	ip_stack_t *ipst;
18470 	sctp_stack_t *sctps;
18471 
18472 	if (q->q_next != NULL) {
18473 		ipst = ILLQ_TO_IPST(q);
18474 	} else {
18475 		ipst = CONNQ_TO_IPST(q);
18476 	}
18477 	ASSERT(ipst != NULL);
18478 	sctps = ipst->ips_netstack->netstack_sctp;
18479 
18480 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18481 		return (0);
18482 	}
18483 
18484 	/*
18485 	 * For the purposes of the (broken) packet shell use
18486 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18487 	 * to make TCP and UDP appear first in the list of mib items.
18488 	 * TBD: We could expand this and use it in netstat so that
18489 	 * the kernel doesn't have to produce large tables (connections,
18490 	 * routes, etc) when netstat only wants the statistics or a particular
18491 	 * table.
18492 	 */
18493 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18494 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18495 			return (1);
18496 		}
18497 	}
18498 
18499 	if (level != MIB2_TCP) {
18500 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18501 			return (1);
18502 		}
18503 	}
18504 
18505 	if (level != MIB2_UDP) {
18506 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18507 			return (1);
18508 		}
18509 	}
18510 
18511 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18512 	    ipst)) == NULL) {
18513 		return (1);
18514 	}
18515 
18516 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18517 		return (1);
18518 	}
18519 
18520 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18521 		return (1);
18522 	}
18523 
18524 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18525 		return (1);
18526 	}
18527 
18528 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18529 		return (1);
18530 	}
18531 
18532 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18533 		return (1);
18534 	}
18535 
18536 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18537 		return (1);
18538 	}
18539 
18540 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18541 		return (1);
18542 	}
18543 
18544 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18545 		return (1);
18546 	}
18547 
18548 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18549 		return (1);
18550 	}
18551 
18552 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18553 		return (1);
18554 	}
18555 
18556 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18557 		return (1);
18558 	}
18559 
18560 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18561 		return (1);
18562 	}
18563 
18564 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18565 		return (1);
18566 	}
18567 
18568 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18569 	if (mpctl == NULL)
18570 		return (1);
18571 
18572 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18573 	if (mpctl == NULL)
18574 		return (1);
18575 
18576 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18577 		return (1);
18578 	}
18579 	freemsg(mpctl);
18580 	return (1);
18581 }
18582 
18583 /* Get global (legacy) IPv4 statistics */
18584 static mblk_t *
18585 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18586     ip_stack_t *ipst)
18587 {
18588 	mib2_ip_t		old_ip_mib;
18589 	struct opthdr		*optp;
18590 	mblk_t			*mp2ctl;
18591 
18592 	/*
18593 	 * make a copy of the original message
18594 	 */
18595 	mp2ctl = copymsg(mpctl);
18596 
18597 	/* fixed length IP structure... */
18598 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18599 	optp->level = MIB2_IP;
18600 	optp->name = 0;
18601 	SET_MIB(old_ip_mib.ipForwarding,
18602 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18603 	SET_MIB(old_ip_mib.ipDefaultTTL,
18604 	    (uint32_t)ipst->ips_ip_def_ttl);
18605 	SET_MIB(old_ip_mib.ipReasmTimeout,
18606 	    ipst->ips_ip_g_frag_timeout);
18607 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18608 	    sizeof (mib2_ipAddrEntry_t));
18609 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18610 	    sizeof (mib2_ipRouteEntry_t));
18611 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18612 	    sizeof (mib2_ipNetToMediaEntry_t));
18613 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18614 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18615 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18616 	    sizeof (mib2_ipAttributeEntry_t));
18617 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18618 
18619 	/*
18620 	 * Grab the statistics from the new IP MIB
18621 	 */
18622 	SET_MIB(old_ip_mib.ipInReceives,
18623 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18624 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18625 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18626 	SET_MIB(old_ip_mib.ipForwDatagrams,
18627 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18628 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18629 	    ipmib->ipIfStatsInUnknownProtos);
18630 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18631 	SET_MIB(old_ip_mib.ipInDelivers,
18632 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18633 	SET_MIB(old_ip_mib.ipOutRequests,
18634 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18635 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18636 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18637 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18638 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18639 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18640 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18641 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18642 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18643 
18644 	/* ipRoutingDiscards is not being used */
18645 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18646 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18647 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18648 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18649 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18650 	    ipmib->ipIfStatsReasmDuplicates);
18651 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18652 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18653 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18654 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18655 	SET_MIB(old_ip_mib.rawipInOverflows,
18656 	    ipmib->rawipIfStatsInOverflows);
18657 
18658 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18659 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18660 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18661 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18662 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18663 	    ipmib->ipIfStatsOutSwitchIPVersion);
18664 
18665 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18666 	    (int)sizeof (old_ip_mib))) {
18667 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18668 		    (uint_t)sizeof (old_ip_mib)));
18669 	}
18670 
18671 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18672 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18673 	    (int)optp->level, (int)optp->name, (int)optp->len));
18674 	qreply(q, mpctl);
18675 	return (mp2ctl);
18676 }
18677 
18678 /* Per interface IPv4 statistics */
18679 static mblk_t *
18680 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18681 {
18682 	struct opthdr		*optp;
18683 	mblk_t			*mp2ctl;
18684 	ill_t			*ill;
18685 	ill_walk_context_t	ctx;
18686 	mblk_t			*mp_tail = NULL;
18687 	mib2_ipIfStatsEntry_t	global_ip_mib;
18688 
18689 	/*
18690 	 * Make a copy of the original message
18691 	 */
18692 	mp2ctl = copymsg(mpctl);
18693 
18694 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18695 	optp->level = MIB2_IP;
18696 	optp->name = MIB2_IP_TRAFFIC_STATS;
18697 	/* Include "unknown interface" ip_mib */
18698 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18699 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18700 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18701 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18702 	    (ipst->ips_ip_g_forward ? 1 : 2));
18703 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18704 	    (uint32_t)ipst->ips_ip_def_ttl);
18705 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18706 	    sizeof (mib2_ipIfStatsEntry_t));
18707 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18708 	    sizeof (mib2_ipAddrEntry_t));
18709 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18710 	    sizeof (mib2_ipRouteEntry_t));
18711 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18712 	    sizeof (mib2_ipNetToMediaEntry_t));
18713 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18714 	    sizeof (ip_member_t));
18715 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18716 	    sizeof (ip_grpsrc_t));
18717 
18718 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18719 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18720 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18721 		    "failed to allocate %u bytes\n",
18722 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18723 	}
18724 
18725 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18726 
18727 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18728 	ill = ILL_START_WALK_V4(&ctx, ipst);
18729 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18730 		ill->ill_ip_mib->ipIfStatsIfIndex =
18731 		    ill->ill_phyint->phyint_ifindex;
18732 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18733 		    (ipst->ips_ip_g_forward ? 1 : 2));
18734 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18735 		    (uint32_t)ipst->ips_ip_def_ttl);
18736 
18737 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18738 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18739 		    (char *)ill->ill_ip_mib,
18740 		    (int)sizeof (*ill->ill_ip_mib))) {
18741 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18742 			    "failed to allocate %u bytes\n",
18743 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18744 		}
18745 	}
18746 	rw_exit(&ipst->ips_ill_g_lock);
18747 
18748 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18749 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18750 	    "level %d, name %d, len %d\n",
18751 	    (int)optp->level, (int)optp->name, (int)optp->len));
18752 	qreply(q, mpctl);
18753 
18754 	if (mp2ctl == NULL)
18755 		return (NULL);
18756 
18757 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18758 }
18759 
18760 /* Global IPv4 ICMP statistics */
18761 static mblk_t *
18762 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18763 {
18764 	struct opthdr		*optp;
18765 	mblk_t			*mp2ctl;
18766 
18767 	/*
18768 	 * Make a copy of the original message
18769 	 */
18770 	mp2ctl = copymsg(mpctl);
18771 
18772 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18773 	optp->level = MIB2_ICMP;
18774 	optp->name = 0;
18775 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18776 	    (int)sizeof (ipst->ips_icmp_mib))) {
18777 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18778 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18779 	}
18780 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18781 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18782 	    (int)optp->level, (int)optp->name, (int)optp->len));
18783 	qreply(q, mpctl);
18784 	return (mp2ctl);
18785 }
18786 
18787 /* Global IPv4 IGMP statistics */
18788 static mblk_t *
18789 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18790 {
18791 	struct opthdr		*optp;
18792 	mblk_t			*mp2ctl;
18793 
18794 	/*
18795 	 * make a copy of the original message
18796 	 */
18797 	mp2ctl = copymsg(mpctl);
18798 
18799 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18800 	optp->level = EXPER_IGMP;
18801 	optp->name = 0;
18802 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18803 	    (int)sizeof (ipst->ips_igmpstat))) {
18804 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18805 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18806 	}
18807 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18808 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18809 	    (int)optp->level, (int)optp->name, (int)optp->len));
18810 	qreply(q, mpctl);
18811 	return (mp2ctl);
18812 }
18813 
18814 /* Global IPv4 Multicast Routing statistics */
18815 static mblk_t *
18816 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18817 {
18818 	struct opthdr		*optp;
18819 	mblk_t			*mp2ctl;
18820 
18821 	/*
18822 	 * make a copy of the original message
18823 	 */
18824 	mp2ctl = copymsg(mpctl);
18825 
18826 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18827 	optp->level = EXPER_DVMRP;
18828 	optp->name = 0;
18829 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18830 		ip0dbg(("ip_mroute_stats: failed\n"));
18831 	}
18832 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18833 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18834 	    (int)optp->level, (int)optp->name, (int)optp->len));
18835 	qreply(q, mpctl);
18836 	return (mp2ctl);
18837 }
18838 
18839 /* IPv4 address information */
18840 static mblk_t *
18841 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18842 {
18843 	struct opthdr		*optp;
18844 	mblk_t			*mp2ctl;
18845 	mblk_t			*mp_tail = NULL;
18846 	ill_t			*ill;
18847 	ipif_t			*ipif;
18848 	uint_t			bitval;
18849 	mib2_ipAddrEntry_t	mae;
18850 	zoneid_t		zoneid;
18851 	ill_walk_context_t ctx;
18852 
18853 	/*
18854 	 * make a copy of the original message
18855 	 */
18856 	mp2ctl = copymsg(mpctl);
18857 
18858 	/* ipAddrEntryTable */
18859 
18860 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18861 	optp->level = MIB2_IP;
18862 	optp->name = MIB2_IP_ADDR;
18863 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18864 
18865 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18866 	ill = ILL_START_WALK_V4(&ctx, ipst);
18867 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18868 		for (ipif = ill->ill_ipif; ipif != NULL;
18869 		    ipif = ipif->ipif_next) {
18870 			if (ipif->ipif_zoneid != zoneid &&
18871 			    ipif->ipif_zoneid != ALL_ZONES)
18872 				continue;
18873 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18874 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18875 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18876 
18877 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18878 			    OCTET_LENGTH);
18879 			mae.ipAdEntIfIndex.o_length =
18880 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18881 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18882 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18883 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18884 			mae.ipAdEntInfo.ae_subnet_len =
18885 			    ip_mask_to_plen(ipif->ipif_net_mask);
18886 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18887 			for (bitval = 1;
18888 			    bitval &&
18889 			    !(bitval & ipif->ipif_brd_addr);
18890 			    bitval <<= 1)
18891 				noop;
18892 			mae.ipAdEntBcastAddr = bitval;
18893 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18894 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18895 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18896 			mae.ipAdEntInfo.ae_broadcast_addr =
18897 			    ipif->ipif_brd_addr;
18898 			mae.ipAdEntInfo.ae_pp_dst_addr =
18899 			    ipif->ipif_pp_dst_addr;
18900 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18901 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18902 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18903 
18904 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18905 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18906 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18907 				    "allocate %u bytes\n",
18908 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18909 			}
18910 		}
18911 	}
18912 	rw_exit(&ipst->ips_ill_g_lock);
18913 
18914 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18915 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18916 	    (int)optp->level, (int)optp->name, (int)optp->len));
18917 	qreply(q, mpctl);
18918 	return (mp2ctl);
18919 }
18920 
18921 /* IPv6 address information */
18922 static mblk_t *
18923 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18924 {
18925 	struct opthdr		*optp;
18926 	mblk_t			*mp2ctl;
18927 	mblk_t			*mp_tail = NULL;
18928 	ill_t			*ill;
18929 	ipif_t			*ipif;
18930 	mib2_ipv6AddrEntry_t	mae6;
18931 	zoneid_t		zoneid;
18932 	ill_walk_context_t	ctx;
18933 
18934 	/*
18935 	 * make a copy of the original message
18936 	 */
18937 	mp2ctl = copymsg(mpctl);
18938 
18939 	/* ipv6AddrEntryTable */
18940 
18941 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18942 	optp->level = MIB2_IP6;
18943 	optp->name = MIB2_IP6_ADDR;
18944 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18945 
18946 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18947 	ill = ILL_START_WALK_V6(&ctx, ipst);
18948 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18949 		for (ipif = ill->ill_ipif; ipif != NULL;
18950 		    ipif = ipif->ipif_next) {
18951 			if (ipif->ipif_zoneid != zoneid &&
18952 			    ipif->ipif_zoneid != ALL_ZONES)
18953 				continue;
18954 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18955 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18956 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18957 
18958 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18959 			    OCTET_LENGTH);
18960 			mae6.ipv6AddrIfIndex.o_length =
18961 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18962 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18963 			mae6.ipv6AddrPfxLength =
18964 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18965 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18966 			mae6.ipv6AddrInfo.ae_subnet_len =
18967 			    mae6.ipv6AddrPfxLength;
18968 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18969 
18970 			/* Type: stateless(1), stateful(2), unknown(3) */
18971 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18972 				mae6.ipv6AddrType = 1;
18973 			else
18974 				mae6.ipv6AddrType = 2;
18975 			/* Anycast: true(1), false(2) */
18976 			if (ipif->ipif_flags & IPIF_ANYCAST)
18977 				mae6.ipv6AddrAnycastFlag = 1;
18978 			else
18979 				mae6.ipv6AddrAnycastFlag = 2;
18980 
18981 			/*
18982 			 * Address status: preferred(1), deprecated(2),
18983 			 * invalid(3), inaccessible(4), unknown(5)
18984 			 */
18985 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18986 				mae6.ipv6AddrStatus = 3;
18987 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18988 				mae6.ipv6AddrStatus = 2;
18989 			else
18990 				mae6.ipv6AddrStatus = 1;
18991 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18992 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18993 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18994 			    ipif->ipif_v6pp_dst_addr;
18995 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18996 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18997 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18998 			mae6.ipv6AddrIdentifier = ill->ill_token;
18999 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
19000 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
19001 			mae6.ipv6AddrRetransmitTime =
19002 			    ill->ill_reachable_retrans_time;
19003 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19004 			    (char *)&mae6,
19005 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
19006 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
19007 				    "allocate %u bytes\n",
19008 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
19009 			}
19010 		}
19011 	}
19012 	rw_exit(&ipst->ips_ill_g_lock);
19013 
19014 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19015 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
19016 	    (int)optp->level, (int)optp->name, (int)optp->len));
19017 	qreply(q, mpctl);
19018 	return (mp2ctl);
19019 }
19020 
19021 /* IPv4 multicast group membership. */
19022 static mblk_t *
19023 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19024 {
19025 	struct opthdr		*optp;
19026 	mblk_t			*mp2ctl;
19027 	ill_t			*ill;
19028 	ipif_t			*ipif;
19029 	ilm_t			*ilm;
19030 	ip_member_t		ipm;
19031 	mblk_t			*mp_tail = NULL;
19032 	ill_walk_context_t	ctx;
19033 	zoneid_t		zoneid;
19034 	ilm_walker_t		ilw;
19035 
19036 	/*
19037 	 * make a copy of the original message
19038 	 */
19039 	mp2ctl = copymsg(mpctl);
19040 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19041 
19042 	/* ipGroupMember table */
19043 	optp = (struct opthdr *)&mpctl->b_rptr[
19044 	    sizeof (struct T_optmgmt_ack)];
19045 	optp->level = MIB2_IP;
19046 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
19047 
19048 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19049 	ill = ILL_START_WALK_V4(&ctx, ipst);
19050 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19051 		if (IS_UNDER_IPMP(ill))
19052 			continue;
19053 
19054 		ilm = ilm_walker_start(&ilw, ill);
19055 		for (ipif = ill->ill_ipif; ipif != NULL;
19056 		    ipif = ipif->ipif_next) {
19057 			if (ipif->ipif_zoneid != zoneid &&
19058 			    ipif->ipif_zoneid != ALL_ZONES)
19059 				continue;	/* not this zone */
19060 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
19061 			    OCTET_LENGTH);
19062 			ipm.ipGroupMemberIfIndex.o_length =
19063 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
19064 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19065 				ASSERT(ilm->ilm_ipif != NULL);
19066 				ASSERT(ilm->ilm_ill == NULL);
19067 				if (ilm->ilm_ipif != ipif)
19068 					continue;
19069 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
19070 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
19071 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
19072 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19073 				    (char *)&ipm, (int)sizeof (ipm))) {
19074 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
19075 					    "failed to allocate %u bytes\n",
19076 					    (uint_t)sizeof (ipm)));
19077 				}
19078 			}
19079 		}
19080 		ilm_walker_finish(&ilw);
19081 	}
19082 	rw_exit(&ipst->ips_ill_g_lock);
19083 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19084 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19085 	    (int)optp->level, (int)optp->name, (int)optp->len));
19086 	qreply(q, mpctl);
19087 	return (mp2ctl);
19088 }
19089 
19090 /* IPv6 multicast group membership. */
19091 static mblk_t *
19092 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19093 {
19094 	struct opthdr		*optp;
19095 	mblk_t			*mp2ctl;
19096 	ill_t			*ill;
19097 	ilm_t			*ilm;
19098 	ipv6_member_t		ipm6;
19099 	mblk_t			*mp_tail = NULL;
19100 	ill_walk_context_t	ctx;
19101 	zoneid_t		zoneid;
19102 	ilm_walker_t		ilw;
19103 
19104 	/*
19105 	 * make a copy of the original message
19106 	 */
19107 	mp2ctl = copymsg(mpctl);
19108 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19109 
19110 	/* ip6GroupMember table */
19111 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19112 	optp->level = MIB2_IP6;
19113 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19114 
19115 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19116 	ill = ILL_START_WALK_V6(&ctx, ipst);
19117 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19118 		if (IS_UNDER_IPMP(ill))
19119 			continue;
19120 
19121 		ilm = ilm_walker_start(&ilw, ill);
19122 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19123 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19124 			ASSERT(ilm->ilm_ipif == NULL);
19125 			ASSERT(ilm->ilm_ill != NULL);
19126 			if (ilm->ilm_zoneid != zoneid)
19127 				continue;	/* not this zone */
19128 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19129 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19130 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19131 			if (!snmp_append_data2(mpctl->b_cont,
19132 			    &mp_tail,
19133 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19134 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19135 				    "failed to allocate %u bytes\n",
19136 				    (uint_t)sizeof (ipm6)));
19137 			}
19138 		}
19139 		ilm_walker_finish(&ilw);
19140 	}
19141 	rw_exit(&ipst->ips_ill_g_lock);
19142 
19143 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19144 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19145 	    (int)optp->level, (int)optp->name, (int)optp->len));
19146 	qreply(q, mpctl);
19147 	return (mp2ctl);
19148 }
19149 
19150 /* IP multicast filtered sources */
19151 static mblk_t *
19152 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19153 {
19154 	struct opthdr		*optp;
19155 	mblk_t			*mp2ctl;
19156 	ill_t			*ill;
19157 	ipif_t			*ipif;
19158 	ilm_t			*ilm;
19159 	ip_grpsrc_t		ips;
19160 	mblk_t			*mp_tail = NULL;
19161 	ill_walk_context_t	ctx;
19162 	zoneid_t		zoneid;
19163 	int			i;
19164 	slist_t			*sl;
19165 	ilm_walker_t		ilw;
19166 
19167 	/*
19168 	 * make a copy of the original message
19169 	 */
19170 	mp2ctl = copymsg(mpctl);
19171 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19172 
19173 	/* ipGroupSource table */
19174 	optp = (struct opthdr *)&mpctl->b_rptr[
19175 	    sizeof (struct T_optmgmt_ack)];
19176 	optp->level = MIB2_IP;
19177 	optp->name = EXPER_IP_GROUP_SOURCES;
19178 
19179 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19180 	ill = ILL_START_WALK_V4(&ctx, ipst);
19181 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19182 		if (IS_UNDER_IPMP(ill))
19183 			continue;
19184 
19185 		ilm = ilm_walker_start(&ilw, ill);
19186 		for (ipif = ill->ill_ipif; ipif != NULL;
19187 		    ipif = ipif->ipif_next) {
19188 			if (ipif->ipif_zoneid != zoneid)
19189 				continue;	/* not this zone */
19190 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19191 			    OCTET_LENGTH);
19192 			ips.ipGroupSourceIfIndex.o_length =
19193 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19194 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19195 				ASSERT(ilm->ilm_ipif != NULL);
19196 				ASSERT(ilm->ilm_ill == NULL);
19197 				sl = ilm->ilm_filter;
19198 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19199 					continue;
19200 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19201 				for (i = 0; i < sl->sl_numsrc; i++) {
19202 					if (!IN6_IS_ADDR_V4MAPPED(
19203 					    &sl->sl_addr[i]))
19204 						continue;
19205 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19206 					    ips.ipGroupSourceAddress);
19207 					if (snmp_append_data2(mpctl->b_cont,
19208 					    &mp_tail, (char *)&ips,
19209 					    (int)sizeof (ips)) == 0) {
19210 						ip1dbg(("ip_snmp_get_mib2_"
19211 						    "ip_group_src: failed to "
19212 						    "allocate %u bytes\n",
19213 						    (uint_t)sizeof (ips)));
19214 					}
19215 				}
19216 			}
19217 		}
19218 		ilm_walker_finish(&ilw);
19219 	}
19220 	rw_exit(&ipst->ips_ill_g_lock);
19221 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19222 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19223 	    (int)optp->level, (int)optp->name, (int)optp->len));
19224 	qreply(q, mpctl);
19225 	return (mp2ctl);
19226 }
19227 
19228 /* IPv6 multicast filtered sources. */
19229 static mblk_t *
19230 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19231 {
19232 	struct opthdr		*optp;
19233 	mblk_t			*mp2ctl;
19234 	ill_t			*ill;
19235 	ilm_t			*ilm;
19236 	ipv6_grpsrc_t		ips6;
19237 	mblk_t			*mp_tail = NULL;
19238 	ill_walk_context_t	ctx;
19239 	zoneid_t		zoneid;
19240 	int			i;
19241 	slist_t			*sl;
19242 	ilm_walker_t		ilw;
19243 
19244 	/*
19245 	 * make a copy of the original message
19246 	 */
19247 	mp2ctl = copymsg(mpctl);
19248 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19249 
19250 	/* ip6GroupMember table */
19251 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19252 	optp->level = MIB2_IP6;
19253 	optp->name = EXPER_IP6_GROUP_SOURCES;
19254 
19255 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19256 	ill = ILL_START_WALK_V6(&ctx, ipst);
19257 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19258 		if (IS_UNDER_IPMP(ill))
19259 			continue;
19260 
19261 		ilm = ilm_walker_start(&ilw, ill);
19262 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19263 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19264 			ASSERT(ilm->ilm_ipif == NULL);
19265 			ASSERT(ilm->ilm_ill != NULL);
19266 			sl = ilm->ilm_filter;
19267 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19268 				continue;
19269 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19270 			for (i = 0; i < sl->sl_numsrc; i++) {
19271 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19272 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19273 				    (char *)&ips6, (int)sizeof (ips6))) {
19274 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19275 					    "group_src: failed to allocate "
19276 					    "%u bytes\n",
19277 					    (uint_t)sizeof (ips6)));
19278 				}
19279 			}
19280 		}
19281 		ilm_walker_finish(&ilw);
19282 	}
19283 	rw_exit(&ipst->ips_ill_g_lock);
19284 
19285 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19286 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19287 	    (int)optp->level, (int)optp->name, (int)optp->len));
19288 	qreply(q, mpctl);
19289 	return (mp2ctl);
19290 }
19291 
19292 /* Multicast routing virtual interface table. */
19293 static mblk_t *
19294 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19295 {
19296 	struct opthdr		*optp;
19297 	mblk_t			*mp2ctl;
19298 
19299 	/*
19300 	 * make a copy of the original message
19301 	 */
19302 	mp2ctl = copymsg(mpctl);
19303 
19304 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19305 	optp->level = EXPER_DVMRP;
19306 	optp->name = EXPER_DVMRP_VIF;
19307 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19308 		ip0dbg(("ip_mroute_vif: failed\n"));
19309 	}
19310 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19311 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19312 	    (int)optp->level, (int)optp->name, (int)optp->len));
19313 	qreply(q, mpctl);
19314 	return (mp2ctl);
19315 }
19316 
19317 /* Multicast routing table. */
19318 static mblk_t *
19319 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19320 {
19321 	struct opthdr		*optp;
19322 	mblk_t			*mp2ctl;
19323 
19324 	/*
19325 	 * make a copy of the original message
19326 	 */
19327 	mp2ctl = copymsg(mpctl);
19328 
19329 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19330 	optp->level = EXPER_DVMRP;
19331 	optp->name = EXPER_DVMRP_MRT;
19332 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19333 		ip0dbg(("ip_mroute_mrt: failed\n"));
19334 	}
19335 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19336 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19337 	    (int)optp->level, (int)optp->name, (int)optp->len));
19338 	qreply(q, mpctl);
19339 	return (mp2ctl);
19340 }
19341 
19342 /*
19343  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19344  * in one IRE walk.
19345  */
19346 static mblk_t *
19347 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19348     ip_stack_t *ipst)
19349 {
19350 	struct opthdr	*optp;
19351 	mblk_t		*mp2ctl;	/* Returned */
19352 	mblk_t		*mp3ctl;	/* nettomedia */
19353 	mblk_t		*mp4ctl;	/* routeattrs */
19354 	iproutedata_t	ird;
19355 	zoneid_t	zoneid;
19356 
19357 	/*
19358 	 * make copies of the original message
19359 	 *	- mp2ctl is returned unchanged to the caller for his use
19360 	 *	- mpctl is sent upstream as ipRouteEntryTable
19361 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19362 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19363 	 */
19364 	mp2ctl = copymsg(mpctl);
19365 	mp3ctl = copymsg(mpctl);
19366 	mp4ctl = copymsg(mpctl);
19367 	if (mp3ctl == NULL || mp4ctl == NULL) {
19368 		freemsg(mp4ctl);
19369 		freemsg(mp3ctl);
19370 		freemsg(mp2ctl);
19371 		freemsg(mpctl);
19372 		return (NULL);
19373 	}
19374 
19375 	bzero(&ird, sizeof (ird));
19376 
19377 	ird.ird_route.lp_head = mpctl->b_cont;
19378 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19379 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19380 	/*
19381 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19382 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19383 	 * intended a temporary solution until a proper MIB API is provided
19384 	 * that provides complete filtering/caller-opt-in.
19385 	 */
19386 	if (level == EXPER_IP_AND_TESTHIDDEN)
19387 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19388 
19389 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19390 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19391 
19392 	/* ipRouteEntryTable in mpctl */
19393 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19394 	optp->level = MIB2_IP;
19395 	optp->name = MIB2_IP_ROUTE;
19396 	optp->len = msgdsize(ird.ird_route.lp_head);
19397 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19398 	    (int)optp->level, (int)optp->name, (int)optp->len));
19399 	qreply(q, mpctl);
19400 
19401 	/* ipNetToMediaEntryTable in mp3ctl */
19402 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19403 	optp->level = MIB2_IP;
19404 	optp->name = MIB2_IP_MEDIA;
19405 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19406 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19407 	    (int)optp->level, (int)optp->name, (int)optp->len));
19408 	qreply(q, mp3ctl);
19409 
19410 	/* ipRouteAttributeTable in mp4ctl */
19411 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19412 	optp->level = MIB2_IP;
19413 	optp->name = EXPER_IP_RTATTR;
19414 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19415 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19416 	    (int)optp->level, (int)optp->name, (int)optp->len));
19417 	if (optp->len == 0)
19418 		freemsg(mp4ctl);
19419 	else
19420 		qreply(q, mp4ctl);
19421 
19422 	return (mp2ctl);
19423 }
19424 
19425 /*
19426  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19427  * ipv6NetToMediaEntryTable in an NDP walk.
19428  */
19429 static mblk_t *
19430 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19431     ip_stack_t *ipst)
19432 {
19433 	struct opthdr	*optp;
19434 	mblk_t		*mp2ctl;	/* Returned */
19435 	mblk_t		*mp3ctl;	/* nettomedia */
19436 	mblk_t		*mp4ctl;	/* routeattrs */
19437 	iproutedata_t	ird;
19438 	zoneid_t	zoneid;
19439 
19440 	/*
19441 	 * make copies of the original message
19442 	 *	- mp2ctl is returned unchanged to the caller for his use
19443 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19444 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19445 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19446 	 */
19447 	mp2ctl = copymsg(mpctl);
19448 	mp3ctl = copymsg(mpctl);
19449 	mp4ctl = copymsg(mpctl);
19450 	if (mp3ctl == NULL || mp4ctl == NULL) {
19451 		freemsg(mp4ctl);
19452 		freemsg(mp3ctl);
19453 		freemsg(mp2ctl);
19454 		freemsg(mpctl);
19455 		return (NULL);
19456 	}
19457 
19458 	bzero(&ird, sizeof (ird));
19459 
19460 	ird.ird_route.lp_head = mpctl->b_cont;
19461 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19462 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19463 	/*
19464 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19465 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19466 	 * intended a temporary solution until a proper MIB API is provided
19467 	 * that provides complete filtering/caller-opt-in.
19468 	 */
19469 	if (level == EXPER_IP_AND_TESTHIDDEN)
19470 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19471 
19472 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19473 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19474 
19475 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19476 	optp->level = MIB2_IP6;
19477 	optp->name = MIB2_IP6_ROUTE;
19478 	optp->len = msgdsize(ird.ird_route.lp_head);
19479 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19480 	    (int)optp->level, (int)optp->name, (int)optp->len));
19481 	qreply(q, mpctl);
19482 
19483 	/* ipv6NetToMediaEntryTable in mp3ctl */
19484 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19485 
19486 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19487 	optp->level = MIB2_IP6;
19488 	optp->name = MIB2_IP6_MEDIA;
19489 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19490 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19491 	    (int)optp->level, (int)optp->name, (int)optp->len));
19492 	qreply(q, mp3ctl);
19493 
19494 	/* ipv6RouteAttributeTable in mp4ctl */
19495 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19496 	optp->level = MIB2_IP6;
19497 	optp->name = EXPER_IP_RTATTR;
19498 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19499 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19500 	    (int)optp->level, (int)optp->name, (int)optp->len));
19501 	if (optp->len == 0)
19502 		freemsg(mp4ctl);
19503 	else
19504 		qreply(q, mp4ctl);
19505 
19506 	return (mp2ctl);
19507 }
19508 
19509 /*
19510  * IPv6 mib: One per ill
19511  */
19512 static mblk_t *
19513 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19514 {
19515 	struct opthdr		*optp;
19516 	mblk_t			*mp2ctl;
19517 	ill_t			*ill;
19518 	ill_walk_context_t	ctx;
19519 	mblk_t			*mp_tail = NULL;
19520 
19521 	/*
19522 	 * Make a copy of the original message
19523 	 */
19524 	mp2ctl = copymsg(mpctl);
19525 
19526 	/* fixed length IPv6 structure ... */
19527 
19528 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19529 	optp->level = MIB2_IP6;
19530 	optp->name = 0;
19531 	/* Include "unknown interface" ip6_mib */
19532 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19533 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19534 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19535 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19536 	    ipst->ips_ipv6_forward ? 1 : 2);
19537 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19538 	    ipst->ips_ipv6_def_hops);
19539 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19540 	    sizeof (mib2_ipIfStatsEntry_t));
19541 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19542 	    sizeof (mib2_ipv6AddrEntry_t));
19543 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19544 	    sizeof (mib2_ipv6RouteEntry_t));
19545 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19546 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19547 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19548 	    sizeof (ipv6_member_t));
19549 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19550 	    sizeof (ipv6_grpsrc_t));
19551 
19552 	/*
19553 	 * Synchronize 64- and 32-bit counters
19554 	 */
19555 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19556 	    ipIfStatsHCInReceives);
19557 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19558 	    ipIfStatsHCInDelivers);
19559 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19560 	    ipIfStatsHCOutRequests);
19561 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19562 	    ipIfStatsHCOutForwDatagrams);
19563 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19564 	    ipIfStatsHCOutMcastPkts);
19565 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19566 	    ipIfStatsHCInMcastPkts);
19567 
19568 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19569 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19570 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19571 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19572 	}
19573 
19574 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19575 	ill = ILL_START_WALK_V6(&ctx, ipst);
19576 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19577 		ill->ill_ip_mib->ipIfStatsIfIndex =
19578 		    ill->ill_phyint->phyint_ifindex;
19579 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19580 		    ipst->ips_ipv6_forward ? 1 : 2);
19581 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19582 		    ill->ill_max_hops);
19583 
19584 		/*
19585 		 * Synchronize 64- and 32-bit counters
19586 		 */
19587 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19588 		    ipIfStatsHCInReceives);
19589 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19590 		    ipIfStatsHCInDelivers);
19591 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19592 		    ipIfStatsHCOutRequests);
19593 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19594 		    ipIfStatsHCOutForwDatagrams);
19595 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19596 		    ipIfStatsHCOutMcastPkts);
19597 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19598 		    ipIfStatsHCInMcastPkts);
19599 
19600 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19601 		    (char *)ill->ill_ip_mib,
19602 		    (int)sizeof (*ill->ill_ip_mib))) {
19603 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19604 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19605 		}
19606 	}
19607 	rw_exit(&ipst->ips_ill_g_lock);
19608 
19609 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19610 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19611 	    (int)optp->level, (int)optp->name, (int)optp->len));
19612 	qreply(q, mpctl);
19613 	return (mp2ctl);
19614 }
19615 
19616 /*
19617  * ICMPv6 mib: One per ill
19618  */
19619 static mblk_t *
19620 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19621 {
19622 	struct opthdr		*optp;
19623 	mblk_t			*mp2ctl;
19624 	ill_t			*ill;
19625 	ill_walk_context_t	ctx;
19626 	mblk_t			*mp_tail = NULL;
19627 	/*
19628 	 * Make a copy of the original message
19629 	 */
19630 	mp2ctl = copymsg(mpctl);
19631 
19632 	/* fixed length ICMPv6 structure ... */
19633 
19634 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19635 	optp->level = MIB2_ICMP6;
19636 	optp->name = 0;
19637 	/* Include "unknown interface" icmp6_mib */
19638 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19639 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19640 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19641 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19642 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19643 	    (char *)&ipst->ips_icmp6_mib,
19644 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19645 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19646 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19647 	}
19648 
19649 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19650 	ill = ILL_START_WALK_V6(&ctx, ipst);
19651 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19652 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19653 		    ill->ill_phyint->phyint_ifindex;
19654 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19655 		    (char *)ill->ill_icmp6_mib,
19656 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19657 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19658 			    "%u bytes\n",
19659 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19660 		}
19661 	}
19662 	rw_exit(&ipst->ips_ill_g_lock);
19663 
19664 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19665 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19666 	    (int)optp->level, (int)optp->name, (int)optp->len));
19667 	qreply(q, mpctl);
19668 	return (mp2ctl);
19669 }
19670 
19671 /*
19672  * ire_walk routine to create both ipRouteEntryTable and
19673  * ipRouteAttributeTable in one IRE walk
19674  */
19675 static void
19676 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19677 {
19678 	ill_t				*ill;
19679 	ipif_t				*ipif;
19680 	mib2_ipRouteEntry_t		*re;
19681 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19682 	ipaddr_t			gw_addr;
19683 	tsol_ire_gw_secattr_t		*attrp;
19684 	tsol_gc_t			*gc = NULL;
19685 	tsol_gcgrp_t			*gcgrp = NULL;
19686 	uint_t				sacnt = 0;
19687 	int				i;
19688 
19689 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19690 
19691 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19692 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19693 		return;
19694 	}
19695 
19696 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19697 		return;
19698 
19699 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19700 		mutex_enter(&attrp->igsa_lock);
19701 		if ((gc = attrp->igsa_gc) != NULL) {
19702 			gcgrp = gc->gc_grp;
19703 			ASSERT(gcgrp != NULL);
19704 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19705 			sacnt = 1;
19706 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19707 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19708 			gc = gcgrp->gcgrp_head;
19709 			sacnt = gcgrp->gcgrp_count;
19710 		}
19711 		mutex_exit(&attrp->igsa_lock);
19712 
19713 		/* do nothing if there's no gc to report */
19714 		if (gc == NULL) {
19715 			ASSERT(sacnt == 0);
19716 			if (gcgrp != NULL) {
19717 				/* we might as well drop the lock now */
19718 				rw_exit(&gcgrp->gcgrp_rwlock);
19719 				gcgrp = NULL;
19720 			}
19721 			attrp = NULL;
19722 		}
19723 
19724 		ASSERT(gc == NULL || (gcgrp != NULL &&
19725 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19726 	}
19727 	ASSERT(sacnt == 0 || gc != NULL);
19728 
19729 	if (sacnt != 0 &&
19730 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19731 		kmem_free(re, sizeof (*re));
19732 		rw_exit(&gcgrp->gcgrp_rwlock);
19733 		return;
19734 	}
19735 
19736 	/*
19737 	 * Return all IRE types for route table... let caller pick and choose
19738 	 */
19739 	re->ipRouteDest = ire->ire_addr;
19740 	ipif = ire->ire_ipif;
19741 	re->ipRouteIfIndex.o_length = 0;
19742 	if (ire->ire_type == IRE_CACHE) {
19743 		ill = (ill_t *)ire->ire_stq->q_ptr;
19744 		re->ipRouteIfIndex.o_length =
19745 		    ill->ill_name_length == 0 ? 0 :
19746 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19747 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19748 		    re->ipRouteIfIndex.o_length);
19749 	} else if (ipif != NULL) {
19750 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19751 		re->ipRouteIfIndex.o_length =
19752 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19753 	}
19754 	re->ipRouteMetric1 = -1;
19755 	re->ipRouteMetric2 = -1;
19756 	re->ipRouteMetric3 = -1;
19757 	re->ipRouteMetric4 = -1;
19758 
19759 	gw_addr = ire->ire_gateway_addr;
19760 
19761 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19762 		re->ipRouteNextHop = ire->ire_src_addr;
19763 	else
19764 		re->ipRouteNextHop = gw_addr;
19765 	/* indirect(4), direct(3), or invalid(2) */
19766 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19767 		re->ipRouteType = 2;
19768 	else
19769 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19770 	re->ipRouteProto = -1;
19771 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19772 	re->ipRouteMask = ire->ire_mask;
19773 	re->ipRouteMetric5 = -1;
19774 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19775 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19776 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19777 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19778 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19779 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19780 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19781 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19782 
19783 	if (ire->ire_flags & RTF_DYNAMIC) {
19784 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19785 	} else {
19786 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19787 	}
19788 
19789 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19790 	    (char *)re, (int)sizeof (*re))) {
19791 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19792 		    (uint_t)sizeof (*re)));
19793 	}
19794 
19795 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19796 		iaeptr->iae_routeidx = ird->ird_idx;
19797 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19798 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19799 	}
19800 
19801 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19802 	    (char *)iae, sacnt * sizeof (*iae))) {
19803 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19804 		    (unsigned)(sacnt * sizeof (*iae))));
19805 	}
19806 
19807 	/* bump route index for next pass */
19808 	ird->ird_idx++;
19809 
19810 	kmem_free(re, sizeof (*re));
19811 	if (sacnt != 0)
19812 		kmem_free(iae, sacnt * sizeof (*iae));
19813 
19814 	if (gcgrp != NULL)
19815 		rw_exit(&gcgrp->gcgrp_rwlock);
19816 }
19817 
19818 /*
19819  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19820  */
19821 static void
19822 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19823 {
19824 	ill_t				*ill;
19825 	ipif_t				*ipif;
19826 	mib2_ipv6RouteEntry_t		*re;
19827 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19828 	in6_addr_t			gw_addr_v6;
19829 	tsol_ire_gw_secattr_t		*attrp;
19830 	tsol_gc_t			*gc = NULL;
19831 	tsol_gcgrp_t			*gcgrp = NULL;
19832 	uint_t				sacnt = 0;
19833 	int				i;
19834 
19835 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19836 
19837 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19838 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19839 		return;
19840 	}
19841 
19842 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19843 		return;
19844 
19845 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19846 		mutex_enter(&attrp->igsa_lock);
19847 		if ((gc = attrp->igsa_gc) != NULL) {
19848 			gcgrp = gc->gc_grp;
19849 			ASSERT(gcgrp != NULL);
19850 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19851 			sacnt = 1;
19852 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19853 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19854 			gc = gcgrp->gcgrp_head;
19855 			sacnt = gcgrp->gcgrp_count;
19856 		}
19857 		mutex_exit(&attrp->igsa_lock);
19858 
19859 		/* do nothing if there's no gc to report */
19860 		if (gc == NULL) {
19861 			ASSERT(sacnt == 0);
19862 			if (gcgrp != NULL) {
19863 				/* we might as well drop the lock now */
19864 				rw_exit(&gcgrp->gcgrp_rwlock);
19865 				gcgrp = NULL;
19866 			}
19867 			attrp = NULL;
19868 		}
19869 
19870 		ASSERT(gc == NULL || (gcgrp != NULL &&
19871 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19872 	}
19873 	ASSERT(sacnt == 0 || gc != NULL);
19874 
19875 	if (sacnt != 0 &&
19876 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19877 		kmem_free(re, sizeof (*re));
19878 		rw_exit(&gcgrp->gcgrp_rwlock);
19879 		return;
19880 	}
19881 
19882 	/*
19883 	 * Return all IRE types for route table... let caller pick and choose
19884 	 */
19885 	re->ipv6RouteDest = ire->ire_addr_v6;
19886 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19887 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19888 	re->ipv6RouteIfIndex.o_length = 0;
19889 	ipif = ire->ire_ipif;
19890 	if (ire->ire_type == IRE_CACHE) {
19891 		ill = (ill_t *)ire->ire_stq->q_ptr;
19892 		re->ipv6RouteIfIndex.o_length =
19893 		    ill->ill_name_length == 0 ? 0 :
19894 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19895 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19896 		    re->ipv6RouteIfIndex.o_length);
19897 	} else if (ipif != NULL) {
19898 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19899 		re->ipv6RouteIfIndex.o_length =
19900 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19901 	}
19902 
19903 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19904 
19905 	mutex_enter(&ire->ire_lock);
19906 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19907 	mutex_exit(&ire->ire_lock);
19908 
19909 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19910 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19911 	else
19912 		re->ipv6RouteNextHop = gw_addr_v6;
19913 
19914 	/* remote(4), local(3), or discard(2) */
19915 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19916 		re->ipv6RouteType = 2;
19917 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19918 		re->ipv6RouteType = 3;
19919 	else
19920 		re->ipv6RouteType = 4;
19921 
19922 	re->ipv6RouteProtocol	= -1;
19923 	re->ipv6RoutePolicy	= 0;
19924 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19925 	re->ipv6RouteNextHopRDI	= 0;
19926 	re->ipv6RouteWeight	= 0;
19927 	re->ipv6RouteMetric	= 0;
19928 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19929 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19930 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19931 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19932 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19933 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19934 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19935 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19936 
19937 	if (ire->ire_flags & RTF_DYNAMIC) {
19938 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19939 	} else {
19940 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19941 	}
19942 
19943 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19944 	    (char *)re, (int)sizeof (*re))) {
19945 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19946 		    (uint_t)sizeof (*re)));
19947 	}
19948 
19949 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19950 		iaeptr->iae_routeidx = ird->ird_idx;
19951 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19952 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19953 	}
19954 
19955 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19956 	    (char *)iae, sacnt * sizeof (*iae))) {
19957 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19958 		    (unsigned)(sacnt * sizeof (*iae))));
19959 	}
19960 
19961 	/* bump route index for next pass */
19962 	ird->ird_idx++;
19963 
19964 	kmem_free(re, sizeof (*re));
19965 	if (sacnt != 0)
19966 		kmem_free(iae, sacnt * sizeof (*iae));
19967 
19968 	if (gcgrp != NULL)
19969 		rw_exit(&gcgrp->gcgrp_rwlock);
19970 }
19971 
19972 /*
19973  * ndp_walk routine to create ipv6NetToMediaEntryTable
19974  */
19975 static int
19976 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19977 {
19978 	ill_t				*ill;
19979 	mib2_ipv6NetToMediaEntry_t	ntme;
19980 	dl_unitdata_req_t		*dl;
19981 
19982 	ill = nce->nce_ill;
19983 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19984 		return (0);
19985 
19986 	/*
19987 	 * Neighbor cache entry attached to IRE with on-link
19988 	 * destination.
19989 	 */
19990 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19991 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19992 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19993 	    (nce->nce_res_mp != NULL)) {
19994 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19995 		ntme.ipv6NetToMediaPhysAddress.o_length =
19996 		    dl->dl_dest_addr_length;
19997 	} else {
19998 		ntme.ipv6NetToMediaPhysAddress.o_length =
19999 		    ill->ill_phys_addr_length;
20000 	}
20001 	if (nce->nce_res_mp != NULL) {
20002 		bcopy((char *)nce->nce_res_mp->b_rptr +
20003 		    NCE_LL_ADDR_OFFSET(ill),
20004 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
20005 		    ntme.ipv6NetToMediaPhysAddress.o_length);
20006 	} else {
20007 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
20008 		    ill->ill_phys_addr_length);
20009 	}
20010 	/*
20011 	 * Note: Returns ND_* states. Should be:
20012 	 * reachable(1), stale(2), delay(3), probe(4),
20013 	 * invalid(5), unknown(6)
20014 	 */
20015 	ntme.ipv6NetToMediaState = nce->nce_state;
20016 	ntme.ipv6NetToMediaLastUpdated = 0;
20017 
20018 	/* other(1), dynamic(2), static(3), local(4) */
20019 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
20020 		ntme.ipv6NetToMediaType = 4;
20021 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
20022 		ntme.ipv6NetToMediaType = 1;
20023 	} else {
20024 		ntme.ipv6NetToMediaType = 2;
20025 	}
20026 
20027 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
20028 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
20029 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
20030 		    (uint_t)sizeof (ntme)));
20031 	}
20032 	return (0);
20033 }
20034 
20035 /*
20036  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
20037  */
20038 /* ARGSUSED */
20039 int
20040 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
20041 {
20042 	switch (level) {
20043 	case MIB2_IP:
20044 	case MIB2_ICMP:
20045 		switch (name) {
20046 		default:
20047 			break;
20048 		}
20049 		return (1);
20050 	default:
20051 		return (1);
20052 	}
20053 }
20054 
20055 /*
20056  * When there exists both a 64- and 32-bit counter of a particular type
20057  * (i.e., InReceives), only the 64-bit counters are added.
20058  */
20059 void
20060 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
20061 {
20062 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
20063 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
20064 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
20065 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
20066 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
20067 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
20068 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
20069 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
20070 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
20071 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
20072 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
20073 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
20074 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
20075 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
20076 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
20077 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
20078 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
20079 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
20080 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
20081 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
20082 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20083 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20084 	    o2->ipIfStatsInWrongIPVersion);
20085 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20086 	    o2->ipIfStatsInWrongIPVersion);
20087 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20088 	    o2->ipIfStatsOutSwitchIPVersion);
20089 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20090 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20091 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20092 	    o2->ipIfStatsHCInForwDatagrams);
20093 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20094 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20095 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20096 	    o2->ipIfStatsHCOutForwDatagrams);
20097 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20098 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20099 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20100 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20101 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20102 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20103 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20104 	    o2->ipIfStatsHCOutMcastOctets);
20105 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20106 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20107 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20108 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20109 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20110 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20111 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20112 }
20113 
20114 void
20115 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20116 {
20117 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20118 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20119 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20120 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20121 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20122 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20123 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20124 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20125 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20126 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20127 	    o2->ipv6IfIcmpInRouterSolicits);
20128 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20129 	    o2->ipv6IfIcmpInRouterAdvertisements);
20130 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20131 	    o2->ipv6IfIcmpInNeighborSolicits);
20132 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20133 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20134 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20135 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20136 	    o2->ipv6IfIcmpInGroupMembQueries);
20137 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20138 	    o2->ipv6IfIcmpInGroupMembResponses);
20139 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20140 	    o2->ipv6IfIcmpInGroupMembReductions);
20141 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20142 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20143 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20144 	    o2->ipv6IfIcmpOutDestUnreachs);
20145 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20146 	    o2->ipv6IfIcmpOutAdminProhibs);
20147 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20148 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20149 	    o2->ipv6IfIcmpOutParmProblems);
20150 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20151 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20152 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20153 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20154 	    o2->ipv6IfIcmpOutRouterSolicits);
20155 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20156 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20157 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20158 	    o2->ipv6IfIcmpOutNeighborSolicits);
20159 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20160 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20161 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20162 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20163 	    o2->ipv6IfIcmpOutGroupMembQueries);
20164 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20165 	    o2->ipv6IfIcmpOutGroupMembResponses);
20166 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20167 	    o2->ipv6IfIcmpOutGroupMembReductions);
20168 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20169 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20170 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20171 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20172 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20173 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20174 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20175 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20176 	    o2->ipv6IfIcmpInGroupMembTotal);
20177 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20178 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20179 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20180 	    o2->ipv6IfIcmpInGroupMembBadReports);
20181 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20182 	    o2->ipv6IfIcmpInGroupMembOurReports);
20183 }
20184 
20185 /*
20186  * Called before the options are updated to check if this packet will
20187  * be source routed from here.
20188  * This routine assumes that the options are well formed i.e. that they
20189  * have already been checked.
20190  */
20191 static boolean_t
20192 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20193 {
20194 	ipoptp_t	opts;
20195 	uchar_t		*opt;
20196 	uint8_t		optval;
20197 	uint8_t		optlen;
20198 	ipaddr_t	dst;
20199 	ire_t		*ire;
20200 
20201 	if (IS_SIMPLE_IPH(ipha)) {
20202 		ip2dbg(("not source routed\n"));
20203 		return (B_FALSE);
20204 	}
20205 	dst = ipha->ipha_dst;
20206 	for (optval = ipoptp_first(&opts, ipha);
20207 	    optval != IPOPT_EOL;
20208 	    optval = ipoptp_next(&opts)) {
20209 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20210 		opt = opts.ipoptp_cur;
20211 		optlen = opts.ipoptp_len;
20212 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20213 		    optval, optlen));
20214 		switch (optval) {
20215 			uint32_t off;
20216 		case IPOPT_SSRR:
20217 		case IPOPT_LSRR:
20218 			/*
20219 			 * If dst is one of our addresses and there are some
20220 			 * entries left in the source route return (true).
20221 			 */
20222 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20223 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20224 			if (ire == NULL) {
20225 				ip2dbg(("ip_source_routed: not next"
20226 				    " source route 0x%x\n",
20227 				    ntohl(dst)));
20228 				return (B_FALSE);
20229 			}
20230 			ire_refrele(ire);
20231 			off = opt[IPOPT_OFFSET];
20232 			off--;
20233 			if (optlen < IP_ADDR_LEN ||
20234 			    off > optlen - IP_ADDR_LEN) {
20235 				/* End of source route */
20236 				ip1dbg(("ip_source_routed: end of SR\n"));
20237 				return (B_FALSE);
20238 			}
20239 			return (B_TRUE);
20240 		}
20241 	}
20242 	ip2dbg(("not source routed\n"));
20243 	return (B_FALSE);
20244 }
20245 
20246 /*
20247  * Check if the packet contains any source route.
20248  */
20249 static boolean_t
20250 ip_source_route_included(ipha_t *ipha)
20251 {
20252 	ipoptp_t	opts;
20253 	uint8_t		optval;
20254 
20255 	if (IS_SIMPLE_IPH(ipha))
20256 		return (B_FALSE);
20257 	for (optval = ipoptp_first(&opts, ipha);
20258 	    optval != IPOPT_EOL;
20259 	    optval = ipoptp_next(&opts)) {
20260 		switch (optval) {
20261 		case IPOPT_SSRR:
20262 		case IPOPT_LSRR:
20263 			return (B_TRUE);
20264 		}
20265 	}
20266 	return (B_FALSE);
20267 }
20268 
20269 /*
20270  * Called when the IRE expiration timer fires.
20271  */
20272 void
20273 ip_trash_timer_expire(void *args)
20274 {
20275 	int			flush_flag = 0;
20276 	ire_expire_arg_t	iea;
20277 	ip_stack_t		*ipst = (ip_stack_t *)args;
20278 
20279 	iea.iea_ipst = ipst;	/* No netstack_hold */
20280 
20281 	/*
20282 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20283 	 * This lock makes sure that a new invocation of this function
20284 	 * that occurs due to an almost immediate timer firing will not
20285 	 * progress beyond this point until the current invocation is done
20286 	 */
20287 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20288 	ipst->ips_ip_ire_expire_id = 0;
20289 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20290 
20291 	/* Periodic timer */
20292 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20293 	    ipst->ips_ip_ire_arp_interval) {
20294 		/*
20295 		 * Remove all IRE_CACHE entries since they might
20296 		 * contain arp information.
20297 		 */
20298 		flush_flag |= FLUSH_ARP_TIME;
20299 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20300 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20301 	}
20302 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20303 	    ipst->ips_ip_ire_redir_interval) {
20304 		/* Remove all redirects */
20305 		flush_flag |= FLUSH_REDIRECT_TIME;
20306 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20307 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20308 	}
20309 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20310 	    ipst->ips_ip_ire_pathmtu_interval) {
20311 		/* Increase path mtu */
20312 		flush_flag |= FLUSH_MTU_TIME;
20313 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20314 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20315 	}
20316 
20317 	/*
20318 	 * Optimize for the case when there are no redirects in the
20319 	 * ftable, that is, no need to walk the ftable in that case.
20320 	 */
20321 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20322 		iea.iea_flush_flag = flush_flag;
20323 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20324 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20325 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20326 		    NULL, ALL_ZONES, ipst);
20327 	}
20328 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20329 	    ipst->ips_ip_redirect_cnt > 0) {
20330 		iea.iea_flush_flag = flush_flag;
20331 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20332 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20333 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20334 	}
20335 	if (flush_flag & FLUSH_MTU_TIME) {
20336 		/*
20337 		 * Walk all IPv6 IRE's and update them
20338 		 * Note that ARP and redirect timers are not
20339 		 * needed since NUD handles stale entries.
20340 		 */
20341 		flush_flag = FLUSH_MTU_TIME;
20342 		iea.iea_flush_flag = flush_flag;
20343 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20344 		    ALL_ZONES, ipst);
20345 	}
20346 
20347 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20348 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20349 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20350 
20351 	/*
20352 	 * Hold the lock to serialize timeout calls and prevent
20353 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20354 	 * for the timer to fire and a new invocation of this function
20355 	 * to start before the return value of timeout has been stored
20356 	 * in ip_ire_expire_id by the current invocation.
20357 	 */
20358 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20359 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20360 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20361 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20362 }
20363 
20364 /*
20365  * Called by the memory allocator subsystem directly, when the system
20366  * is running low on memory.
20367  */
20368 /* ARGSUSED */
20369 void
20370 ip_trash_ire_reclaim(void *args)
20371 {
20372 	netstack_handle_t nh;
20373 	netstack_t *ns;
20374 
20375 	netstack_next_init(&nh);
20376 	while ((ns = netstack_next(&nh)) != NULL) {
20377 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20378 		netstack_rele(ns);
20379 	}
20380 	netstack_next_fini(&nh);
20381 }
20382 
20383 static void
20384 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20385 {
20386 	ire_cache_count_t icc;
20387 	ire_cache_reclaim_t icr;
20388 	ncc_cache_count_t ncc;
20389 	nce_cache_reclaim_t ncr;
20390 	uint_t delete_cnt;
20391 	/*
20392 	 * Memory reclaim call back.
20393 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20394 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20395 	 * entries, determine what fraction to free for
20396 	 * each category of IRE_CACHE entries giving absolute priority
20397 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20398 	 * entry will be freed unless all offlink entries are freed).
20399 	 */
20400 	icc.icc_total = 0;
20401 	icc.icc_unused = 0;
20402 	icc.icc_offlink = 0;
20403 	icc.icc_pmtu = 0;
20404 	icc.icc_onlink = 0;
20405 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20406 
20407 	/*
20408 	 * Free NCEs for IPv6 like the onlink ires.
20409 	 */
20410 	ncc.ncc_total = 0;
20411 	ncc.ncc_host = 0;
20412 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20413 
20414 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20415 	    icc.icc_pmtu + icc.icc_onlink);
20416 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20417 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20418 	if (delete_cnt == 0)
20419 		return;
20420 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20421 	/* Always delete all unused offlink entries */
20422 	icr.icr_ipst = ipst;
20423 	icr.icr_unused = 1;
20424 	if (delete_cnt <= icc.icc_unused) {
20425 		/*
20426 		 * Only need to free unused entries.  In other words,
20427 		 * there are enough unused entries to free to meet our
20428 		 * target number of freed ire cache entries.
20429 		 */
20430 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20431 		ncr.ncr_host = 0;
20432 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20433 		/*
20434 		 * Only need to free unused entries, plus a fraction of offlink
20435 		 * entries.  It follows from the first if statement that
20436 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20437 		 */
20438 		delete_cnt -= icc.icc_unused;
20439 		/* Round up # deleted by truncating fraction */
20440 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20441 		icr.icr_pmtu = icr.icr_onlink = 0;
20442 		ncr.ncr_host = 0;
20443 	} else if (delete_cnt <=
20444 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20445 		/*
20446 		 * Free all unused and offlink entries, plus a fraction of
20447 		 * pmtu entries.  It follows from the previous if statement
20448 		 * that icc_pmtu is non-zero, and that
20449 		 * delete_cnt != icc_unused + icc_offlink.
20450 		 */
20451 		icr.icr_offlink = 1;
20452 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20453 		/* Round up # deleted by truncating fraction */
20454 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20455 		icr.icr_onlink = 0;
20456 		ncr.ncr_host = 0;
20457 	} else {
20458 		/*
20459 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20460 		 * of onlink entries.  If we're here, then we know that
20461 		 * icc_onlink is non-zero, and that
20462 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20463 		 */
20464 		icr.icr_offlink = icr.icr_pmtu = 1;
20465 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20466 		    icc.icc_pmtu;
20467 		/* Round up # deleted by truncating fraction */
20468 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20469 		/* Using the same delete fraction as for onlink IREs */
20470 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20471 	}
20472 #ifdef DEBUG
20473 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20474 	    "fractions %d/%d/%d/%d\n",
20475 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20476 	    icc.icc_unused, icc.icc_offlink,
20477 	    icc.icc_pmtu, icc.icc_onlink,
20478 	    icr.icr_unused, icr.icr_offlink,
20479 	    icr.icr_pmtu, icr.icr_onlink));
20480 #endif
20481 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20482 	if (ncr.ncr_host != 0)
20483 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20484 		    (uchar_t *)&ncr, ipst);
20485 #ifdef DEBUG
20486 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20487 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20488 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20489 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20490 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20491 	    icc.icc_pmtu, icc.icc_onlink));
20492 #endif
20493 }
20494 
20495 /*
20496  * ip_unbind is called when a copy of an unbind request is received from the
20497  * upper level protocol.  We remove this conn from any fanout hash list it is
20498  * on, and zero out the bind information.  No reply is expected up above.
20499  */
20500 void
20501 ip_unbind(conn_t *connp)
20502 {
20503 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20504 
20505 	if (is_system_labeled() && connp->conn_anon_port) {
20506 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20507 		    connp->conn_mlp_type, connp->conn_ulp,
20508 		    ntohs(connp->conn_lport), B_FALSE);
20509 		connp->conn_anon_port = 0;
20510 	}
20511 	connp->conn_mlp_type = mlptSingle;
20512 
20513 	ipcl_hash_remove(connp);
20514 
20515 }
20516 
20517 /*
20518  * Write side put procedure.  Outbound data, IOCTLs, responses from
20519  * resolvers, etc, come down through here.
20520  *
20521  * arg2 is always a queue_t *.
20522  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20523  * the zoneid.
20524  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20525  */
20526 void
20527 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20528 {
20529 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20530 }
20531 
20532 void
20533 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20534     ip_opt_info_t *infop)
20535 {
20536 	conn_t		*connp = NULL;
20537 	queue_t		*q = (queue_t *)arg2;
20538 	ipha_t		*ipha;
20539 #define	rptr	((uchar_t *)ipha)
20540 	ire_t		*ire = NULL;
20541 	ire_t		*sctp_ire = NULL;
20542 	uint32_t	v_hlen_tos_len;
20543 	ipaddr_t	dst;
20544 	mblk_t		*first_mp = NULL;
20545 	boolean_t	mctl_present;
20546 	ipsec_out_t	*io;
20547 	int		match_flags;
20548 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20549 	ipif_t		*dst_ipif;
20550 	boolean_t	multirt_need_resolve = B_FALSE;
20551 	mblk_t		*copy_mp = NULL;
20552 	int		err = 0;
20553 	zoneid_t	zoneid;
20554 	boolean_t	need_decref = B_FALSE;
20555 	boolean_t	ignore_dontroute = B_FALSE;
20556 	boolean_t	ignore_nexthop = B_FALSE;
20557 	boolean_t	ip_nexthop = B_FALSE;
20558 	ipaddr_t	nexthop_addr;
20559 	ip_stack_t	*ipst;
20560 
20561 #ifdef	_BIG_ENDIAN
20562 #define	V_HLEN	(v_hlen_tos_len >> 24)
20563 #else
20564 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20565 #endif
20566 
20567 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20568 	    "ip_wput_start: q %p", q);
20569 
20570 	/*
20571 	 * ip_wput fast path
20572 	 */
20573 
20574 	/* is packet from ARP ? */
20575 	if (q->q_next != NULL) {
20576 		zoneid = (zoneid_t)(uintptr_t)arg;
20577 		goto qnext;
20578 	}
20579 
20580 	connp = (conn_t *)arg;
20581 	ASSERT(connp != NULL);
20582 	zoneid = connp->conn_zoneid;
20583 	ipst = connp->conn_netstack->netstack_ip;
20584 	ASSERT(ipst != NULL);
20585 
20586 	/* is queue flow controlled? */
20587 	if ((q->q_first != NULL || connp->conn_draining) &&
20588 	    (caller == IP_WPUT)) {
20589 		ASSERT(!need_decref);
20590 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20591 		(void) putq(q, mp);
20592 		return;
20593 	}
20594 
20595 	/* Multidata transmit? */
20596 	if (DB_TYPE(mp) == M_MULTIDATA) {
20597 		/*
20598 		 * We should never get here, since all Multidata messages
20599 		 * originating from tcp should have been directed over to
20600 		 * tcp_multisend() in the first place.
20601 		 */
20602 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20603 		freemsg(mp);
20604 		return;
20605 	} else if (DB_TYPE(mp) != M_DATA)
20606 		goto notdata;
20607 
20608 	if (mp->b_flag & MSGHASREF) {
20609 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20610 		mp->b_flag &= ~MSGHASREF;
20611 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20612 		need_decref = B_TRUE;
20613 	}
20614 	ipha = (ipha_t *)mp->b_rptr;
20615 
20616 	/* is IP header non-aligned or mblk smaller than basic IP header */
20617 #ifndef SAFETY_BEFORE_SPEED
20618 	if (!OK_32PTR(rptr) ||
20619 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20620 		goto hdrtoosmall;
20621 #endif
20622 
20623 	ASSERT(OK_32PTR(ipha));
20624 
20625 	/*
20626 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20627 	 * wrong version, we'll catch it again in ip_output_v6.
20628 	 *
20629 	 * Note that this is *only* locally-generated output here, and never
20630 	 * forwarded data, and that we need to deal only with transports that
20631 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20632 	 * label.)
20633 	 */
20634 	if (is_system_labeled() &&
20635 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20636 	    !connp->conn_ulp_labeled) {
20637 		cred_t	*credp;
20638 		pid_t	pid;
20639 
20640 		credp = BEST_CRED(mp, connp, &pid);
20641 		err = tsol_check_label(credp, &mp,
20642 		    connp->conn_mac_exempt, ipst, pid);
20643 		ipha = (ipha_t *)mp->b_rptr;
20644 		if (err != 0) {
20645 			first_mp = mp;
20646 			if (err == EINVAL)
20647 				goto icmp_parameter_problem;
20648 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20649 			goto discard_pkt;
20650 		}
20651 	}
20652 
20653 	ASSERT(infop != NULL);
20654 
20655 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20656 		/*
20657 		 * IP_PKTINFO ancillary option is present.
20658 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20659 		 * allows using address of any zone as the source address.
20660 		 */
20661 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20662 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20663 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20664 		if (ire == NULL)
20665 			goto drop_pkt;
20666 		ire_refrele(ire);
20667 		ire = NULL;
20668 	}
20669 
20670 	/*
20671 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20672 	 */
20673 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20674 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20675 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20676 
20677 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20678 			goto drop_pkt;
20679 		/*
20680 		 * check that there is an ipif belonging
20681 		 * to our zone. IPCL_ZONEID is not used because
20682 		 * IP_ALLZONES option is valid only when the ill is
20683 		 * accessible from all zones i.e has a valid ipif in
20684 		 * all zones.
20685 		 */
20686 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20687 			goto drop_pkt;
20688 		}
20689 	}
20690 
20691 	/*
20692 	 * If there is a policy, try to attach an ipsec_out in
20693 	 * the front. At the end, first_mp either points to a
20694 	 * M_DATA message or IPSEC_OUT message linked to a
20695 	 * M_DATA message. We have to do it now as we might
20696 	 * lose the "conn" if we go through ip_newroute.
20697 	 */
20698 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20699 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20700 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20701 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20702 			if (need_decref)
20703 				CONN_DEC_REF(connp);
20704 			return;
20705 		} else {
20706 			ASSERT(mp->b_datap->db_type == M_CTL);
20707 			first_mp = mp;
20708 			mp = mp->b_cont;
20709 			mctl_present = B_TRUE;
20710 		}
20711 	} else {
20712 		first_mp = mp;
20713 		mctl_present = B_FALSE;
20714 	}
20715 
20716 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20717 
20718 	/* is wrong version or IP options present */
20719 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20720 		goto version_hdrlen_check;
20721 	dst = ipha->ipha_dst;
20722 
20723 	/* If IP_BOUND_IF has been set, use that ill. */
20724 	if (connp->conn_outgoing_ill != NULL) {
20725 		xmit_ill = conn_get_held_ill(connp,
20726 		    &connp->conn_outgoing_ill, &err);
20727 		if (err == ILL_LOOKUP_FAILED)
20728 			goto drop_pkt;
20729 
20730 		goto send_from_ill;
20731 	}
20732 
20733 	/* is packet multicast? */
20734 	if (CLASSD(dst))
20735 		goto multicast;
20736 
20737 	/*
20738 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20739 	 * takes precedence over conn_dontroute and conn_nexthop_set
20740 	 */
20741 	if (xmit_ill != NULL)
20742 		goto send_from_ill;
20743 
20744 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20745 		/*
20746 		 * If the destination is a broadcast, local, or loopback
20747 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20748 		 * standard path.
20749 		 */
20750 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20751 		if ((ire == NULL) || (ire->ire_type &
20752 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20753 			if (ire != NULL) {
20754 				ire_refrele(ire);
20755 				/* No more access to ire */
20756 				ire = NULL;
20757 			}
20758 			/*
20759 			 * bypass routing checks and go directly to interface.
20760 			 */
20761 			if (connp->conn_dontroute)
20762 				goto dontroute;
20763 
20764 			ASSERT(connp->conn_nexthop_set);
20765 			ip_nexthop = B_TRUE;
20766 			nexthop_addr = connp->conn_nexthop_v4;
20767 			goto send_from_ill;
20768 		}
20769 
20770 		/* Must be a broadcast, a loopback or a local ire */
20771 		ire_refrele(ire);
20772 		/* No more access to ire */
20773 		ire = NULL;
20774 	}
20775 
20776 	/*
20777 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20778 	 * this for the tcp global queue and listen end point
20779 	 * as it does not really have a real destination to
20780 	 * talk to.  This is also true for SCTP.
20781 	 */
20782 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20783 	    !connp->conn_fully_bound) {
20784 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20785 		if (ire == NULL)
20786 			goto noirefound;
20787 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20788 		    "ip_wput_end: q %p (%S)", q, "end");
20789 
20790 		/*
20791 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20792 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20793 		 */
20794 		if (ire->ire_flags & RTF_MULTIRT) {
20795 
20796 			/*
20797 			 * Force the TTL of multirouted packets if required.
20798 			 * The TTL of such packets is bounded by the
20799 			 * ip_multirt_ttl ndd variable.
20800 			 */
20801 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20802 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20803 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20804 				    "(was %d), dst 0x%08x\n",
20805 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20806 				    ntohl(ire->ire_addr)));
20807 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20808 			}
20809 			/*
20810 			 * We look at this point if there are pending
20811 			 * unresolved routes. ire_multirt_resolvable()
20812 			 * checks in O(n) that all IRE_OFFSUBNET ire
20813 			 * entries for the packet's destination and
20814 			 * flagged RTF_MULTIRT are currently resolved.
20815 			 * If some remain unresolved, we make a copy
20816 			 * of the current message. It will be used
20817 			 * to initiate additional route resolutions.
20818 			 */
20819 			multirt_need_resolve =
20820 			    ire_multirt_need_resolve(ire->ire_addr,
20821 			    msg_getlabel(first_mp), ipst);
20822 			ip2dbg(("ip_wput[TCP]: ire %p, "
20823 			    "multirt_need_resolve %d, first_mp %p\n",
20824 			    (void *)ire, multirt_need_resolve,
20825 			    (void *)first_mp));
20826 			if (multirt_need_resolve) {
20827 				copy_mp = copymsg(first_mp);
20828 				if (copy_mp != NULL) {
20829 					MULTIRT_DEBUG_TAG(copy_mp);
20830 				}
20831 			}
20832 		}
20833 
20834 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20835 
20836 		/*
20837 		 * Try to resolve another multiroute if
20838 		 * ire_multirt_need_resolve() deemed it necessary.
20839 		 */
20840 		if (copy_mp != NULL)
20841 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20842 		if (need_decref)
20843 			CONN_DEC_REF(connp);
20844 		return;
20845 	}
20846 
20847 	/*
20848 	 * Access to conn_ire_cache. (protected by conn_lock)
20849 	 *
20850 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20851 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20852 	 * send a packet or two with the IRE_CACHE that is going away.
20853 	 * Access to the ire requires an ire refhold on the ire prior to
20854 	 * its use since an interface unplumb thread may delete the cached
20855 	 * ire and release the refhold at any time.
20856 	 *
20857 	 * Caching an ire in the conn_ire_cache
20858 	 *
20859 	 * o Caching an ire pointer in the conn requires a strict check for
20860 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20861 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20862 	 * in the conn is done after making sure under the bucket lock that the
20863 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20864 	 * caching an ire after the unplumb thread has cleaned up the conn.
20865 	 * If the conn does not send a packet subsequently the unplumb thread
20866 	 * will be hanging waiting for the ire count to drop to zero.
20867 	 *
20868 	 * o We also need to atomically test for a null conn_ire_cache and
20869 	 * set the conn_ire_cache under the the protection of the conn_lock
20870 	 * to avoid races among concurrent threads trying to simultaneously
20871 	 * cache an ire in the conn_ire_cache.
20872 	 */
20873 	mutex_enter(&connp->conn_lock);
20874 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20875 
20876 	if (ire != NULL && ire->ire_addr == dst &&
20877 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20878 
20879 		IRE_REFHOLD(ire);
20880 		mutex_exit(&connp->conn_lock);
20881 
20882 	} else {
20883 		boolean_t cached = B_FALSE;
20884 		connp->conn_ire_cache = NULL;
20885 		mutex_exit(&connp->conn_lock);
20886 		/* Release the old ire */
20887 		if (ire != NULL && sctp_ire == NULL)
20888 			IRE_REFRELE_NOTR(ire);
20889 
20890 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20891 		if (ire == NULL)
20892 			goto noirefound;
20893 		IRE_REFHOLD_NOTR(ire);
20894 
20895 		mutex_enter(&connp->conn_lock);
20896 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20897 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20898 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20899 				if (connp->conn_ulp == IPPROTO_TCP)
20900 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20901 				connp->conn_ire_cache = ire;
20902 				cached = B_TRUE;
20903 			}
20904 			rw_exit(&ire->ire_bucket->irb_lock);
20905 		}
20906 		mutex_exit(&connp->conn_lock);
20907 
20908 		/*
20909 		 * We can continue to use the ire but since it was
20910 		 * not cached, we should drop the extra reference.
20911 		 */
20912 		if (!cached)
20913 			IRE_REFRELE_NOTR(ire);
20914 	}
20915 
20916 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20917 	    "ip_wput_end: q %p (%S)", q, "end");
20918 
20919 	/*
20920 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20921 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20922 	 */
20923 	if (ire->ire_flags & RTF_MULTIRT) {
20924 		/*
20925 		 * Force the TTL of multirouted packets if required.
20926 		 * The TTL of such packets is bounded by the
20927 		 * ip_multirt_ttl ndd variable.
20928 		 */
20929 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20930 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20931 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20932 			    "(was %d), dst 0x%08x\n",
20933 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20934 			    ntohl(ire->ire_addr)));
20935 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20936 		}
20937 
20938 		/*
20939 		 * At this point, we check to see if there are any pending
20940 		 * unresolved routes. ire_multirt_resolvable()
20941 		 * checks in O(n) that all IRE_OFFSUBNET ire
20942 		 * entries for the packet's destination and
20943 		 * flagged RTF_MULTIRT are currently resolved.
20944 		 * If some remain unresolved, we make a copy
20945 		 * of the current message. It will be used
20946 		 * to initiate additional route resolutions.
20947 		 */
20948 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20949 		    msg_getlabel(first_mp), ipst);
20950 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20951 		    "multirt_need_resolve %d, first_mp %p\n",
20952 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20953 		if (multirt_need_resolve) {
20954 			copy_mp = copymsg(first_mp);
20955 			if (copy_mp != NULL) {
20956 				MULTIRT_DEBUG_TAG(copy_mp);
20957 			}
20958 		}
20959 	}
20960 
20961 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20962 
20963 	/*
20964 	 * Try to resolve another multiroute if
20965 	 * ire_multirt_resolvable() deemed it necessary
20966 	 */
20967 	if (copy_mp != NULL)
20968 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20969 	if (need_decref)
20970 		CONN_DEC_REF(connp);
20971 	return;
20972 
20973 qnext:
20974 	/*
20975 	 * Upper Level Protocols pass down complete IP datagrams
20976 	 * as M_DATA messages.	Everything else is a sideshow.
20977 	 *
20978 	 * 1) We could be re-entering ip_wput because of ip_neworute
20979 	 *    in which case we could have a IPSEC_OUT message. We
20980 	 *    need to pass through ip_wput like other datagrams and
20981 	 *    hence cannot branch to ip_wput_nondata.
20982 	 *
20983 	 * 2) ARP, AH, ESP, and other clients who are on the module
20984 	 *    instance of IP stream, give us something to deal with.
20985 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20986 	 *
20987 	 * 3) ICMP replies also could come here.
20988 	 */
20989 	ipst = ILLQ_TO_IPST(q);
20990 
20991 	if (DB_TYPE(mp) != M_DATA) {
20992 notdata:
20993 		if (DB_TYPE(mp) == M_CTL) {
20994 			/*
20995 			 * M_CTL messages are used by ARP, AH and ESP to
20996 			 * communicate with IP. We deal with IPSEC_IN and
20997 			 * IPSEC_OUT here. ip_wput_nondata handles other
20998 			 * cases.
20999 			 */
21000 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
21001 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
21002 				first_mp = mp->b_cont;
21003 				first_mp->b_flag &= ~MSGHASREF;
21004 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
21005 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
21006 				CONN_DEC_REF(connp);
21007 				connp = NULL;
21008 			}
21009 			if (ii->ipsec_info_type == IPSEC_IN) {
21010 				/*
21011 				 * Either this message goes back to
21012 				 * IPsec for further processing or to
21013 				 * ULP after policy checks.
21014 				 */
21015 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
21016 				return;
21017 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
21018 				io = (ipsec_out_t *)ii;
21019 				if (io->ipsec_out_proc_begin) {
21020 					/*
21021 					 * IPsec processing has already started.
21022 					 * Complete it.
21023 					 * IPQoS notes: We don't care what is
21024 					 * in ipsec_out_ill_index since this
21025 					 * won't be processed for IPQoS policies
21026 					 * in ipsec_out_process.
21027 					 */
21028 					ipsec_out_process(q, mp, NULL,
21029 					    io->ipsec_out_ill_index);
21030 					return;
21031 				} else {
21032 					connp = (q->q_next != NULL) ?
21033 					    NULL : Q_TO_CONN(q);
21034 					first_mp = mp;
21035 					mp = mp->b_cont;
21036 					mctl_present = B_TRUE;
21037 				}
21038 				zoneid = io->ipsec_out_zoneid;
21039 				ASSERT(zoneid != ALL_ZONES);
21040 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
21041 				/*
21042 				 * It's an IPsec control message requesting
21043 				 * an SADB update to be sent to the IPsec
21044 				 * hardware acceleration capable ills.
21045 				 */
21046 				ipsec_ctl_t *ipsec_ctl =
21047 				    (ipsec_ctl_t *)mp->b_rptr;
21048 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
21049 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
21050 				mblk_t *cmp = mp->b_cont;
21051 
21052 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
21053 				ASSERT(cmp != NULL);
21054 
21055 				freeb(mp);
21056 				ill_ipsec_capab_send_all(satype, cmp, sa,
21057 				    ipst->ips_netstack);
21058 				return;
21059 			} else {
21060 				/*
21061 				 * This must be ARP or special TSOL signaling.
21062 				 */
21063 				ip_wput_nondata(NULL, q, mp, NULL);
21064 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21065 				    "ip_wput_end: q %p (%S)", q, "nondata");
21066 				return;
21067 			}
21068 		} else {
21069 			/*
21070 			 * This must be non-(ARP/AH/ESP) messages.
21071 			 */
21072 			ASSERT(!need_decref);
21073 			ip_wput_nondata(NULL, q, mp, NULL);
21074 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21075 			    "ip_wput_end: q %p (%S)", q, "nondata");
21076 			return;
21077 		}
21078 	} else {
21079 		first_mp = mp;
21080 		mctl_present = B_FALSE;
21081 	}
21082 
21083 	ASSERT(first_mp != NULL);
21084 
21085 	if (mctl_present) {
21086 		io = (ipsec_out_t *)first_mp->b_rptr;
21087 		if (io->ipsec_out_ip_nexthop) {
21088 			/*
21089 			 * We may have lost the conn context if we are
21090 			 * coming here from ip_newroute(). Copy the
21091 			 * nexthop information.
21092 			 */
21093 			ip_nexthop = B_TRUE;
21094 			nexthop_addr = io->ipsec_out_nexthop_addr;
21095 
21096 			ipha = (ipha_t *)mp->b_rptr;
21097 			dst = ipha->ipha_dst;
21098 			goto send_from_ill;
21099 		}
21100 	}
21101 
21102 	ASSERT(xmit_ill == NULL);
21103 
21104 	/* We have a complete IP datagram heading outbound. */
21105 	ipha = (ipha_t *)mp->b_rptr;
21106 
21107 #ifndef SPEED_BEFORE_SAFETY
21108 	/*
21109 	 * Make sure we have a full-word aligned message and that at least
21110 	 * a simple IP header is accessible in the first message.  If not,
21111 	 * try a pullup.  For labeled systems we need to always take this
21112 	 * path as M_CTLs are "notdata" but have trailing data to process.
21113 	 */
21114 	if (!OK_32PTR(rptr) ||
21115 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21116 hdrtoosmall:
21117 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21118 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21119 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21120 			if (first_mp == NULL)
21121 				first_mp = mp;
21122 			goto discard_pkt;
21123 		}
21124 
21125 		/* This function assumes that mp points to an IPv4 packet. */
21126 		if (is_system_labeled() &&
21127 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21128 		    (connp == NULL || !connp->conn_ulp_labeled)) {
21129 			cred_t	*credp;
21130 			pid_t	pid;
21131 
21132 			if (connp != NULL) {
21133 				credp = BEST_CRED(mp, connp, &pid);
21134 				err = tsol_check_label(credp, &mp,
21135 				    connp->conn_mac_exempt, ipst, pid);
21136 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
21137 				err = tsol_check_label(credp, &mp,
21138 				    B_FALSE, ipst, pid);
21139 			}
21140 			ipha = (ipha_t *)mp->b_rptr;
21141 			if (mctl_present)
21142 				first_mp->b_cont = mp;
21143 			else
21144 				first_mp = mp;
21145 			if (err != 0) {
21146 				if (err == EINVAL)
21147 					goto icmp_parameter_problem;
21148 				ip2dbg(("ip_wput: label check failed (%d)\n",
21149 				    err));
21150 				goto discard_pkt;
21151 			}
21152 		}
21153 
21154 		ipha = (ipha_t *)mp->b_rptr;
21155 		if (first_mp == NULL) {
21156 			ASSERT(xmit_ill == NULL);
21157 			/*
21158 			 * If we got here because of "goto hdrtoosmall"
21159 			 * We need to attach a IPSEC_OUT.
21160 			 */
21161 			if (connp->conn_out_enforce_policy) {
21162 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21163 				    NULL, ipha->ipha_protocol,
21164 				    ipst->ips_netstack)) == NULL)) {
21165 					BUMP_MIB(&ipst->ips_ip_mib,
21166 					    ipIfStatsOutDiscards);
21167 					if (need_decref)
21168 						CONN_DEC_REF(connp);
21169 					return;
21170 				} else {
21171 					ASSERT(mp->b_datap->db_type == M_CTL);
21172 					first_mp = mp;
21173 					mp = mp->b_cont;
21174 					mctl_present = B_TRUE;
21175 				}
21176 			} else {
21177 				first_mp = mp;
21178 				mctl_present = B_FALSE;
21179 			}
21180 		}
21181 	}
21182 #endif
21183 
21184 	/* Most of the code below is written for speed, not readability */
21185 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21186 
21187 	/*
21188 	 * If ip_newroute() fails, we're going to need a full
21189 	 * header for the icmp wraparound.
21190 	 */
21191 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21192 		uint_t	v_hlen;
21193 version_hdrlen_check:
21194 		ASSERT(first_mp != NULL);
21195 		v_hlen = V_HLEN;
21196 		/*
21197 		 * siphon off IPv6 packets coming down from transport
21198 		 * layer modules here.
21199 		 * Note: high-order bit carries NUD reachability confirmation
21200 		 */
21201 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21202 			/*
21203 			 * FIXME: assume that callers of ip_output* call
21204 			 * the right version?
21205 			 */
21206 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21207 			ASSERT(xmit_ill == NULL);
21208 			if (need_decref)
21209 				mp->b_flag |= MSGHASREF;
21210 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21211 			return;
21212 		}
21213 
21214 		if ((v_hlen >> 4) != IP_VERSION) {
21215 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21216 			    "ip_wput_end: q %p (%S)", q, "badvers");
21217 			goto discard_pkt;
21218 		}
21219 		/*
21220 		 * Is the header length at least 20 bytes?
21221 		 *
21222 		 * Are there enough bytes accessible in the header?  If
21223 		 * not, try a pullup.
21224 		 */
21225 		v_hlen &= 0xF;
21226 		v_hlen <<= 2;
21227 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21228 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21229 			    "ip_wput_end: q %p (%S)", q, "badlen");
21230 			goto discard_pkt;
21231 		}
21232 		if (v_hlen > (mp->b_wptr - rptr)) {
21233 			if (!pullupmsg(mp, v_hlen)) {
21234 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21235 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21236 				goto discard_pkt;
21237 			}
21238 			ipha = (ipha_t *)mp->b_rptr;
21239 		}
21240 		/*
21241 		 * Move first entry from any source route into ipha_dst and
21242 		 * verify the options
21243 		 */
21244 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21245 		    zoneid, ipst)) {
21246 			ASSERT(xmit_ill == NULL);
21247 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21248 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21249 			    "ip_wput_end: q %p (%S)", q, "badopts");
21250 			if (need_decref)
21251 				CONN_DEC_REF(connp);
21252 			return;
21253 		}
21254 	}
21255 	dst = ipha->ipha_dst;
21256 
21257 	/*
21258 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21259 	 * we have to run the packet through ip_newroute which will take
21260 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21261 	 * a resolver, or assigning a default gateway, etc.
21262 	 */
21263 	if (CLASSD(dst)) {
21264 		ipif_t	*ipif;
21265 		uint32_t setsrc = 0;
21266 
21267 multicast:
21268 		ASSERT(first_mp != NULL);
21269 		ip2dbg(("ip_wput: CLASSD\n"));
21270 		if (connp == NULL) {
21271 			/*
21272 			 * Use the first good ipif on the ill.
21273 			 * XXX Should this ever happen? (Appears
21274 			 * to show up with just ppp and no ethernet due
21275 			 * to in.rdisc.)
21276 			 * However, ire_send should be able to
21277 			 * call ip_wput_ire directly.
21278 			 *
21279 			 * XXX Also, this can happen for ICMP and other packets
21280 			 * with multicast source addresses.  Perhaps we should
21281 			 * fix things so that we drop the packet in question,
21282 			 * but for now, just run with it.
21283 			 */
21284 			ill_t *ill = (ill_t *)q->q_ptr;
21285 
21286 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21287 			if (ipif == NULL) {
21288 				if (need_decref)
21289 					CONN_DEC_REF(connp);
21290 				freemsg(first_mp);
21291 				return;
21292 			}
21293 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21294 			    ntohl(dst), ill->ill_name));
21295 		} else {
21296 			/*
21297 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21298 			 * and IP_MULTICAST_IF.  The block comment above this
21299 			 * function explains the locking mechanism used here.
21300 			 */
21301 			if (xmit_ill == NULL) {
21302 				xmit_ill = conn_get_held_ill(connp,
21303 				    &connp->conn_outgoing_ill, &err);
21304 				if (err == ILL_LOOKUP_FAILED) {
21305 					ip1dbg(("ip_wput: No ill for "
21306 					    "IP_BOUND_IF\n"));
21307 					BUMP_MIB(&ipst->ips_ip_mib,
21308 					    ipIfStatsOutNoRoutes);
21309 					goto drop_pkt;
21310 				}
21311 			}
21312 
21313 			if (xmit_ill == NULL) {
21314 				ipif = conn_get_held_ipif(connp,
21315 				    &connp->conn_multicast_ipif, &err);
21316 				if (err == IPIF_LOOKUP_FAILED) {
21317 					ip1dbg(("ip_wput: No ipif for "
21318 					    "multicast\n"));
21319 					BUMP_MIB(&ipst->ips_ip_mib,
21320 					    ipIfStatsOutNoRoutes);
21321 					goto drop_pkt;
21322 				}
21323 			}
21324 			if (xmit_ill != NULL) {
21325 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21326 				if (ipif == NULL) {
21327 					ip1dbg(("ip_wput: No ipif for "
21328 					    "xmit_ill\n"));
21329 					BUMP_MIB(&ipst->ips_ip_mib,
21330 					    ipIfStatsOutNoRoutes);
21331 					goto drop_pkt;
21332 				}
21333 			} else if (ipif == NULL || ipif->ipif_isv6) {
21334 				/*
21335 				 * We must do this ipif determination here
21336 				 * else we could pass through ip_newroute
21337 				 * and come back here without the conn context.
21338 				 *
21339 				 * Note: we do late binding i.e. we bind to
21340 				 * the interface when the first packet is sent.
21341 				 * For performance reasons we do not rebind on
21342 				 * each packet but keep the binding until the
21343 				 * next IP_MULTICAST_IF option.
21344 				 *
21345 				 * conn_multicast_{ipif,ill} are shared between
21346 				 * IPv4 and IPv6 and AF_INET6 sockets can
21347 				 * send both IPv4 and IPv6 packets. Hence
21348 				 * we have to check that "isv6" matches above.
21349 				 */
21350 				if (ipif != NULL)
21351 					ipif_refrele(ipif);
21352 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21353 				if (ipif == NULL) {
21354 					ip1dbg(("ip_wput: No ipif for "
21355 					    "multicast\n"));
21356 					BUMP_MIB(&ipst->ips_ip_mib,
21357 					    ipIfStatsOutNoRoutes);
21358 					goto drop_pkt;
21359 				}
21360 				err = conn_set_held_ipif(connp,
21361 				    &connp->conn_multicast_ipif, ipif);
21362 				if (err == IPIF_LOOKUP_FAILED) {
21363 					ipif_refrele(ipif);
21364 					ip1dbg(("ip_wput: No ipif for "
21365 					    "multicast\n"));
21366 					BUMP_MIB(&ipst->ips_ip_mib,
21367 					    ipIfStatsOutNoRoutes);
21368 					goto drop_pkt;
21369 				}
21370 			}
21371 		}
21372 		ASSERT(!ipif->ipif_isv6);
21373 		/*
21374 		 * As we may lose the conn by the time we reach ip_wput_ire,
21375 		 * we copy conn_multicast_loop and conn_dontroute on to an
21376 		 * ipsec_out. In case if this datagram goes out secure,
21377 		 * we need the ill_index also. Copy that also into the
21378 		 * ipsec_out.
21379 		 */
21380 		if (mctl_present) {
21381 			io = (ipsec_out_t *)first_mp->b_rptr;
21382 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21383 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21384 		} else {
21385 			ASSERT(mp == first_mp);
21386 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21387 			    BPRI_HI)) == NULL) {
21388 				ipif_refrele(ipif);
21389 				first_mp = mp;
21390 				goto discard_pkt;
21391 			}
21392 			first_mp->b_datap->db_type = M_CTL;
21393 			first_mp->b_wptr += sizeof (ipsec_info_t);
21394 			/* ipsec_out_secure is B_FALSE now */
21395 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21396 			io = (ipsec_out_t *)first_mp->b_rptr;
21397 			io->ipsec_out_type = IPSEC_OUT;
21398 			io->ipsec_out_len = sizeof (ipsec_out_t);
21399 			io->ipsec_out_use_global_policy = B_TRUE;
21400 			io->ipsec_out_ns = ipst->ips_netstack;
21401 			first_mp->b_cont = mp;
21402 			mctl_present = B_TRUE;
21403 		}
21404 
21405 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21406 		io->ipsec_out_ill_index =
21407 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21408 
21409 		if (connp != NULL) {
21410 			io->ipsec_out_multicast_loop =
21411 			    connp->conn_multicast_loop;
21412 			io->ipsec_out_dontroute = connp->conn_dontroute;
21413 			io->ipsec_out_zoneid = connp->conn_zoneid;
21414 		}
21415 		/*
21416 		 * If the application uses IP_MULTICAST_IF with
21417 		 * different logical addresses of the same ILL, we
21418 		 * need to make sure that the soruce address of
21419 		 * the packet matches the logical IP address used
21420 		 * in the option. We do it by initializing ipha_src
21421 		 * here. This should keep IPsec also happy as
21422 		 * when we return from IPsec processing, we don't
21423 		 * have to worry about getting the right address on
21424 		 * the packet. Thus it is sufficient to look for
21425 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21426 		 * MATCH_IRE_IPIF.
21427 		 *
21428 		 * NOTE : We need to do it for non-secure case also as
21429 		 * this might go out secure if there is a global policy
21430 		 * match in ip_wput_ire.
21431 		 *
21432 		 * As we do not have the ire yet, it is possible that
21433 		 * we set the source address here and then later discover
21434 		 * that the ire implies the source address to be assigned
21435 		 * through the RTF_SETSRC flag.
21436 		 * In that case, the setsrc variable will remind us
21437 		 * that overwritting the source address by the one
21438 		 * of the RTF_SETSRC-flagged ire is allowed.
21439 		 */
21440 		if (ipha->ipha_src == INADDR_ANY &&
21441 		    (connp == NULL || !connp->conn_unspec_src)) {
21442 			ipha->ipha_src = ipif->ipif_src_addr;
21443 			setsrc = RTF_SETSRC;
21444 		}
21445 		/*
21446 		 * Find an IRE which matches the destination and the outgoing
21447 		 * queue (i.e. the outgoing interface.)
21448 		 * For loopback use a unicast IP address for
21449 		 * the ire lookup.
21450 		 */
21451 		if (IS_LOOPBACK(ipif->ipif_ill))
21452 			dst = ipif->ipif_lcl_addr;
21453 
21454 		/*
21455 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21456 		 * We don't need to lookup ire in ctable as the packet
21457 		 * needs to be sent to the destination through the specified
21458 		 * ill irrespective of ires in the cache table.
21459 		 */
21460 		ire = NULL;
21461 		if (xmit_ill == NULL) {
21462 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21463 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21464 		}
21465 
21466 		if (ire == NULL) {
21467 			/*
21468 			 * Multicast loopback and multicast forwarding is
21469 			 * done in ip_wput_ire.
21470 			 *
21471 			 * Mark this packet to make it be delivered to
21472 			 * ip_wput_ire after the new ire has been
21473 			 * created.
21474 			 *
21475 			 * The call to ip_newroute_ipif takes into account
21476 			 * the setsrc reminder. In any case, we take care
21477 			 * of the RTF_MULTIRT flag.
21478 			 */
21479 			mp->b_prev = mp->b_next = NULL;
21480 			if (xmit_ill == NULL ||
21481 			    xmit_ill->ill_ipif_up_count > 0) {
21482 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21483 				    setsrc | RTF_MULTIRT, zoneid, infop);
21484 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21485 				    "ip_wput_end: q %p (%S)", q, "noire");
21486 			} else {
21487 				freemsg(first_mp);
21488 			}
21489 			ipif_refrele(ipif);
21490 			if (xmit_ill != NULL)
21491 				ill_refrele(xmit_ill);
21492 			if (need_decref)
21493 				CONN_DEC_REF(connp);
21494 			return;
21495 		}
21496 
21497 		ipif_refrele(ipif);
21498 		ipif = NULL;
21499 		ASSERT(xmit_ill == NULL);
21500 
21501 		/*
21502 		 * Honor the RTF_SETSRC flag for multicast packets,
21503 		 * if allowed by the setsrc reminder.
21504 		 */
21505 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21506 			ipha->ipha_src = ire->ire_src_addr;
21507 		}
21508 
21509 		/*
21510 		 * Unconditionally force the TTL to 1 for
21511 		 * multirouted multicast packets:
21512 		 * multirouted multicast should not cross
21513 		 * multicast routers.
21514 		 */
21515 		if (ire->ire_flags & RTF_MULTIRT) {
21516 			if (ipha->ipha_ttl > 1) {
21517 				ip2dbg(("ip_wput: forcing multicast "
21518 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21519 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21520 				ipha->ipha_ttl = 1;
21521 			}
21522 		}
21523 	} else {
21524 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21525 		if ((ire != NULL) && (ire->ire_type &
21526 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21527 			ignore_dontroute = B_TRUE;
21528 			ignore_nexthop = B_TRUE;
21529 		}
21530 		if (ire != NULL) {
21531 			ire_refrele(ire);
21532 			ire = NULL;
21533 		}
21534 		/*
21535 		 * Guard against coming in from arp in which case conn is NULL.
21536 		 * Also guard against non M_DATA with dontroute set but
21537 		 * destined to local, loopback or broadcast addresses.
21538 		 */
21539 		if (connp != NULL && connp->conn_dontroute &&
21540 		    !ignore_dontroute) {
21541 dontroute:
21542 			/*
21543 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21544 			 * routing protocols from seeing false direct
21545 			 * connectivity.
21546 			 */
21547 			ipha->ipha_ttl = 1;
21548 			/* If suitable ipif not found, drop packet */
21549 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21550 			if (dst_ipif == NULL) {
21551 noroute:
21552 				ip1dbg(("ip_wput: no route for dst using"
21553 				    " SO_DONTROUTE\n"));
21554 				BUMP_MIB(&ipst->ips_ip_mib,
21555 				    ipIfStatsOutNoRoutes);
21556 				mp->b_prev = mp->b_next = NULL;
21557 				if (first_mp == NULL)
21558 					first_mp = mp;
21559 				goto drop_pkt;
21560 			} else {
21561 				/*
21562 				 * If suitable ipif has been found, set
21563 				 * xmit_ill to the corresponding
21564 				 * ipif_ill because we'll be using the
21565 				 * send_from_ill logic below.
21566 				 */
21567 				ASSERT(xmit_ill == NULL);
21568 				xmit_ill = dst_ipif->ipif_ill;
21569 				mutex_enter(&xmit_ill->ill_lock);
21570 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21571 					mutex_exit(&xmit_ill->ill_lock);
21572 					xmit_ill = NULL;
21573 					ipif_refrele(dst_ipif);
21574 					goto noroute;
21575 				}
21576 				ill_refhold_locked(xmit_ill);
21577 				mutex_exit(&xmit_ill->ill_lock);
21578 				ipif_refrele(dst_ipif);
21579 			}
21580 		}
21581 
21582 send_from_ill:
21583 		if (xmit_ill != NULL) {
21584 			ipif_t *ipif;
21585 
21586 			/*
21587 			 * Mark this packet as originated locally
21588 			 */
21589 			mp->b_prev = mp->b_next = NULL;
21590 
21591 			/*
21592 			 * Could be SO_DONTROUTE case also.
21593 			 * Verify that at least one ipif is up on the ill.
21594 			 */
21595 			if (xmit_ill->ill_ipif_up_count == 0) {
21596 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21597 				    xmit_ill->ill_name));
21598 				goto drop_pkt;
21599 			}
21600 
21601 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21602 			if (ipif == NULL) {
21603 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21604 				    xmit_ill->ill_name));
21605 				goto drop_pkt;
21606 			}
21607 
21608 			match_flags = 0;
21609 			if (IS_UNDER_IPMP(xmit_ill))
21610 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21611 
21612 			/*
21613 			 * Look for a ire that is part of the group,
21614 			 * if found use it else call ip_newroute_ipif.
21615 			 * IPCL_ZONEID is not used for matching because
21616 			 * IP_ALLZONES option is valid only when the
21617 			 * ill is accessible from all zones i.e has a
21618 			 * valid ipif in all zones.
21619 			 */
21620 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21621 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21622 			    msg_getlabel(mp), match_flags, ipst);
21623 			/*
21624 			 * If an ire exists use it or else create
21625 			 * an ire but don't add it to the cache.
21626 			 * Adding an ire may cause issues with
21627 			 * asymmetric routing.
21628 			 * In case of multiroute always act as if
21629 			 * ire does not exist.
21630 			 */
21631 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21632 				if (ire != NULL)
21633 					ire_refrele(ire);
21634 				ip_newroute_ipif(q, first_mp, ipif,
21635 				    dst, connp, 0, zoneid, infop);
21636 				ipif_refrele(ipif);
21637 				ip1dbg(("ip_output: xmit_ill via %s\n",
21638 				    xmit_ill->ill_name));
21639 				ill_refrele(xmit_ill);
21640 				if (need_decref)
21641 					CONN_DEC_REF(connp);
21642 				return;
21643 			}
21644 			ipif_refrele(ipif);
21645 		} else if (ip_nexthop || (connp != NULL &&
21646 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21647 			if (!ip_nexthop) {
21648 				ip_nexthop = B_TRUE;
21649 				nexthop_addr = connp->conn_nexthop_v4;
21650 			}
21651 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21652 			    MATCH_IRE_GW;
21653 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21654 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21655 		} else {
21656 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21657 			    ipst);
21658 		}
21659 		if (!ire) {
21660 			if (ip_nexthop && !ignore_nexthop) {
21661 				if (mctl_present) {
21662 					io = (ipsec_out_t *)first_mp->b_rptr;
21663 					ASSERT(first_mp->b_datap->db_type ==
21664 					    M_CTL);
21665 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21666 				} else {
21667 					ASSERT(mp == first_mp);
21668 					first_mp = allocb(
21669 					    sizeof (ipsec_info_t), BPRI_HI);
21670 					if (first_mp == NULL) {
21671 						first_mp = mp;
21672 						goto discard_pkt;
21673 					}
21674 					first_mp->b_datap->db_type = M_CTL;
21675 					first_mp->b_wptr +=
21676 					    sizeof (ipsec_info_t);
21677 					/* ipsec_out_secure is B_FALSE now */
21678 					bzero(first_mp->b_rptr,
21679 					    sizeof (ipsec_info_t));
21680 					io = (ipsec_out_t *)first_mp->b_rptr;
21681 					io->ipsec_out_type = IPSEC_OUT;
21682 					io->ipsec_out_len =
21683 					    sizeof (ipsec_out_t);
21684 					io->ipsec_out_use_global_policy =
21685 					    B_TRUE;
21686 					io->ipsec_out_ns = ipst->ips_netstack;
21687 					first_mp->b_cont = mp;
21688 					mctl_present = B_TRUE;
21689 				}
21690 				io->ipsec_out_ip_nexthop = ip_nexthop;
21691 				io->ipsec_out_nexthop_addr = nexthop_addr;
21692 			}
21693 noirefound:
21694 			/*
21695 			 * Mark this packet as having originated on
21696 			 * this machine.  This will be noted in
21697 			 * ire_add_then_send, which needs to know
21698 			 * whether to run it back through ip_wput or
21699 			 * ip_rput following successful resolution.
21700 			 */
21701 			mp->b_prev = NULL;
21702 			mp->b_next = NULL;
21703 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21704 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21705 			    "ip_wput_end: q %p (%S)", q, "newroute");
21706 			if (xmit_ill != NULL)
21707 				ill_refrele(xmit_ill);
21708 			if (need_decref)
21709 				CONN_DEC_REF(connp);
21710 			return;
21711 		}
21712 	}
21713 
21714 	/* We now know where we are going with it. */
21715 
21716 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21717 	    "ip_wput_end: q %p (%S)", q, "end");
21718 
21719 	/*
21720 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21721 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21722 	 */
21723 	if (ire->ire_flags & RTF_MULTIRT) {
21724 		/*
21725 		 * Force the TTL of multirouted packets if required.
21726 		 * The TTL of such packets is bounded by the
21727 		 * ip_multirt_ttl ndd variable.
21728 		 */
21729 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21730 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21731 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21732 			    "(was %d), dst 0x%08x\n",
21733 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21734 			    ntohl(ire->ire_addr)));
21735 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21736 		}
21737 		/*
21738 		 * At this point, we check to see if there are any pending
21739 		 * unresolved routes. ire_multirt_resolvable()
21740 		 * checks in O(n) that all IRE_OFFSUBNET ire
21741 		 * entries for the packet's destination and
21742 		 * flagged RTF_MULTIRT are currently resolved.
21743 		 * If some remain unresolved, we make a copy
21744 		 * of the current message. It will be used
21745 		 * to initiate additional route resolutions.
21746 		 */
21747 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21748 		    msg_getlabel(first_mp), ipst);
21749 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21750 		    "multirt_need_resolve %d, first_mp %p\n",
21751 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21752 		if (multirt_need_resolve) {
21753 			copy_mp = copymsg(first_mp);
21754 			if (copy_mp != NULL) {
21755 				MULTIRT_DEBUG_TAG(copy_mp);
21756 			}
21757 		}
21758 	}
21759 
21760 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21761 	/*
21762 	 * Try to resolve another multiroute if
21763 	 * ire_multirt_resolvable() deemed it necessary.
21764 	 * At this point, we need to distinguish
21765 	 * multicasts from other packets. For multicasts,
21766 	 * we call ip_newroute_ipif() and request that both
21767 	 * multirouting and setsrc flags are checked.
21768 	 */
21769 	if (copy_mp != NULL) {
21770 		if (CLASSD(dst)) {
21771 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21772 			if (ipif) {
21773 				ASSERT(infop->ip_opt_ill_index == 0);
21774 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21775 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21776 				ipif_refrele(ipif);
21777 			} else {
21778 				MULTIRT_DEBUG_UNTAG(copy_mp);
21779 				freemsg(copy_mp);
21780 				copy_mp = NULL;
21781 			}
21782 		} else {
21783 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21784 		}
21785 	}
21786 	if (xmit_ill != NULL)
21787 		ill_refrele(xmit_ill);
21788 	if (need_decref)
21789 		CONN_DEC_REF(connp);
21790 	return;
21791 
21792 icmp_parameter_problem:
21793 	/* could not have originated externally */
21794 	ASSERT(mp->b_prev == NULL);
21795 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21796 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21797 		/* it's the IP header length that's in trouble */
21798 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21799 		first_mp = NULL;
21800 	}
21801 
21802 discard_pkt:
21803 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21804 drop_pkt:
21805 	ip1dbg(("ip_wput: dropped packet\n"));
21806 	if (ire != NULL)
21807 		ire_refrele(ire);
21808 	if (need_decref)
21809 		CONN_DEC_REF(connp);
21810 	freemsg(first_mp);
21811 	if (xmit_ill != NULL)
21812 		ill_refrele(xmit_ill);
21813 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21814 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21815 }
21816 
21817 /*
21818  * If this is a conn_t queue, then we pass in the conn. This includes the
21819  * zoneid.
21820  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21821  * in which case we use the global zoneid since those are all part of
21822  * the global zone.
21823  */
21824 void
21825 ip_wput(queue_t *q, mblk_t *mp)
21826 {
21827 	if (CONN_Q(q))
21828 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21829 	else
21830 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21831 }
21832 
21833 /*
21834  *
21835  * The following rules must be observed when accessing any ipif or ill
21836  * that has been cached in the conn. Typically conn_outgoing_ill,
21837  * conn_multicast_ipif and conn_multicast_ill.
21838  *
21839  * Access: The ipif or ill pointed to from the conn can be accessed under
21840  * the protection of the conn_lock or after it has been refheld under the
21841  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21842  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21843  * The reason for this is that a concurrent unplumb could actually be
21844  * cleaning up these cached pointers by walking the conns and might have
21845  * finished cleaning up the conn in question. The macros check that an
21846  * unplumb has not yet started on the ipif or ill.
21847  *
21848  * Caching: An ipif or ill pointer may be cached in the conn only after
21849  * making sure that an unplumb has not started. So the caching is done
21850  * while holding both the conn_lock and the ill_lock and after using the
21851  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21852  * flag before starting the cleanup of conns.
21853  *
21854  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21855  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21856  * or a reference to the ipif or a reference to an ire that references the
21857  * ipif. An ipif only changes its ill when migrating from an underlying ill
21858  * to an IPMP ill in ipif_up().
21859  */
21860 ipif_t *
21861 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21862 {
21863 	ipif_t	*ipif;
21864 	ill_t	*ill;
21865 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21866 
21867 	*err = 0;
21868 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21869 	mutex_enter(&connp->conn_lock);
21870 	ipif = *ipifp;
21871 	if (ipif != NULL) {
21872 		ill = ipif->ipif_ill;
21873 		mutex_enter(&ill->ill_lock);
21874 		if (IPIF_CAN_LOOKUP(ipif)) {
21875 			ipif_refhold_locked(ipif);
21876 			mutex_exit(&ill->ill_lock);
21877 			mutex_exit(&connp->conn_lock);
21878 			rw_exit(&ipst->ips_ill_g_lock);
21879 			return (ipif);
21880 		} else {
21881 			*err = IPIF_LOOKUP_FAILED;
21882 		}
21883 		mutex_exit(&ill->ill_lock);
21884 	}
21885 	mutex_exit(&connp->conn_lock);
21886 	rw_exit(&ipst->ips_ill_g_lock);
21887 	return (NULL);
21888 }
21889 
21890 ill_t *
21891 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21892 {
21893 	ill_t	*ill;
21894 
21895 	*err = 0;
21896 	mutex_enter(&connp->conn_lock);
21897 	ill = *illp;
21898 	if (ill != NULL) {
21899 		mutex_enter(&ill->ill_lock);
21900 		if (ILL_CAN_LOOKUP(ill)) {
21901 			ill_refhold_locked(ill);
21902 			mutex_exit(&ill->ill_lock);
21903 			mutex_exit(&connp->conn_lock);
21904 			return (ill);
21905 		} else {
21906 			*err = ILL_LOOKUP_FAILED;
21907 		}
21908 		mutex_exit(&ill->ill_lock);
21909 	}
21910 	mutex_exit(&connp->conn_lock);
21911 	return (NULL);
21912 }
21913 
21914 static int
21915 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21916 {
21917 	ill_t	*ill;
21918 
21919 	ill = ipif->ipif_ill;
21920 	mutex_enter(&connp->conn_lock);
21921 	mutex_enter(&ill->ill_lock);
21922 	if (IPIF_CAN_LOOKUP(ipif)) {
21923 		*ipifp = ipif;
21924 		mutex_exit(&ill->ill_lock);
21925 		mutex_exit(&connp->conn_lock);
21926 		return (0);
21927 	}
21928 	mutex_exit(&ill->ill_lock);
21929 	mutex_exit(&connp->conn_lock);
21930 	return (IPIF_LOOKUP_FAILED);
21931 }
21932 
21933 /*
21934  * This is called if the outbound datagram needs fragmentation.
21935  *
21936  * NOTE : This function does not ire_refrele the ire argument passed in.
21937  */
21938 static void
21939 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21940     ip_stack_t *ipst, conn_t *connp)
21941 {
21942 	ipha_t		*ipha;
21943 	mblk_t		*mp;
21944 	uint32_t	v_hlen_tos_len;
21945 	uint32_t	max_frag;
21946 	uint32_t	frag_flag;
21947 	boolean_t	dont_use;
21948 
21949 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21950 		mp = ipsec_mp->b_cont;
21951 	} else {
21952 		mp = ipsec_mp;
21953 	}
21954 
21955 	ipha = (ipha_t *)mp->b_rptr;
21956 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21957 
21958 #ifdef	_BIG_ENDIAN
21959 #define	V_HLEN	(v_hlen_tos_len >> 24)
21960 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21961 #else
21962 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21963 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21964 #endif
21965 
21966 #ifndef SPEED_BEFORE_SAFETY
21967 	/*
21968 	 * Check that ipha_length is consistent with
21969 	 * the mblk length
21970 	 */
21971 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21972 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21973 		    LENGTH, msgdsize(mp)));
21974 		freemsg(ipsec_mp);
21975 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21976 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21977 		    "packet length mismatch");
21978 		return;
21979 	}
21980 #endif
21981 	/*
21982 	 * Don't use frag_flag if pre-built packet or source
21983 	 * routed or if multicast (since multicast packets do not solicit
21984 	 * ICMP "packet too big" messages). Get the values of
21985 	 * max_frag and frag_flag atomically by acquiring the
21986 	 * ire_lock.
21987 	 */
21988 	mutex_enter(&ire->ire_lock);
21989 	max_frag = ire->ire_max_frag;
21990 	frag_flag = ire->ire_frag_flag;
21991 	mutex_exit(&ire->ire_lock);
21992 
21993 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21994 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21995 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21996 
21997 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21998 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21999 }
22000 
22001 /*
22002  * Used for deciding the MSS size for the upper layer. Thus
22003  * we need to check the outbound policy values in the conn.
22004  */
22005 int
22006 conn_ipsec_length(conn_t *connp)
22007 {
22008 	ipsec_latch_t *ipl;
22009 
22010 	ipl = connp->conn_latch;
22011 	if (ipl == NULL)
22012 		return (0);
22013 
22014 	if (ipl->ipl_out_policy == NULL)
22015 		return (0);
22016 
22017 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
22018 }
22019 
22020 /*
22021  * Returns an estimate of the IPsec headers size. This is used if
22022  * we don't want to call into IPsec to get the exact size.
22023  */
22024 int
22025 ipsec_out_extra_length(mblk_t *ipsec_mp)
22026 {
22027 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
22028 	ipsec_action_t *a;
22029 
22030 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
22031 	if (!io->ipsec_out_secure)
22032 		return (0);
22033 
22034 	a = io->ipsec_out_act;
22035 
22036 	if (a == NULL) {
22037 		ASSERT(io->ipsec_out_policy != NULL);
22038 		a = io->ipsec_out_policy->ipsp_act;
22039 	}
22040 	ASSERT(a != NULL);
22041 
22042 	return (a->ipa_ovhd);
22043 }
22044 
22045 /*
22046  * Returns an estimate of the IPsec headers size. This is used if
22047  * we don't want to call into IPsec to get the exact size.
22048  */
22049 int
22050 ipsec_in_extra_length(mblk_t *ipsec_mp)
22051 {
22052 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22053 	ipsec_action_t *a;
22054 
22055 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22056 
22057 	a = ii->ipsec_in_action;
22058 	return (a == NULL ? 0 : a->ipa_ovhd);
22059 }
22060 
22061 /*
22062  * If there are any source route options, return the true final
22063  * destination. Otherwise, return the destination.
22064  */
22065 ipaddr_t
22066 ip_get_dst(ipha_t *ipha)
22067 {
22068 	ipoptp_t	opts;
22069 	uchar_t		*opt;
22070 	uint8_t		optval;
22071 	uint8_t		optlen;
22072 	ipaddr_t	dst;
22073 	uint32_t off;
22074 
22075 	dst = ipha->ipha_dst;
22076 
22077 	if (IS_SIMPLE_IPH(ipha))
22078 		return (dst);
22079 
22080 	for (optval = ipoptp_first(&opts, ipha);
22081 	    optval != IPOPT_EOL;
22082 	    optval = ipoptp_next(&opts)) {
22083 		opt = opts.ipoptp_cur;
22084 		optlen = opts.ipoptp_len;
22085 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22086 		switch (optval) {
22087 		case IPOPT_SSRR:
22088 		case IPOPT_LSRR:
22089 			off = opt[IPOPT_OFFSET];
22090 			/*
22091 			 * If one of the conditions is true, it means
22092 			 * end of options and dst already has the right
22093 			 * value.
22094 			 */
22095 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22096 				off = optlen - IP_ADDR_LEN;
22097 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22098 			}
22099 			return (dst);
22100 		default:
22101 			break;
22102 		}
22103 	}
22104 
22105 	return (dst);
22106 }
22107 
22108 mblk_t *
22109 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22110     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22111 {
22112 	ipsec_out_t	*io;
22113 	mblk_t		*first_mp;
22114 	boolean_t policy_present;
22115 	ip_stack_t	*ipst;
22116 	ipsec_stack_t	*ipss;
22117 
22118 	ASSERT(ire != NULL);
22119 	ipst = ire->ire_ipst;
22120 	ipss = ipst->ips_netstack->netstack_ipsec;
22121 
22122 	first_mp = mp;
22123 	if (mp->b_datap->db_type == M_CTL) {
22124 		io = (ipsec_out_t *)first_mp->b_rptr;
22125 		/*
22126 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22127 		 *
22128 		 * 1) There is per-socket policy (including cached global
22129 		 *    policy) or a policy on the IP-in-IP tunnel.
22130 		 * 2) There is no per-socket policy, but it is
22131 		 *    a multicast packet that needs to go out
22132 		 *    on a specific interface. This is the case
22133 		 *    where (ip_wput and ip_wput_multicast) attaches
22134 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22135 		 *
22136 		 * In case (2) we check with global policy to
22137 		 * see if there is a match and set the ill_index
22138 		 * appropriately so that we can lookup the ire
22139 		 * properly in ip_wput_ipsec_out.
22140 		 */
22141 
22142 		/*
22143 		 * ipsec_out_use_global_policy is set to B_FALSE
22144 		 * in ipsec_in_to_out(). Refer to that function for
22145 		 * details.
22146 		 */
22147 		if ((io->ipsec_out_latch == NULL) &&
22148 		    (io->ipsec_out_use_global_policy)) {
22149 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22150 			    ire, connp, unspec_src, zoneid));
22151 		}
22152 		if (!io->ipsec_out_secure) {
22153 			/*
22154 			 * If this is not a secure packet, drop
22155 			 * the IPSEC_OUT mp and treat it as a clear
22156 			 * packet. This happens when we are sending
22157 			 * a ICMP reply back to a clear packet. See
22158 			 * ipsec_in_to_out() for details.
22159 			 */
22160 			mp = first_mp->b_cont;
22161 			freeb(first_mp);
22162 		}
22163 		return (mp);
22164 	}
22165 	/*
22166 	 * See whether we need to attach a global policy here. We
22167 	 * don't depend on the conn (as it could be null) for deciding
22168 	 * what policy this datagram should go through because it
22169 	 * should have happened in ip_wput if there was some
22170 	 * policy. This normally happens for connections which are not
22171 	 * fully bound preventing us from caching policies in
22172 	 * ip_bind. Packets coming from the TCP listener/global queue
22173 	 * - which are non-hard_bound - could also be affected by
22174 	 * applying policy here.
22175 	 *
22176 	 * If this packet is coming from tcp global queue or listener,
22177 	 * we will be applying policy here.  This may not be *right*
22178 	 * if these packets are coming from the detached connection as
22179 	 * it could have gone in clear before. This happens only if a
22180 	 * TCP connection started when there is no policy and somebody
22181 	 * added policy before it became detached. Thus packets of the
22182 	 * detached connection could go out secure and the other end
22183 	 * would drop it because it will be expecting in clear. The
22184 	 * converse is not true i.e if somebody starts a TCP
22185 	 * connection and deletes the policy, all the packets will
22186 	 * still go out with the policy that existed before deleting
22187 	 * because ip_unbind sends up policy information which is used
22188 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22189 	 * TCP to attach a dummy IPSEC_OUT and set
22190 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22191 	 * affect performance for normal cases, we are not doing it.
22192 	 * Thus, set policy before starting any TCP connections.
22193 	 *
22194 	 * NOTE - We might apply policy even for a hard bound connection
22195 	 * - for which we cached policy in ip_bind - if somebody added
22196 	 * global policy after we inherited the policy in ip_bind.
22197 	 * This means that the packets that were going out in clear
22198 	 * previously would start going secure and hence get dropped
22199 	 * on the other side. To fix this, TCP attaches a dummy
22200 	 * ipsec_out and make sure that we don't apply global policy.
22201 	 */
22202 	if (ipha != NULL)
22203 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22204 	else
22205 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22206 	if (!policy_present)
22207 		return (mp);
22208 
22209 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22210 	    zoneid));
22211 }
22212 
22213 /*
22214  * This function does the ire_refrele of the ire passed in as the
22215  * argument. As this function looks up more ires i.e broadcast ires,
22216  * it needs to REFRELE them. Currently, for simplicity we don't
22217  * differentiate the one passed in and looked up here. We always
22218  * REFRELE.
22219  * IPQoS Notes:
22220  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22221  * IPsec packets are done in ipsec_out_process.
22222  */
22223 void
22224 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22225     zoneid_t zoneid)
22226 {
22227 	ipha_t		*ipha;
22228 #define	rptr	((uchar_t *)ipha)
22229 	queue_t		*stq;
22230 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22231 	uint32_t	v_hlen_tos_len;
22232 	uint32_t	ttl_protocol;
22233 	ipaddr_t	src;
22234 	ipaddr_t	dst;
22235 	uint32_t	cksum;
22236 	ipaddr_t	orig_src;
22237 	ire_t		*ire1;
22238 	mblk_t		*next_mp;
22239 	uint_t		hlen;
22240 	uint16_t	*up;
22241 	uint32_t	max_frag = ire->ire_max_frag;
22242 	ill_t		*ill = ire_to_ill(ire);
22243 	int		clusterwide;
22244 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22245 	int		ipsec_len;
22246 	mblk_t		*first_mp;
22247 	ipsec_out_t	*io;
22248 	boolean_t	conn_dontroute;		/* conn value for multicast */
22249 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22250 	boolean_t	multicast_forward;	/* Should we forward ? */
22251 	boolean_t	unspec_src;
22252 	ill_t		*conn_outgoing_ill = NULL;
22253 	ill_t		*ire_ill;
22254 	ill_t		*ire1_ill;
22255 	ill_t		*out_ill;
22256 	uint32_t 	ill_index = 0;
22257 	boolean_t	multirt_send = B_FALSE;
22258 	int		err;
22259 	ipxmit_state_t	pktxmit_state;
22260 	ip_stack_t	*ipst = ire->ire_ipst;
22261 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22262 
22263 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22264 	    "ip_wput_ire_start: q %p", q);
22265 
22266 	multicast_forward = B_FALSE;
22267 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22268 
22269 	if (ire->ire_flags & RTF_MULTIRT) {
22270 		/*
22271 		 * Multirouting case. The bucket where ire is stored
22272 		 * probably holds other RTF_MULTIRT flagged ire
22273 		 * to the destination. In this call to ip_wput_ire,
22274 		 * we attempt to send the packet through all
22275 		 * those ires. Thus, we first ensure that ire is the
22276 		 * first RTF_MULTIRT ire in the bucket,
22277 		 * before walking the ire list.
22278 		 */
22279 		ire_t *first_ire;
22280 		irb_t *irb = ire->ire_bucket;
22281 		ASSERT(irb != NULL);
22282 
22283 		/* Make sure we do not omit any multiroute ire. */
22284 		IRB_REFHOLD(irb);
22285 		for (first_ire = irb->irb_ire;
22286 		    first_ire != NULL;
22287 		    first_ire = first_ire->ire_next) {
22288 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22289 			    (first_ire->ire_addr == ire->ire_addr) &&
22290 			    !(first_ire->ire_marks &
22291 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22292 				break;
22293 		}
22294 
22295 		if ((first_ire != NULL) && (first_ire != ire)) {
22296 			IRE_REFHOLD(first_ire);
22297 			ire_refrele(ire);
22298 			ire = first_ire;
22299 			ill = ire_to_ill(ire);
22300 		}
22301 		IRB_REFRELE(irb);
22302 	}
22303 
22304 	/*
22305 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22306 	 * for performance we don't grab the mutexs in the fastpath
22307 	 */
22308 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22309 	    connp->conn_outgoing_ill != NULL) {
22310 		conn_outgoing_ill = conn_get_held_ill(connp,
22311 		    &connp->conn_outgoing_ill, &err);
22312 		if (err == ILL_LOOKUP_FAILED) {
22313 			ire_refrele(ire);
22314 			freemsg(mp);
22315 			return;
22316 		}
22317 	}
22318 
22319 	if (mp->b_datap->db_type != M_CTL) {
22320 		ipha = (ipha_t *)mp->b_rptr;
22321 	} else {
22322 		io = (ipsec_out_t *)mp->b_rptr;
22323 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22324 		ASSERT(zoneid == io->ipsec_out_zoneid);
22325 		ASSERT(zoneid != ALL_ZONES);
22326 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22327 		dst = ipha->ipha_dst;
22328 		/*
22329 		 * For the multicast case, ipsec_out carries conn_dontroute and
22330 		 * conn_multicast_loop as conn may not be available here. We
22331 		 * need this for multicast loopback and forwarding which is done
22332 		 * later in the code.
22333 		 */
22334 		if (CLASSD(dst)) {
22335 			conn_dontroute = io->ipsec_out_dontroute;
22336 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22337 			/*
22338 			 * If conn_dontroute is not set or conn_multicast_loop
22339 			 * is set, we need to do forwarding/loopback. For
22340 			 * datagrams from ip_wput_multicast, conn_dontroute is
22341 			 * set to B_TRUE and conn_multicast_loop is set to
22342 			 * B_FALSE so that we neither do forwarding nor
22343 			 * loopback.
22344 			 */
22345 			if (!conn_dontroute || conn_multicast_loop)
22346 				multicast_forward = B_TRUE;
22347 		}
22348 	}
22349 
22350 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22351 	    ire->ire_zoneid != ALL_ZONES) {
22352 		/*
22353 		 * When a zone sends a packet to another zone, we try to deliver
22354 		 * the packet under the same conditions as if the destination
22355 		 * was a real node on the network. To do so, we look for a
22356 		 * matching route in the forwarding table.
22357 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22358 		 * ip_newroute() does.
22359 		 * Note that IRE_LOCAL are special, since they are used
22360 		 * when the zoneid doesn't match in some cases. This means that
22361 		 * we need to handle ipha_src differently since ire_src_addr
22362 		 * belongs to the receiving zone instead of the sending zone.
22363 		 * When ip_restrict_interzone_loopback is set, then
22364 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22365 		 * for loopback between zones when the logical "Ethernet" would
22366 		 * have looped them back.
22367 		 */
22368 		ire_t *src_ire;
22369 
22370 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22371 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22372 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22373 		if (src_ire != NULL &&
22374 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22375 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22376 		    ire_local_same_lan(ire, src_ire))) {
22377 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22378 				ipha->ipha_src = src_ire->ire_src_addr;
22379 			ire_refrele(src_ire);
22380 		} else {
22381 			ire_refrele(ire);
22382 			if (conn_outgoing_ill != NULL)
22383 				ill_refrele(conn_outgoing_ill);
22384 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22385 			if (src_ire != NULL) {
22386 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22387 					ire_refrele(src_ire);
22388 					freemsg(mp);
22389 					return;
22390 				}
22391 				ire_refrele(src_ire);
22392 			}
22393 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22394 				/* Failed */
22395 				freemsg(mp);
22396 				return;
22397 			}
22398 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22399 			    ipst);
22400 			return;
22401 		}
22402 	}
22403 
22404 	if (mp->b_datap->db_type == M_CTL ||
22405 	    ipss->ipsec_outbound_v4_policy_present) {
22406 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22407 		    unspec_src, zoneid);
22408 		if (mp == NULL) {
22409 			ire_refrele(ire);
22410 			if (conn_outgoing_ill != NULL)
22411 				ill_refrele(conn_outgoing_ill);
22412 			return;
22413 		}
22414 		/*
22415 		 * Trusted Extensions supports all-zones interfaces, so
22416 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22417 		 * the global zone.
22418 		 */
22419 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22420 			io = (ipsec_out_t *)mp->b_rptr;
22421 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22422 			zoneid = io->ipsec_out_zoneid;
22423 		}
22424 	}
22425 
22426 	first_mp = mp;
22427 	ipsec_len = 0;
22428 
22429 	if (first_mp->b_datap->db_type == M_CTL) {
22430 		io = (ipsec_out_t *)first_mp->b_rptr;
22431 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22432 		mp = first_mp->b_cont;
22433 		ipsec_len = ipsec_out_extra_length(first_mp);
22434 		ASSERT(ipsec_len >= 0);
22435 		/* We already picked up the zoneid from the M_CTL above */
22436 		ASSERT(zoneid == io->ipsec_out_zoneid);
22437 		ASSERT(zoneid != ALL_ZONES);
22438 
22439 		/*
22440 		 * Drop M_CTL here if IPsec processing is not needed.
22441 		 * (Non-IPsec use of M_CTL extracted any information it
22442 		 * needed above).
22443 		 */
22444 		if (ipsec_len == 0) {
22445 			freeb(first_mp);
22446 			first_mp = mp;
22447 		}
22448 	}
22449 
22450 	/*
22451 	 * Fast path for ip_wput_ire
22452 	 */
22453 
22454 	ipha = (ipha_t *)mp->b_rptr;
22455 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22456 	dst = ipha->ipha_dst;
22457 
22458 	/*
22459 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22460 	 * if the socket is a SOCK_RAW type. The transport checksum should
22461 	 * be provided in the pre-built packet, so we don't need to compute it.
22462 	 * Also, other application set flags, like DF, should not be altered.
22463 	 * Other transport MUST pass down zero.
22464 	 */
22465 	ip_hdr_included = ipha->ipha_ident;
22466 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22467 
22468 	if (CLASSD(dst)) {
22469 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22470 		    ntohl(dst),
22471 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22472 		    ntohl(ire->ire_addr)));
22473 	}
22474 
22475 /* Macros to extract header fields from data already in registers */
22476 #ifdef	_BIG_ENDIAN
22477 #define	V_HLEN	(v_hlen_tos_len >> 24)
22478 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22479 #define	PROTO	(ttl_protocol & 0xFF)
22480 #else
22481 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22482 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22483 #define	PROTO	(ttl_protocol >> 8)
22484 #endif
22485 
22486 	orig_src = src = ipha->ipha_src;
22487 	/* (The loop back to "another" is explained down below.) */
22488 another:;
22489 	/*
22490 	 * Assign an ident value for this packet.  We assign idents on
22491 	 * a per destination basis out of the IRE.  There could be
22492 	 * other threads targeting the same destination, so we have to
22493 	 * arrange for a atomic increment.  Note that we use a 32-bit
22494 	 * atomic add because it has better performance than its
22495 	 * 16-bit sibling.
22496 	 *
22497 	 * If running in cluster mode and if the source address
22498 	 * belongs to a replicated service then vector through
22499 	 * cl_inet_ipident vector to allocate ip identifier
22500 	 * NOTE: This is a contract private interface with the
22501 	 * clustering group.
22502 	 */
22503 	clusterwide = 0;
22504 	if (cl_inet_ipident) {
22505 		ASSERT(cl_inet_isclusterwide);
22506 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22507 
22508 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22509 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22510 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22511 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22512 			    (uint8_t *)(uintptr_t)dst, NULL);
22513 			clusterwide = 1;
22514 		}
22515 	}
22516 	if (!clusterwide) {
22517 		ipha->ipha_ident =
22518 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22519 	}
22520 
22521 #ifndef _BIG_ENDIAN
22522 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22523 #endif
22524 
22525 	/*
22526 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22527 	 * This is needed to obey conn_unspec_src when packets go through
22528 	 * ip_newroute + arp.
22529 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22530 	 */
22531 	if (src == INADDR_ANY && !unspec_src) {
22532 		/*
22533 		 * Assign the appropriate source address from the IRE if none
22534 		 * was specified.
22535 		 */
22536 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22537 
22538 		src = ire->ire_src_addr;
22539 		if (connp == NULL) {
22540 			ip1dbg(("ip_wput_ire: no connp and no src "
22541 			    "address for dst 0x%x, using src 0x%x\n",
22542 			    ntohl(dst),
22543 			    ntohl(src)));
22544 		}
22545 		ipha->ipha_src = src;
22546 	}
22547 	stq = ire->ire_stq;
22548 
22549 	/*
22550 	 * We only allow ire chains for broadcasts since there will
22551 	 * be multiple IRE_CACHE entries for the same multicast
22552 	 * address (one per ipif).
22553 	 */
22554 	next_mp = NULL;
22555 
22556 	/* broadcast packet */
22557 	if (ire->ire_type == IRE_BROADCAST)
22558 		goto broadcast;
22559 
22560 	/* loopback ? */
22561 	if (stq == NULL)
22562 		goto nullstq;
22563 
22564 	/* The ill_index for outbound ILL */
22565 	ill_index = Q_TO_INDEX(stq);
22566 
22567 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22568 	ttl_protocol = ((uint16_t *)ipha)[4];
22569 
22570 	/* pseudo checksum (do it in parts for IP header checksum) */
22571 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22572 
22573 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22574 		queue_t *dev_q = stq->q_next;
22575 
22576 		/*
22577 		 * For DIRECT_CAPABLE, we do flow control at
22578 		 * the time of sending the packet. See
22579 		 * ILL_SEND_TX().
22580 		 */
22581 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22582 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22583 			goto blocked;
22584 
22585 		if ((PROTO == IPPROTO_UDP) &&
22586 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22587 			hlen = (V_HLEN & 0xF) << 2;
22588 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22589 			if (*up != 0) {
22590 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22591 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22592 				/* Software checksum? */
22593 				if (DB_CKSUMFLAGS(mp) == 0) {
22594 					IP_STAT(ipst, ip_out_sw_cksum);
22595 					IP_STAT_UPDATE(ipst,
22596 					    ip_udp_out_sw_cksum_bytes,
22597 					    LENGTH - hlen);
22598 				}
22599 			}
22600 		}
22601 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22602 		hlen = (V_HLEN & 0xF) << 2;
22603 		if (PROTO == IPPROTO_TCP) {
22604 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22605 			/*
22606 			 * The packet header is processed once and for all, even
22607 			 * in the multirouting case. We disable hardware
22608 			 * checksum if the packet is multirouted, as it will be
22609 			 * replicated via several interfaces, and not all of
22610 			 * them may have this capability.
22611 			 */
22612 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22613 			    LENGTH, max_frag, ipsec_len, cksum);
22614 			/* Software checksum? */
22615 			if (DB_CKSUMFLAGS(mp) == 0) {
22616 				IP_STAT(ipst, ip_out_sw_cksum);
22617 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22618 				    LENGTH - hlen);
22619 			}
22620 		} else {
22621 			sctp_hdr_t	*sctph;
22622 
22623 			ASSERT(PROTO == IPPROTO_SCTP);
22624 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22625 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22626 			/*
22627 			 * Zero out the checksum field to ensure proper
22628 			 * checksum calculation.
22629 			 */
22630 			sctph->sh_chksum = 0;
22631 #ifdef	DEBUG
22632 			if (!skip_sctp_cksum)
22633 #endif
22634 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22635 		}
22636 	}
22637 
22638 	/*
22639 	 * If this is a multicast packet and originated from ip_wput
22640 	 * we need to do loopback and forwarding checks. If it comes
22641 	 * from ip_wput_multicast, we SHOULD not do this.
22642 	 */
22643 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22644 
22645 	/* checksum */
22646 	cksum += ttl_protocol;
22647 
22648 	/* fragment the packet */
22649 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22650 		goto fragmentit;
22651 	/*
22652 	 * Don't use frag_flag if packet is pre-built or source
22653 	 * routed or if multicast (since multicast packets do
22654 	 * not solicit ICMP "packet too big" messages).
22655 	 */
22656 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22657 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22658 	    !ip_source_route_included(ipha)) &&
22659 	    !CLASSD(ipha->ipha_dst))
22660 		ipha->ipha_fragment_offset_and_flags |=
22661 		    htons(ire->ire_frag_flag);
22662 
22663 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22664 		/* calculate IP header checksum */
22665 		cksum += ipha->ipha_ident;
22666 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22667 		cksum += ipha->ipha_fragment_offset_and_flags;
22668 
22669 		/* IP options present */
22670 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22671 		if (hlen)
22672 			goto checksumoptions;
22673 
22674 		/* calculate hdr checksum */
22675 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22676 		cksum = ~(cksum + (cksum >> 16));
22677 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22678 	}
22679 	if (ipsec_len != 0) {
22680 		/*
22681 		 * We will do the rest of the processing after
22682 		 * we come back from IPsec in ip_wput_ipsec_out().
22683 		 */
22684 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22685 
22686 		io = (ipsec_out_t *)first_mp->b_rptr;
22687 		io->ipsec_out_ill_index =
22688 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22689 		ipsec_out_process(q, first_mp, ire, 0);
22690 		ire_refrele(ire);
22691 		if (conn_outgoing_ill != NULL)
22692 			ill_refrele(conn_outgoing_ill);
22693 		return;
22694 	}
22695 
22696 	/*
22697 	 * In most cases, the emission loop below is entered only
22698 	 * once. Only in the case where the ire holds the
22699 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22700 	 * flagged ires in the bucket, and send the packet
22701 	 * through all crossed RTF_MULTIRT routes.
22702 	 */
22703 	if (ire->ire_flags & RTF_MULTIRT) {
22704 		multirt_send = B_TRUE;
22705 	}
22706 	do {
22707 		if (multirt_send) {
22708 			irb_t *irb;
22709 			/*
22710 			 * We are in a multiple send case, need to get
22711 			 * the next ire and make a duplicate of the packet.
22712 			 * ire1 holds here the next ire to process in the
22713 			 * bucket. If multirouting is expected,
22714 			 * any non-RTF_MULTIRT ire that has the
22715 			 * right destination address is ignored.
22716 			 */
22717 			irb = ire->ire_bucket;
22718 			ASSERT(irb != NULL);
22719 
22720 			IRB_REFHOLD(irb);
22721 			for (ire1 = ire->ire_next;
22722 			    ire1 != NULL;
22723 			    ire1 = ire1->ire_next) {
22724 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22725 					continue;
22726 				if (ire1->ire_addr != ire->ire_addr)
22727 					continue;
22728 				if (ire1->ire_marks &
22729 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22730 					continue;
22731 
22732 				/* Got one */
22733 				IRE_REFHOLD(ire1);
22734 				break;
22735 			}
22736 			IRB_REFRELE(irb);
22737 
22738 			if (ire1 != NULL) {
22739 				next_mp = copyb(mp);
22740 				if ((next_mp == NULL) ||
22741 				    ((mp->b_cont != NULL) &&
22742 				    ((next_mp->b_cont =
22743 				    dupmsg(mp->b_cont)) == NULL))) {
22744 					freemsg(next_mp);
22745 					next_mp = NULL;
22746 					ire_refrele(ire1);
22747 					ire1 = NULL;
22748 				}
22749 			}
22750 
22751 			/* Last multiroute ire; don't loop anymore. */
22752 			if (ire1 == NULL) {
22753 				multirt_send = B_FALSE;
22754 			}
22755 		}
22756 
22757 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22758 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22759 		    mblk_t *, mp);
22760 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22761 		    ipst->ips_ipv4firewall_physical_out,
22762 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22763 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22764 
22765 		if (mp == NULL)
22766 			goto release_ire_and_ill;
22767 
22768 		if (ipst->ips_ipobs_enabled) {
22769 			zoneid_t szone;
22770 
22771 			/*
22772 			 * On the outbound path the destination zone will be
22773 			 * unknown as we're sending this packet out on the
22774 			 * wire.
22775 			 */
22776 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22777 			    ALL_ZONES);
22778 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22779 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22780 		}
22781 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22782 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22783 
22784 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22785 
22786 		if ((pktxmit_state == SEND_FAILED) ||
22787 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22788 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22789 			    "- packet dropped\n"));
22790 release_ire_and_ill:
22791 			ire_refrele(ire);
22792 			if (next_mp != NULL) {
22793 				freemsg(next_mp);
22794 				ire_refrele(ire1);
22795 			}
22796 			if (conn_outgoing_ill != NULL)
22797 				ill_refrele(conn_outgoing_ill);
22798 			return;
22799 		}
22800 
22801 		if (CLASSD(dst)) {
22802 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22803 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22804 			    LENGTH);
22805 		}
22806 
22807 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22808 		    "ip_wput_ire_end: q %p (%S)",
22809 		    q, "last copy out");
22810 		IRE_REFRELE(ire);
22811 
22812 		if (multirt_send) {
22813 			ASSERT(ire1);
22814 			/*
22815 			 * Proceed with the next RTF_MULTIRT ire,
22816 			 * Also set up the send-to queue accordingly.
22817 			 */
22818 			ire = ire1;
22819 			ire1 = NULL;
22820 			stq = ire->ire_stq;
22821 			mp = next_mp;
22822 			next_mp = NULL;
22823 			ipha = (ipha_t *)mp->b_rptr;
22824 			ill_index = Q_TO_INDEX(stq);
22825 			ill = (ill_t *)stq->q_ptr;
22826 		}
22827 	} while (multirt_send);
22828 	if (conn_outgoing_ill != NULL)
22829 		ill_refrele(conn_outgoing_ill);
22830 	return;
22831 
22832 	/*
22833 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22834 	 */
22835 broadcast:
22836 	{
22837 		/*
22838 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22839 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22840 		 * can be overridden stack-wide through the ip_broadcast_ttl
22841 		 * ndd tunable, or on a per-connection basis through the
22842 		 * IP_BROADCAST_TTL socket option.
22843 		 *
22844 		 * In the event that we are replying to incoming ICMP packets,
22845 		 * connp could be NULL.
22846 		 */
22847 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22848 		if (connp != NULL) {
22849 			if (connp->conn_dontroute)
22850 				ipha->ipha_ttl = 1;
22851 			else if (connp->conn_broadcast_ttl != 0)
22852 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22853 		}
22854 
22855 		/*
22856 		 * Note that we are not doing a IRB_REFHOLD here.
22857 		 * Actually we don't care if the list changes i.e
22858 		 * if somebody deletes an IRE from the list while
22859 		 * we drop the lock, the next time we come around
22860 		 * ire_next will be NULL and hence we won't send
22861 		 * out multiple copies which is fine.
22862 		 */
22863 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22864 		ire1 = ire->ire_next;
22865 		if (conn_outgoing_ill != NULL) {
22866 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22867 				ASSERT(ire1 == ire->ire_next);
22868 				if (ire1 != NULL && ire1->ire_addr == dst) {
22869 					ire_refrele(ire);
22870 					ire = ire1;
22871 					IRE_REFHOLD(ire);
22872 					ire1 = ire->ire_next;
22873 					continue;
22874 				}
22875 				rw_exit(&ire->ire_bucket->irb_lock);
22876 				/* Did not find a matching ill */
22877 				ip1dbg(("ip_wput_ire: broadcast with no "
22878 				    "matching IP_BOUND_IF ill %s dst %x\n",
22879 				    conn_outgoing_ill->ill_name, dst));
22880 				freemsg(first_mp);
22881 				if (ire != NULL)
22882 					ire_refrele(ire);
22883 				ill_refrele(conn_outgoing_ill);
22884 				return;
22885 			}
22886 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22887 			/*
22888 			 * If the next IRE has the same address and is not one
22889 			 * of the two copies that we need to send, try to see
22890 			 * whether this copy should be sent at all. This
22891 			 * assumes that we insert loopbacks first and then
22892 			 * non-loopbacks. This is acheived by inserting the
22893 			 * loopback always before non-loopback.
22894 			 * This is used to send a single copy of a broadcast
22895 			 * packet out all physical interfaces that have an
22896 			 * matching IRE_BROADCAST while also looping
22897 			 * back one copy (to ip_wput_local) for each
22898 			 * matching physical interface. However, we avoid
22899 			 * sending packets out different logical that match by
22900 			 * having ipif_up/ipif_down supress duplicate
22901 			 * IRE_BROADCASTS.
22902 			 *
22903 			 * This feature is currently used to get broadcasts
22904 			 * sent to multiple interfaces, when the broadcast
22905 			 * address being used applies to multiple interfaces.
22906 			 * For example, a whole net broadcast will be
22907 			 * replicated on every connected subnet of
22908 			 * the target net.
22909 			 *
22910 			 * Each zone has its own set of IRE_BROADCASTs, so that
22911 			 * we're able to distribute inbound packets to multiple
22912 			 * zones who share a broadcast address. We avoid looping
22913 			 * back outbound packets in different zones but on the
22914 			 * same ill, as the application would see duplicates.
22915 			 *
22916 			 * This logic assumes that ire_add_v4() groups the
22917 			 * IRE_BROADCAST entries so that those with the same
22918 			 * ire_addr are kept together.
22919 			 */
22920 			ire_ill = ire->ire_ipif->ipif_ill;
22921 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22922 				while (ire1 != NULL && ire1->ire_addr == dst) {
22923 					ire1_ill = ire1->ire_ipif->ipif_ill;
22924 					if (ire1_ill != ire_ill)
22925 						break;
22926 					ire1 = ire1->ire_next;
22927 				}
22928 			}
22929 		}
22930 		ASSERT(multirt_send == B_FALSE);
22931 		if (ire1 != NULL && ire1->ire_addr == dst) {
22932 			if ((ire->ire_flags & RTF_MULTIRT) &&
22933 			    (ire1->ire_flags & RTF_MULTIRT)) {
22934 				/*
22935 				 * We are in the multirouting case.
22936 				 * The message must be sent at least
22937 				 * on both ires. These ires have been
22938 				 * inserted AFTER the standard ones
22939 				 * in ip_rt_add(). There are thus no
22940 				 * other ire entries for the destination
22941 				 * address in the rest of the bucket
22942 				 * that do not have the RTF_MULTIRT
22943 				 * flag. We don't process a copy
22944 				 * of the message here. This will be
22945 				 * done in the final sending loop.
22946 				 */
22947 				multirt_send = B_TRUE;
22948 			} else {
22949 				next_mp = ip_copymsg(first_mp);
22950 				if (next_mp != NULL)
22951 					IRE_REFHOLD(ire1);
22952 			}
22953 		}
22954 		rw_exit(&ire->ire_bucket->irb_lock);
22955 	}
22956 
22957 	if (stq) {
22958 		/*
22959 		 * A non-NULL send-to queue means this packet is going
22960 		 * out of this machine.
22961 		 */
22962 		out_ill = (ill_t *)stq->q_ptr;
22963 
22964 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22965 		ttl_protocol = ((uint16_t *)ipha)[4];
22966 		/*
22967 		 * We accumulate the pseudo header checksum in cksum.
22968 		 * This is pretty hairy code, so watch close.  One
22969 		 * thing to keep in mind is that UDP and TCP have
22970 		 * stored their respective datagram lengths in their
22971 		 * checksum fields.  This lines things up real nice.
22972 		 */
22973 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22974 		    (src >> 16) + (src & 0xFFFF);
22975 		/*
22976 		 * We assume the udp checksum field contains the
22977 		 * length, so to compute the pseudo header checksum,
22978 		 * all we need is the protocol number and src/dst.
22979 		 */
22980 		/* Provide the checksums for UDP and TCP. */
22981 		if ((PROTO == IPPROTO_TCP) &&
22982 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22983 			/* hlen gets the number of uchar_ts in the IP header */
22984 			hlen = (V_HLEN & 0xF) << 2;
22985 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22986 			IP_STAT(ipst, ip_out_sw_cksum);
22987 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22988 			    LENGTH - hlen);
22989 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22990 		} else if (PROTO == IPPROTO_SCTP &&
22991 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22992 			sctp_hdr_t	*sctph;
22993 
22994 			hlen = (V_HLEN & 0xF) << 2;
22995 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22996 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22997 			sctph->sh_chksum = 0;
22998 #ifdef	DEBUG
22999 			if (!skip_sctp_cksum)
23000 #endif
23001 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23002 		} else {
23003 			queue_t	*dev_q = stq->q_next;
23004 
23005 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
23006 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
23007 blocked:
23008 				ipha->ipha_ident = ip_hdr_included;
23009 				/*
23010 				 * If we don't have a conn to apply
23011 				 * backpressure, free the message.
23012 				 * In the ire_send path, we don't know
23013 				 * the position to requeue the packet. Rather
23014 				 * than reorder packets, we just drop this
23015 				 * packet.
23016 				 */
23017 				if (ipst->ips_ip_output_queue &&
23018 				    connp != NULL &&
23019 				    caller != IRE_SEND) {
23020 					if (caller == IP_WSRV) {
23021 						idl_tx_list_t *idl_txl;
23022 
23023 						idl_txl =
23024 						    &ipst->ips_idl_tx_list[0];
23025 						connp->conn_did_putbq = 1;
23026 						(void) putbq(connp->conn_wq,
23027 						    first_mp);
23028 						conn_drain_insert(connp,
23029 						    idl_txl);
23030 						/*
23031 						 * This is the service thread,
23032 						 * and the queue is already
23033 						 * noenabled. The check for
23034 						 * canput and the putbq is not
23035 						 * atomic. So we need to check
23036 						 * again.
23037 						 */
23038 						if (canput(stq->q_next))
23039 							connp->conn_did_putbq
23040 							    = 0;
23041 						IP_STAT(ipst, ip_conn_flputbq);
23042 					} else {
23043 						/*
23044 						 * We are not the service proc.
23045 						 * ip_wsrv will be scheduled or
23046 						 * is already running.
23047 						 */
23048 
23049 						(void) putq(connp->conn_wq,
23050 						    first_mp);
23051 					}
23052 				} else {
23053 					out_ill = (ill_t *)stq->q_ptr;
23054 					BUMP_MIB(out_ill->ill_ip_mib,
23055 					    ipIfStatsOutDiscards);
23056 					freemsg(first_mp);
23057 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23058 					    "ip_wput_ire_end: q %p (%S)",
23059 					    q, "discard");
23060 				}
23061 				ire_refrele(ire);
23062 				if (next_mp) {
23063 					ire_refrele(ire1);
23064 					freemsg(next_mp);
23065 				}
23066 				if (conn_outgoing_ill != NULL)
23067 					ill_refrele(conn_outgoing_ill);
23068 				return;
23069 			}
23070 			if ((PROTO == IPPROTO_UDP) &&
23071 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23072 				/*
23073 				 * hlen gets the number of uchar_ts in the
23074 				 * IP header
23075 				 */
23076 				hlen = (V_HLEN & 0xF) << 2;
23077 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23078 				max_frag = ire->ire_max_frag;
23079 				if (*up != 0) {
23080 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23081 					    up, PROTO, hlen, LENGTH, max_frag,
23082 					    ipsec_len, cksum);
23083 					/* Software checksum? */
23084 					if (DB_CKSUMFLAGS(mp) == 0) {
23085 						IP_STAT(ipst, ip_out_sw_cksum);
23086 						IP_STAT_UPDATE(ipst,
23087 						    ip_udp_out_sw_cksum_bytes,
23088 						    LENGTH - hlen);
23089 					}
23090 				}
23091 			}
23092 		}
23093 		/*
23094 		 * Need to do this even when fragmenting. The local
23095 		 * loopback can be done without computing checksums
23096 		 * but forwarding out other interface must be done
23097 		 * after the IP checksum (and ULP checksums) have been
23098 		 * computed.
23099 		 *
23100 		 * NOTE : multicast_forward is set only if this packet
23101 		 * originated from ip_wput. For packets originating from
23102 		 * ip_wput_multicast, it is not set.
23103 		 */
23104 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23105 multi_loopback:
23106 			ip2dbg(("ip_wput: multicast, loop %d\n",
23107 			    conn_multicast_loop));
23108 
23109 			/*  Forget header checksum offload */
23110 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23111 
23112 			/*
23113 			 * Local loopback of multicasts?  Check the
23114 			 * ill.
23115 			 *
23116 			 * Note that the loopback function will not come
23117 			 * in through ip_rput - it will only do the
23118 			 * client fanout thus we need to do an mforward
23119 			 * as well.  The is different from the BSD
23120 			 * logic.
23121 			 */
23122 			if (ill != NULL) {
23123 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23124 				    ALL_ZONES) != NULL) {
23125 					/*
23126 					 * Pass along the virtual output q.
23127 					 * ip_wput_local() will distribute the
23128 					 * packet to all the matching zones,
23129 					 * except the sending zone when
23130 					 * IP_MULTICAST_LOOP is false.
23131 					 */
23132 					ip_multicast_loopback(q, ill, first_mp,
23133 					    conn_multicast_loop ? 0 :
23134 					    IP_FF_NO_MCAST_LOOP, zoneid);
23135 				}
23136 			}
23137 			if (ipha->ipha_ttl == 0) {
23138 				/*
23139 				 * 0 => only to this host i.e. we are
23140 				 * done. We are also done if this was the
23141 				 * loopback interface since it is sufficient
23142 				 * to loopback one copy of a multicast packet.
23143 				 */
23144 				freemsg(first_mp);
23145 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23146 				    "ip_wput_ire_end: q %p (%S)",
23147 				    q, "loopback");
23148 				ire_refrele(ire);
23149 				if (conn_outgoing_ill != NULL)
23150 					ill_refrele(conn_outgoing_ill);
23151 				return;
23152 			}
23153 			/*
23154 			 * ILLF_MULTICAST is checked in ip_newroute
23155 			 * i.e. we don't need to check it here since
23156 			 * all IRE_CACHEs come from ip_newroute.
23157 			 * For multicast traffic, SO_DONTROUTE is interpreted
23158 			 * to mean only send the packet out the interface
23159 			 * (optionally specified with IP_MULTICAST_IF)
23160 			 * and do not forward it out additional interfaces.
23161 			 * RSVP and the rsvp daemon is an example of a
23162 			 * protocol and user level process that
23163 			 * handles it's own routing. Hence, it uses the
23164 			 * SO_DONTROUTE option to accomplish this.
23165 			 */
23166 
23167 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23168 			    ill != NULL) {
23169 				/* Unconditionally redo the checksum */
23170 				ipha->ipha_hdr_checksum = 0;
23171 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23172 
23173 				/*
23174 				 * If this needs to go out secure, we need
23175 				 * to wait till we finish the IPsec
23176 				 * processing.
23177 				 */
23178 				if (ipsec_len == 0 &&
23179 				    ip_mforward(ill, ipha, mp)) {
23180 					freemsg(first_mp);
23181 					ip1dbg(("ip_wput: mforward failed\n"));
23182 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23183 					    "ip_wput_ire_end: q %p (%S)",
23184 					    q, "mforward failed");
23185 					ire_refrele(ire);
23186 					if (conn_outgoing_ill != NULL)
23187 						ill_refrele(conn_outgoing_ill);
23188 					return;
23189 				}
23190 			}
23191 		}
23192 		max_frag = ire->ire_max_frag;
23193 		cksum += ttl_protocol;
23194 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23195 			/* No fragmentation required for this one. */
23196 			/*
23197 			 * Don't use frag_flag if packet is pre-built or source
23198 			 * routed or if multicast (since multicast packets do
23199 			 * not solicit ICMP "packet too big" messages).
23200 			 */
23201 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23202 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23203 			    !ip_source_route_included(ipha)) &&
23204 			    !CLASSD(ipha->ipha_dst))
23205 				ipha->ipha_fragment_offset_and_flags |=
23206 				    htons(ire->ire_frag_flag);
23207 
23208 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23209 				/* Complete the IP header checksum. */
23210 				cksum += ipha->ipha_ident;
23211 				cksum += (v_hlen_tos_len >> 16)+
23212 				    (v_hlen_tos_len & 0xFFFF);
23213 				cksum += ipha->ipha_fragment_offset_and_flags;
23214 				hlen = (V_HLEN & 0xF) -
23215 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23216 				if (hlen) {
23217 checksumoptions:
23218 					/*
23219 					 * Account for the IP Options in the IP
23220 					 * header checksum.
23221 					 */
23222 					up = (uint16_t *)(rptr+
23223 					    IP_SIMPLE_HDR_LENGTH);
23224 					do {
23225 						cksum += up[0];
23226 						cksum += up[1];
23227 						up += 2;
23228 					} while (--hlen);
23229 				}
23230 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23231 				cksum = ~(cksum + (cksum >> 16));
23232 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23233 			}
23234 			if (ipsec_len != 0) {
23235 				ipsec_out_process(q, first_mp, ire, ill_index);
23236 				if (!next_mp) {
23237 					ire_refrele(ire);
23238 					if (conn_outgoing_ill != NULL)
23239 						ill_refrele(conn_outgoing_ill);
23240 					return;
23241 				}
23242 				goto next;
23243 			}
23244 
23245 			/*
23246 			 * multirt_send has already been handled
23247 			 * for broadcast, but not yet for multicast
23248 			 * or IP options.
23249 			 */
23250 			if (next_mp == NULL) {
23251 				if (ire->ire_flags & RTF_MULTIRT) {
23252 					multirt_send = B_TRUE;
23253 				}
23254 			}
23255 
23256 			/*
23257 			 * In most cases, the emission loop below is
23258 			 * entered only once. Only in the case where
23259 			 * the ire holds the RTF_MULTIRT flag, do we loop
23260 			 * to process all RTF_MULTIRT ires in the bucket,
23261 			 * and send the packet through all crossed
23262 			 * RTF_MULTIRT routes.
23263 			 */
23264 			do {
23265 				if (multirt_send) {
23266 					irb_t *irb;
23267 
23268 					irb = ire->ire_bucket;
23269 					ASSERT(irb != NULL);
23270 					/*
23271 					 * We are in a multiple send case,
23272 					 * need to get the next IRE and make
23273 					 * a duplicate of the packet.
23274 					 */
23275 					IRB_REFHOLD(irb);
23276 					for (ire1 = ire->ire_next;
23277 					    ire1 != NULL;
23278 					    ire1 = ire1->ire_next) {
23279 						if (!(ire1->ire_flags &
23280 						    RTF_MULTIRT))
23281 							continue;
23282 
23283 						if (ire1->ire_addr !=
23284 						    ire->ire_addr)
23285 							continue;
23286 
23287 						if (ire1->ire_marks &
23288 						    (IRE_MARK_CONDEMNED |
23289 						    IRE_MARK_TESTHIDDEN))
23290 							continue;
23291 
23292 						/* Got one */
23293 						IRE_REFHOLD(ire1);
23294 						break;
23295 					}
23296 					IRB_REFRELE(irb);
23297 
23298 					if (ire1 != NULL) {
23299 						next_mp = copyb(mp);
23300 						if ((next_mp == NULL) ||
23301 						    ((mp->b_cont != NULL) &&
23302 						    ((next_mp->b_cont =
23303 						    dupmsg(mp->b_cont))
23304 						    == NULL))) {
23305 							freemsg(next_mp);
23306 							next_mp = NULL;
23307 							ire_refrele(ire1);
23308 							ire1 = NULL;
23309 						}
23310 					}
23311 
23312 					/*
23313 					 * Last multiroute ire; don't loop
23314 					 * anymore. The emission is over
23315 					 * and next_mp is NULL.
23316 					 */
23317 					if (ire1 == NULL) {
23318 						multirt_send = B_FALSE;
23319 					}
23320 				}
23321 
23322 				out_ill = ire_to_ill(ire);
23323 				DTRACE_PROBE4(ip4__physical__out__start,
23324 				    ill_t *, NULL,
23325 				    ill_t *, out_ill,
23326 				    ipha_t *, ipha, mblk_t *, mp);
23327 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23328 				    ipst->ips_ipv4firewall_physical_out,
23329 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23330 				DTRACE_PROBE1(ip4__physical__out__end,
23331 				    mblk_t *, mp);
23332 				if (mp == NULL)
23333 					goto release_ire_and_ill_2;
23334 
23335 				ASSERT(ipsec_len == 0);
23336 				mp->b_prev =
23337 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23338 				DTRACE_PROBE2(ip__xmit__2,
23339 				    mblk_t *, mp, ire_t *, ire);
23340 				pktxmit_state = ip_xmit_v4(mp, ire,
23341 				    NULL, B_TRUE, connp);
23342 				if ((pktxmit_state == SEND_FAILED) ||
23343 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23344 release_ire_and_ill_2:
23345 					if (next_mp) {
23346 						freemsg(next_mp);
23347 						ire_refrele(ire1);
23348 					}
23349 					ire_refrele(ire);
23350 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23351 					    "ip_wput_ire_end: q %p (%S)",
23352 					    q, "discard MDATA");
23353 					if (conn_outgoing_ill != NULL)
23354 						ill_refrele(conn_outgoing_ill);
23355 					return;
23356 				}
23357 
23358 				if (CLASSD(dst)) {
23359 					BUMP_MIB(out_ill->ill_ip_mib,
23360 					    ipIfStatsHCOutMcastPkts);
23361 					UPDATE_MIB(out_ill->ill_ip_mib,
23362 					    ipIfStatsHCOutMcastOctets,
23363 					    LENGTH);
23364 				} else if (ire->ire_type == IRE_BROADCAST) {
23365 					BUMP_MIB(out_ill->ill_ip_mib,
23366 					    ipIfStatsHCOutBcastPkts);
23367 				}
23368 
23369 				if (multirt_send) {
23370 					/*
23371 					 * We are in a multiple send case,
23372 					 * need to re-enter the sending loop
23373 					 * using the next ire.
23374 					 */
23375 					ire_refrele(ire);
23376 					ire = ire1;
23377 					stq = ire->ire_stq;
23378 					mp = next_mp;
23379 					next_mp = NULL;
23380 					ipha = (ipha_t *)mp->b_rptr;
23381 					ill_index = Q_TO_INDEX(stq);
23382 				}
23383 			} while (multirt_send);
23384 
23385 			if (!next_mp) {
23386 				/*
23387 				 * Last copy going out (the ultra-common
23388 				 * case).  Note that we intentionally replicate
23389 				 * the putnext rather than calling it before
23390 				 * the next_mp check in hopes of a little
23391 				 * tail-call action out of the compiler.
23392 				 */
23393 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23394 				    "ip_wput_ire_end: q %p (%S)",
23395 				    q, "last copy out(1)");
23396 				ire_refrele(ire);
23397 				if (conn_outgoing_ill != NULL)
23398 					ill_refrele(conn_outgoing_ill);
23399 				return;
23400 			}
23401 			/* More copies going out below. */
23402 		} else {
23403 			int offset;
23404 fragmentit:
23405 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23406 			/*
23407 			 * If this would generate a icmp_frag_needed message,
23408 			 * we need to handle it before we do the IPsec
23409 			 * processing. Otherwise, we need to strip the IPsec
23410 			 * headers before we send up the message to the ULPs
23411 			 * which becomes messy and difficult.
23412 			 */
23413 			if (ipsec_len != 0) {
23414 				if ((max_frag < (unsigned int)(LENGTH +
23415 				    ipsec_len)) && (offset & IPH_DF)) {
23416 					out_ill = (ill_t *)stq->q_ptr;
23417 					BUMP_MIB(out_ill->ill_ip_mib,
23418 					    ipIfStatsOutFragFails);
23419 					BUMP_MIB(out_ill->ill_ip_mib,
23420 					    ipIfStatsOutFragReqds);
23421 					ipha->ipha_hdr_checksum = 0;
23422 					ipha->ipha_hdr_checksum =
23423 					    (uint16_t)ip_csum_hdr(ipha);
23424 					icmp_frag_needed(ire->ire_stq, first_mp,
23425 					    max_frag, zoneid, ipst);
23426 					if (!next_mp) {
23427 						ire_refrele(ire);
23428 						if (conn_outgoing_ill != NULL) {
23429 							ill_refrele(
23430 							    conn_outgoing_ill);
23431 						}
23432 						return;
23433 					}
23434 				} else {
23435 					/*
23436 					 * This won't cause a icmp_frag_needed
23437 					 * message. to be generated. Send it on
23438 					 * the wire. Note that this could still
23439 					 * cause fragmentation and all we
23440 					 * do is the generation of the message
23441 					 * to the ULP if needed before IPsec.
23442 					 */
23443 					if (!next_mp) {
23444 						ipsec_out_process(q, first_mp,
23445 						    ire, ill_index);
23446 						TRACE_2(TR_FAC_IP,
23447 						    TR_IP_WPUT_IRE_END,
23448 						    "ip_wput_ire_end: q %p "
23449 						    "(%S)", q,
23450 						    "last ipsec_out_process");
23451 						ire_refrele(ire);
23452 						if (conn_outgoing_ill != NULL) {
23453 							ill_refrele(
23454 							    conn_outgoing_ill);
23455 						}
23456 						return;
23457 					}
23458 					ipsec_out_process(q, first_mp,
23459 					    ire, ill_index);
23460 				}
23461 			} else {
23462 				/*
23463 				 * Initiate IPPF processing. For
23464 				 * fragmentable packets we finish
23465 				 * all QOS packet processing before
23466 				 * calling:
23467 				 * ip_wput_ire_fragmentit->ip_wput_frag
23468 				 */
23469 
23470 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23471 					ip_process(IPP_LOCAL_OUT, &mp,
23472 					    ill_index);
23473 					if (mp == NULL) {
23474 						out_ill = (ill_t *)stq->q_ptr;
23475 						BUMP_MIB(out_ill->ill_ip_mib,
23476 						    ipIfStatsOutDiscards);
23477 						if (next_mp != NULL) {
23478 							freemsg(next_mp);
23479 							ire_refrele(ire1);
23480 						}
23481 						ire_refrele(ire);
23482 						TRACE_2(TR_FAC_IP,
23483 						    TR_IP_WPUT_IRE_END,
23484 						    "ip_wput_ire: q %p (%S)",
23485 						    q, "discard MDATA");
23486 						if (conn_outgoing_ill != NULL) {
23487 							ill_refrele(
23488 							    conn_outgoing_ill);
23489 						}
23490 						return;
23491 					}
23492 				}
23493 				if (!next_mp) {
23494 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23495 					    "ip_wput_ire_end: q %p (%S)",
23496 					    q, "last fragmentation");
23497 					ip_wput_ire_fragmentit(mp, ire,
23498 					    zoneid, ipst, connp);
23499 					ire_refrele(ire);
23500 					if (conn_outgoing_ill != NULL)
23501 						ill_refrele(conn_outgoing_ill);
23502 					return;
23503 				}
23504 				ip_wput_ire_fragmentit(mp, ire,
23505 				    zoneid, ipst, connp);
23506 			}
23507 		}
23508 	} else {
23509 nullstq:
23510 		/* A NULL stq means the destination address is local. */
23511 		UPDATE_OB_PKT_COUNT(ire);
23512 		ire->ire_last_used_time = lbolt;
23513 		ASSERT(ire->ire_ipif != NULL);
23514 		if (!next_mp) {
23515 			/*
23516 			 * Is there an "in" and "out" for traffic local
23517 			 * to a host (loopback)?  The code in Solaris doesn't
23518 			 * explicitly draw a line in its code for in vs out,
23519 			 * so we've had to draw a line in the sand: ip_wput_ire
23520 			 * is considered to be the "output" side and
23521 			 * ip_wput_local to be the "input" side.
23522 			 */
23523 			out_ill = ire_to_ill(ire);
23524 
23525 			/*
23526 			 * DTrace this as ip:::send.  A blocked packet will
23527 			 * fire the send probe, but not the receive probe.
23528 			 */
23529 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23530 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23531 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23532 
23533 			DTRACE_PROBE4(ip4__loopback__out__start,
23534 			    ill_t *, NULL, ill_t *, out_ill,
23535 			    ipha_t *, ipha, mblk_t *, first_mp);
23536 
23537 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23538 			    ipst->ips_ipv4firewall_loopback_out,
23539 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23540 
23541 			DTRACE_PROBE1(ip4__loopback__out_end,
23542 			    mblk_t *, first_mp);
23543 
23544 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23545 			    "ip_wput_ire_end: q %p (%S)",
23546 			    q, "local address");
23547 
23548 			if (first_mp != NULL)
23549 				ip_wput_local(q, out_ill, ipha,
23550 				    first_mp, ire, 0, ire->ire_zoneid);
23551 			ire_refrele(ire);
23552 			if (conn_outgoing_ill != NULL)
23553 				ill_refrele(conn_outgoing_ill);
23554 			return;
23555 		}
23556 
23557 		out_ill = ire_to_ill(ire);
23558 
23559 		/*
23560 		 * DTrace this as ip:::send.  A blocked packet will fire the
23561 		 * send probe, but not the receive probe.
23562 		 */
23563 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23564 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23565 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23566 
23567 		DTRACE_PROBE4(ip4__loopback__out__start,
23568 		    ill_t *, NULL, ill_t *, out_ill,
23569 		    ipha_t *, ipha, mblk_t *, first_mp);
23570 
23571 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23572 		    ipst->ips_ipv4firewall_loopback_out,
23573 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23574 
23575 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23576 
23577 		if (first_mp != NULL)
23578 			ip_wput_local(q, out_ill, ipha,
23579 			    first_mp, ire, 0, ire->ire_zoneid);
23580 	}
23581 next:
23582 	/*
23583 	 * More copies going out to additional interfaces.
23584 	 * ire1 has already been held. We don't need the
23585 	 * "ire" anymore.
23586 	 */
23587 	ire_refrele(ire);
23588 	ire = ire1;
23589 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23590 	mp = next_mp;
23591 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23592 	ill = ire_to_ill(ire);
23593 	first_mp = mp;
23594 	if (ipsec_len != 0) {
23595 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23596 		mp = mp->b_cont;
23597 	}
23598 	dst = ire->ire_addr;
23599 	ipha = (ipha_t *)mp->b_rptr;
23600 	/*
23601 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23602 	 * Restore ipha_ident "no checksum" flag.
23603 	 */
23604 	src = orig_src;
23605 	ipha->ipha_ident = ip_hdr_included;
23606 	goto another;
23607 
23608 #undef	rptr
23609 #undef	Q_TO_INDEX
23610 }
23611 
23612 /*
23613  * Routine to allocate a message that is used to notify the ULP about MDT.
23614  * The caller may provide a pointer to the link-layer MDT capabilities,
23615  * or NULL if MDT is to be disabled on the stream.
23616  */
23617 mblk_t *
23618 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23619 {
23620 	mblk_t *mp;
23621 	ip_mdt_info_t *mdti;
23622 	ill_mdt_capab_t *idst;
23623 
23624 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23625 		DB_TYPE(mp) = M_CTL;
23626 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23627 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23628 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23629 		idst = &(mdti->mdt_capab);
23630 
23631 		/*
23632 		 * If the caller provides us with the capability, copy
23633 		 * it over into our notification message; otherwise
23634 		 * we zero out the capability portion.
23635 		 */
23636 		if (isrc != NULL)
23637 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23638 		else
23639 			bzero((caddr_t)idst, sizeof (*idst));
23640 	}
23641 	return (mp);
23642 }
23643 
23644 /*
23645  * Routine which determines whether MDT can be enabled on the destination
23646  * IRE and IPC combination, and if so, allocates and returns the MDT
23647  * notification mblk that may be used by ULP.  We also check if we need to
23648  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23649  * MDT usage in the past have been lifted.  This gets called during IP
23650  * and ULP binding.
23651  */
23652 mblk_t *
23653 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23654     ill_mdt_capab_t *mdt_cap)
23655 {
23656 	mblk_t *mp;
23657 	boolean_t rc = B_FALSE;
23658 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23659 
23660 	ASSERT(dst_ire != NULL);
23661 	ASSERT(connp != NULL);
23662 	ASSERT(mdt_cap != NULL);
23663 
23664 	/*
23665 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23666 	 * Multidata, which is handled in tcp_multisend().  This
23667 	 * is the reason why we do all these checks here, to ensure
23668 	 * that we don't enable Multidata for the cases which we
23669 	 * can't handle at the moment.
23670 	 */
23671 	do {
23672 		/* Only do TCP at the moment */
23673 		if (connp->conn_ulp != IPPROTO_TCP)
23674 			break;
23675 
23676 		/*
23677 		 * IPsec outbound policy present?  Note that we get here
23678 		 * after calling ipsec_conn_cache_policy() where the global
23679 		 * policy checking is performed.  conn_latch will be
23680 		 * non-NULL as long as there's a policy defined,
23681 		 * i.e. conn_out_enforce_policy may be NULL in such case
23682 		 * when the connection is non-secure, and hence we check
23683 		 * further if the latch refers to an outbound policy.
23684 		 */
23685 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23686 			break;
23687 
23688 		/* CGTP (multiroute) is enabled? */
23689 		if (dst_ire->ire_flags & RTF_MULTIRT)
23690 			break;
23691 
23692 		/* Outbound IPQoS enabled? */
23693 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23694 			/*
23695 			 * In this case, we disable MDT for this and all
23696 			 * future connections going over the interface.
23697 			 */
23698 			mdt_cap->ill_mdt_on = 0;
23699 			break;
23700 		}
23701 
23702 		/* socket option(s) present? */
23703 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23704 			break;
23705 
23706 		rc = B_TRUE;
23707 	/* CONSTCOND */
23708 	} while (0);
23709 
23710 	/* Remember the result */
23711 	connp->conn_mdt_ok = rc;
23712 
23713 	if (!rc)
23714 		return (NULL);
23715 	else if (!mdt_cap->ill_mdt_on) {
23716 		/*
23717 		 * If MDT has been previously turned off in the past, and we
23718 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23719 		 * then enable it for this interface.
23720 		 */
23721 		mdt_cap->ill_mdt_on = 1;
23722 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23723 		    "interface %s\n", ill_name));
23724 	}
23725 
23726 	/* Allocate the MDT info mblk */
23727 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23728 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23729 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23730 		return (NULL);
23731 	}
23732 	return (mp);
23733 }
23734 
23735 /*
23736  * Routine to allocate a message that is used to notify the ULP about LSO.
23737  * The caller may provide a pointer to the link-layer LSO capabilities,
23738  * or NULL if LSO is to be disabled on the stream.
23739  */
23740 mblk_t *
23741 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23742 {
23743 	mblk_t *mp;
23744 	ip_lso_info_t *lsoi;
23745 	ill_lso_capab_t *idst;
23746 
23747 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23748 		DB_TYPE(mp) = M_CTL;
23749 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23750 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23751 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23752 		idst = &(lsoi->lso_capab);
23753 
23754 		/*
23755 		 * If the caller provides us with the capability, copy
23756 		 * it over into our notification message; otherwise
23757 		 * we zero out the capability portion.
23758 		 */
23759 		if (isrc != NULL)
23760 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23761 		else
23762 			bzero((caddr_t)idst, sizeof (*idst));
23763 	}
23764 	return (mp);
23765 }
23766 
23767 /*
23768  * Routine which determines whether LSO can be enabled on the destination
23769  * IRE and IPC combination, and if so, allocates and returns the LSO
23770  * notification mblk that may be used by ULP.  We also check if we need to
23771  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23772  * LSO usage in the past have been lifted.  This gets called during IP
23773  * and ULP binding.
23774  */
23775 mblk_t *
23776 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23777     ill_lso_capab_t *lso_cap)
23778 {
23779 	mblk_t *mp;
23780 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23781 
23782 	ASSERT(dst_ire != NULL);
23783 	ASSERT(connp != NULL);
23784 	ASSERT(lso_cap != NULL);
23785 
23786 	connp->conn_lso_ok = B_TRUE;
23787 
23788 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23789 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23790 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23791 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23792 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23793 		connp->conn_lso_ok = B_FALSE;
23794 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23795 			/*
23796 			 * Disable LSO for this and all future connections going
23797 			 * over the interface.
23798 			 */
23799 			lso_cap->ill_lso_on = 0;
23800 		}
23801 	}
23802 
23803 	if (!connp->conn_lso_ok)
23804 		return (NULL);
23805 	else if (!lso_cap->ill_lso_on) {
23806 		/*
23807 		 * If LSO has been previously turned off in the past, and we
23808 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23809 		 * then enable it for this interface.
23810 		 */
23811 		lso_cap->ill_lso_on = 1;
23812 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23813 		    ill_name));
23814 	}
23815 
23816 	/* Allocate the LSO info mblk */
23817 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23818 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23819 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23820 
23821 	return (mp);
23822 }
23823 
23824 /*
23825  * Create destination address attribute, and fill it with the physical
23826  * destination address and SAP taken from the template DL_UNITDATA_REQ
23827  * message block.
23828  */
23829 boolean_t
23830 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23831 {
23832 	dl_unitdata_req_t *dlurp;
23833 	pattr_t *pa;
23834 	pattrinfo_t pa_info;
23835 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23836 	uint_t das_len, das_off;
23837 
23838 	ASSERT(dlmp != NULL);
23839 
23840 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23841 	das_len = dlurp->dl_dest_addr_length;
23842 	das_off = dlurp->dl_dest_addr_offset;
23843 
23844 	pa_info.type = PATTR_DSTADDRSAP;
23845 	pa_info.len = sizeof (**das) + das_len - 1;
23846 
23847 	/* create and associate the attribute */
23848 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23849 	if (pa != NULL) {
23850 		ASSERT(*das != NULL);
23851 		(*das)->addr_is_group = 0;
23852 		(*das)->addr_len = (uint8_t)das_len;
23853 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23854 	}
23855 
23856 	return (pa != NULL);
23857 }
23858 
23859 /*
23860  * Create hardware checksum attribute and fill it with the values passed.
23861  */
23862 boolean_t
23863 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23864     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23865 {
23866 	pattr_t *pa;
23867 	pattrinfo_t pa_info;
23868 
23869 	ASSERT(mmd != NULL);
23870 
23871 	pa_info.type = PATTR_HCKSUM;
23872 	pa_info.len = sizeof (pattr_hcksum_t);
23873 
23874 	/* create and associate the attribute */
23875 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23876 	if (pa != NULL) {
23877 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23878 
23879 		hck->hcksum_start_offset = start_offset;
23880 		hck->hcksum_stuff_offset = stuff_offset;
23881 		hck->hcksum_end_offset = end_offset;
23882 		hck->hcksum_flags = flags;
23883 	}
23884 	return (pa != NULL);
23885 }
23886 
23887 /*
23888  * Create zerocopy attribute and fill it with the specified flags
23889  */
23890 boolean_t
23891 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23892 {
23893 	pattr_t *pa;
23894 	pattrinfo_t pa_info;
23895 
23896 	ASSERT(mmd != NULL);
23897 	pa_info.type = PATTR_ZCOPY;
23898 	pa_info.len = sizeof (pattr_zcopy_t);
23899 
23900 	/* create and associate the attribute */
23901 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23902 	if (pa != NULL) {
23903 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23904 
23905 		zcopy->zcopy_flags = flags;
23906 	}
23907 	return (pa != NULL);
23908 }
23909 
23910 /*
23911  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23912  * block chain. We could rewrite to handle arbitrary message block chains but
23913  * that would make the code complicated and slow. Right now there three
23914  * restrictions:
23915  *
23916  *   1. The first message block must contain the complete IP header and
23917  *	at least 1 byte of payload data.
23918  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23919  *	so that we can use a single Multidata message.
23920  *   3. No frag must be distributed over two or more message blocks so
23921  *	that we don't need more than two packet descriptors per frag.
23922  *
23923  * The above restrictions allow us to support userland applications (which
23924  * will send down a single message block) and NFS over UDP (which will
23925  * send down a chain of at most three message blocks).
23926  *
23927  * We also don't use MDT for payloads with less than or equal to
23928  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23929  */
23930 boolean_t
23931 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23932 {
23933 	int	blocks;
23934 	ssize_t	total, missing, size;
23935 
23936 	ASSERT(mp != NULL);
23937 	ASSERT(hdr_len > 0);
23938 
23939 	size = MBLKL(mp) - hdr_len;
23940 	if (size <= 0)
23941 		return (B_FALSE);
23942 
23943 	/* The first mblk contains the header and some payload. */
23944 	blocks = 1;
23945 	total = size;
23946 	size %= len;
23947 	missing = (size == 0) ? 0 : (len - size);
23948 	mp = mp->b_cont;
23949 
23950 	while (mp != NULL) {
23951 		/*
23952 		 * Give up if we encounter a zero length message block.
23953 		 * In practice, this should rarely happen and therefore
23954 		 * not worth the trouble of freeing and re-linking the
23955 		 * mblk from the chain to handle such case.
23956 		 */
23957 		if ((size = MBLKL(mp)) == 0)
23958 			return (B_FALSE);
23959 
23960 		/* Too many payload buffers for a single Multidata message? */
23961 		if (++blocks > MULTIDATA_MAX_PBUFS)
23962 			return (B_FALSE);
23963 
23964 		total += size;
23965 		/* Is a frag distributed over two or more message blocks? */
23966 		if (missing > size)
23967 			return (B_FALSE);
23968 		size -= missing;
23969 
23970 		size %= len;
23971 		missing = (size == 0) ? 0 : (len - size);
23972 
23973 		mp = mp->b_cont;
23974 	}
23975 
23976 	return (total > ip_wput_frag_mdt_min);
23977 }
23978 
23979 /*
23980  * Outbound IPv4 fragmentation routine using MDT.
23981  */
23982 static void
23983 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23984     uint32_t frag_flag, int offset)
23985 {
23986 	ipha_t		*ipha_orig;
23987 	int		i1, ip_data_end;
23988 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23989 	mblk_t		*hdr_mp, *md_mp = NULL;
23990 	unsigned char	*hdr_ptr, *pld_ptr;
23991 	multidata_t	*mmd;
23992 	ip_pdescinfo_t	pdi;
23993 	ill_t		*ill;
23994 	ip_stack_t	*ipst = ire->ire_ipst;
23995 
23996 	ASSERT(DB_TYPE(mp) == M_DATA);
23997 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23998 
23999 	ill = ire_to_ill(ire);
24000 	ASSERT(ill != NULL);
24001 
24002 	ipha_orig = (ipha_t *)mp->b_rptr;
24003 	mp->b_rptr += sizeof (ipha_t);
24004 
24005 	/* Calculate how many packets we will send out */
24006 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24007 	pkts = (i1 + len - 1) / len;
24008 	ASSERT(pkts > 1);
24009 
24010 	/* Allocate a message block which will hold all the IP Headers. */
24011 	wroff = ipst->ips_ip_wroff_extra;
24012 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24013 
24014 	i1 = pkts * hdr_chunk_len;
24015 	/*
24016 	 * Create the header buffer, Multidata and destination address
24017 	 * and SAP attribute that should be associated with it.
24018 	 */
24019 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24020 	    ((hdr_mp->b_wptr += i1),
24021 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24022 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24023 		freemsg(mp);
24024 		if (md_mp == NULL) {
24025 			freemsg(hdr_mp);
24026 		} else {
24027 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24028 			freemsg(md_mp);
24029 		}
24030 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24031 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24032 		return;
24033 	}
24034 	IP_STAT(ipst, ip_frag_mdt_allocd);
24035 
24036 	/*
24037 	 * Add a payload buffer to the Multidata; this operation must not
24038 	 * fail, or otherwise our logic in this routine is broken.  There
24039 	 * is no memory allocation done by the routine, so any returned
24040 	 * failure simply tells us that we've done something wrong.
24041 	 *
24042 	 * A failure tells us that either we're adding the same payload
24043 	 * buffer more than once, or we're trying to add more buffers than
24044 	 * allowed.  None of the above cases should happen, and we panic
24045 	 * because either there's horrible heap corruption, and/or
24046 	 * programming mistake.
24047 	 */
24048 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24049 		goto pbuf_panic;
24050 
24051 	hdr_ptr = hdr_mp->b_rptr;
24052 	pld_ptr = mp->b_rptr;
24053 
24054 	/* Establish the ending byte offset, based on the starting offset. */
24055 	offset <<= 3;
24056 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24057 	    IP_SIMPLE_HDR_LENGTH;
24058 
24059 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24060 
24061 	while (pld_ptr < mp->b_wptr) {
24062 		ipha_t		*ipha;
24063 		uint16_t	offset_and_flags;
24064 		uint16_t	ip_len;
24065 		int		error;
24066 
24067 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24068 		ipha = (ipha_t *)(hdr_ptr + wroff);
24069 		ASSERT(OK_32PTR(ipha));
24070 		*ipha = *ipha_orig;
24071 
24072 		if (ip_data_end - offset > len) {
24073 			offset_and_flags = IPH_MF;
24074 		} else {
24075 			/*
24076 			 * Last frag. Set len to the length of this last piece.
24077 			 */
24078 			len = ip_data_end - offset;
24079 			/* A frag of a frag might have IPH_MF non-zero */
24080 			offset_and_flags =
24081 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24082 			    IPH_MF;
24083 		}
24084 		offset_and_flags |= (uint16_t)(offset >> 3);
24085 		offset_and_flags |= (uint16_t)frag_flag;
24086 		/* Store the offset and flags in the IP header. */
24087 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24088 
24089 		/* Store the length in the IP header. */
24090 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24091 		ipha->ipha_length = htons(ip_len);
24092 
24093 		/*
24094 		 * Set the IP header checksum.  Note that mp is just
24095 		 * the header, so this is easy to pass to ip_csum.
24096 		 */
24097 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24098 
24099 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24100 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24101 		    NULL, int, 0);
24102 
24103 		/*
24104 		 * Record offset and size of header and data of the next packet
24105 		 * in the multidata message.
24106 		 */
24107 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24108 		PDESC_PLD_INIT(&pdi);
24109 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24110 		ASSERT(i1 > 0);
24111 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24112 		if (i1 == len) {
24113 			pld_ptr += len;
24114 		} else {
24115 			i1 = len - i1;
24116 			mp = mp->b_cont;
24117 			ASSERT(mp != NULL);
24118 			ASSERT(MBLKL(mp) >= i1);
24119 			/*
24120 			 * Attach the next payload message block to the
24121 			 * multidata message.
24122 			 */
24123 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24124 				goto pbuf_panic;
24125 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24126 			pld_ptr = mp->b_rptr + i1;
24127 		}
24128 
24129 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24130 		    KM_NOSLEEP)) == NULL) {
24131 			/*
24132 			 * Any failure other than ENOMEM indicates that we
24133 			 * have passed in invalid pdesc info or parameters
24134 			 * to mmd_addpdesc, which must not happen.
24135 			 *
24136 			 * EINVAL is a result of failure on boundary checks
24137 			 * against the pdesc info contents.  It should not
24138 			 * happen, and we panic because either there's
24139 			 * horrible heap corruption, and/or programming
24140 			 * mistake.
24141 			 */
24142 			if (error != ENOMEM) {
24143 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24144 				    "pdesc logic error detected for "
24145 				    "mmd %p pinfo %p (%d)\n",
24146 				    (void *)mmd, (void *)&pdi, error);
24147 				/* NOTREACHED */
24148 			}
24149 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24150 			/* Free unattached payload message blocks as well */
24151 			md_mp->b_cont = mp->b_cont;
24152 			goto free_mmd;
24153 		}
24154 
24155 		/* Advance fragment offset. */
24156 		offset += len;
24157 
24158 		/* Advance to location for next header in the buffer. */
24159 		hdr_ptr += hdr_chunk_len;
24160 
24161 		/* Did we reach the next payload message block? */
24162 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24163 			mp = mp->b_cont;
24164 			/*
24165 			 * Attach the next message block with payload
24166 			 * data to the multidata message.
24167 			 */
24168 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24169 				goto pbuf_panic;
24170 			pld_ptr = mp->b_rptr;
24171 		}
24172 	}
24173 
24174 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24175 	ASSERT(mp->b_wptr == pld_ptr);
24176 
24177 	/* Update IP statistics */
24178 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24179 
24180 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24181 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24182 
24183 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24184 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24185 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24186 
24187 	if (pkt_type == OB_PKT) {
24188 		ire->ire_ob_pkt_count += pkts;
24189 		if (ire->ire_ipif != NULL)
24190 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24191 	} else {
24192 		/* The type is IB_PKT in the forwarding path. */
24193 		ire->ire_ib_pkt_count += pkts;
24194 		ASSERT(!IRE_IS_LOCAL(ire));
24195 		if (ire->ire_type & IRE_BROADCAST) {
24196 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24197 		} else {
24198 			UPDATE_MIB(ill->ill_ip_mib,
24199 			    ipIfStatsHCOutForwDatagrams, pkts);
24200 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24201 		}
24202 	}
24203 	ire->ire_last_used_time = lbolt;
24204 	/* Send it down */
24205 	putnext(ire->ire_stq, md_mp);
24206 	return;
24207 
24208 pbuf_panic:
24209 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24210 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24211 	    pbuf_idx);
24212 	/* NOTREACHED */
24213 }
24214 
24215 /*
24216  * Outbound IP fragmentation routine.
24217  *
24218  * NOTE : This routine does not ire_refrele the ire that is passed in
24219  * as the argument.
24220  */
24221 static void
24222 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24223     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24224 {
24225 	int		i1;
24226 	mblk_t		*ll_hdr_mp;
24227 	int 		ll_hdr_len;
24228 	int		hdr_len;
24229 	mblk_t		*hdr_mp;
24230 	ipha_t		*ipha;
24231 	int		ip_data_end;
24232 	int		len;
24233 	mblk_t		*mp = mp_orig, *mp1;
24234 	int		offset;
24235 	queue_t		*q;
24236 	uint32_t	v_hlen_tos_len;
24237 	mblk_t		*first_mp;
24238 	boolean_t	mctl_present;
24239 	ill_t		*ill;
24240 	ill_t		*out_ill;
24241 	mblk_t		*xmit_mp;
24242 	mblk_t		*carve_mp;
24243 	ire_t		*ire1 = NULL;
24244 	ire_t		*save_ire = NULL;
24245 	mblk_t  	*next_mp = NULL;
24246 	boolean_t	last_frag = B_FALSE;
24247 	boolean_t	multirt_send = B_FALSE;
24248 	ire_t		*first_ire = NULL;
24249 	irb_t		*irb = NULL;
24250 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24251 
24252 	ill = ire_to_ill(ire);
24253 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24254 
24255 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24256 
24257 	if (max_frag == 0) {
24258 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24259 		    " -  dropping packet\n"));
24260 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24261 		freemsg(mp);
24262 		return;
24263 	}
24264 
24265 	/*
24266 	 * IPsec does not allow hw accelerated packets to be fragmented
24267 	 * This check is made in ip_wput_ipsec_out prior to coming here
24268 	 * via ip_wput_ire_fragmentit.
24269 	 *
24270 	 * If at this point we have an ire whose ARP request has not
24271 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24272 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24273 	 * This packet and all fragmentable packets for this ire will
24274 	 * continue to get dropped while ire_nce->nce_state remains in
24275 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24276 	 * ND_REACHABLE, all subsquent large packets for this ire will
24277 	 * get fragemented and sent out by this function.
24278 	 */
24279 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24280 		/* If nce_state is ND_INITIAL, trigger ARP query */
24281 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24282 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24283 		    " -  dropping packet\n"));
24284 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24285 		freemsg(mp);
24286 		return;
24287 	}
24288 
24289 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24290 	    "ip_wput_frag_start:");
24291 
24292 	if (mp->b_datap->db_type == M_CTL) {
24293 		first_mp = mp;
24294 		mp_orig = mp = mp->b_cont;
24295 		mctl_present = B_TRUE;
24296 	} else {
24297 		first_mp = mp;
24298 		mctl_present = B_FALSE;
24299 	}
24300 
24301 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24302 	ipha = (ipha_t *)mp->b_rptr;
24303 
24304 	/*
24305 	 * If the Don't Fragment flag is on, generate an ICMP destination
24306 	 * unreachable, fragmentation needed.
24307 	 */
24308 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24309 	if (offset & IPH_DF) {
24310 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24311 		if (is_system_labeled()) {
24312 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24313 			    ire->ire_max_frag - max_frag, AF_INET);
24314 		}
24315 		/*
24316 		 * Need to compute hdr checksum if called from ip_wput_ire.
24317 		 * Note that ip_rput_forward verifies the checksum before
24318 		 * calling this routine so in that case this is a noop.
24319 		 */
24320 		ipha->ipha_hdr_checksum = 0;
24321 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24322 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24323 		    ipst);
24324 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24325 		    "ip_wput_frag_end:(%S)",
24326 		    "don't fragment");
24327 		return;
24328 	}
24329 	/*
24330 	 * Labeled systems adjust max_frag if they add a label
24331 	 * to send the correct path mtu.  We need the real mtu since we
24332 	 * are fragmenting the packet after label adjustment.
24333 	 */
24334 	if (is_system_labeled())
24335 		max_frag = ire->ire_max_frag;
24336 	if (mctl_present)
24337 		freeb(first_mp);
24338 	/*
24339 	 * Establish the starting offset.  May not be zero if we are fragging
24340 	 * a fragment that is being forwarded.
24341 	 */
24342 	offset = offset & IPH_OFFSET;
24343 
24344 	/* TODO why is this test needed? */
24345 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24346 	if (((max_frag - LENGTH) & ~7) < 8) {
24347 		/* TODO: notify ulp somehow */
24348 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24349 		freemsg(mp);
24350 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24351 		    "ip_wput_frag_end:(%S)",
24352 		    "len < 8");
24353 		return;
24354 	}
24355 
24356 	hdr_len = (V_HLEN & 0xF) << 2;
24357 
24358 	ipha->ipha_hdr_checksum = 0;
24359 
24360 	/*
24361 	 * Establish the number of bytes maximum per frag, after putting
24362 	 * in the header.
24363 	 */
24364 	len = (max_frag - hdr_len) & ~7;
24365 
24366 	/* Check if we can use MDT to send out the frags. */
24367 	ASSERT(!IRE_IS_LOCAL(ire));
24368 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24369 	    ipst->ips_ip_multidata_outbound &&
24370 	    !(ire->ire_flags & RTF_MULTIRT) &&
24371 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24372 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24373 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24374 		ASSERT(ill->ill_mdt_capab != NULL);
24375 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24376 			/*
24377 			 * If MDT has been previously turned off in the past,
24378 			 * and we currently can do MDT (due to IPQoS policy
24379 			 * removal, etc.) then enable it for this interface.
24380 			 */
24381 			ill->ill_mdt_capab->ill_mdt_on = 1;
24382 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24383 			    ill->ill_name));
24384 		}
24385 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24386 		    offset);
24387 		return;
24388 	}
24389 
24390 	/* Get a copy of the header for the trailing frags */
24391 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24392 	    mp);
24393 	if (!hdr_mp) {
24394 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24395 		freemsg(mp);
24396 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24397 		    "ip_wput_frag_end:(%S)",
24398 		    "couldn't copy hdr");
24399 		return;
24400 	}
24401 
24402 	/* Store the starting offset, with the MoreFrags flag. */
24403 	i1 = offset | IPH_MF | frag_flag;
24404 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24405 
24406 	/* Establish the ending byte offset, based on the starting offset. */
24407 	offset <<= 3;
24408 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24409 
24410 	/* Store the length of the first fragment in the IP header. */
24411 	i1 = len + hdr_len;
24412 	ASSERT(i1 <= IP_MAXPACKET);
24413 	ipha->ipha_length = htons((uint16_t)i1);
24414 
24415 	/*
24416 	 * Compute the IP header checksum for the first frag.  We have to
24417 	 * watch out that we stop at the end of the header.
24418 	 */
24419 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24420 
24421 	/*
24422 	 * Now carve off the first frag.  Note that this will include the
24423 	 * original IP header.
24424 	 */
24425 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24426 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24427 		freeb(hdr_mp);
24428 		freemsg(mp_orig);
24429 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24430 		    "ip_wput_frag_end:(%S)",
24431 		    "couldn't carve first");
24432 		return;
24433 	}
24434 
24435 	/*
24436 	 * Multirouting case. Each fragment is replicated
24437 	 * via all non-condemned RTF_MULTIRT routes
24438 	 * currently resolved.
24439 	 * We ensure that first_ire is the first RTF_MULTIRT
24440 	 * ire in the bucket.
24441 	 */
24442 	if (ire->ire_flags & RTF_MULTIRT) {
24443 		irb = ire->ire_bucket;
24444 		ASSERT(irb != NULL);
24445 
24446 		multirt_send = B_TRUE;
24447 
24448 		/* Make sure we do not omit any multiroute ire. */
24449 		IRB_REFHOLD(irb);
24450 		for (first_ire = irb->irb_ire;
24451 		    first_ire != NULL;
24452 		    first_ire = first_ire->ire_next) {
24453 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24454 			    (first_ire->ire_addr == ire->ire_addr) &&
24455 			    !(first_ire->ire_marks &
24456 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24457 				break;
24458 		}
24459 
24460 		if (first_ire != NULL) {
24461 			if (first_ire != ire) {
24462 				IRE_REFHOLD(first_ire);
24463 				/*
24464 				 * Do not release the ire passed in
24465 				 * as the argument.
24466 				 */
24467 				ire = first_ire;
24468 			} else {
24469 				first_ire = NULL;
24470 			}
24471 		}
24472 		IRB_REFRELE(irb);
24473 
24474 		/*
24475 		 * Save the first ire; we will need to restore it
24476 		 * for the trailing frags.
24477 		 * We REFHOLD save_ire, as each iterated ire will be
24478 		 * REFRELEd.
24479 		 */
24480 		save_ire = ire;
24481 		IRE_REFHOLD(save_ire);
24482 	}
24483 
24484 	/*
24485 	 * First fragment emission loop.
24486 	 * In most cases, the emission loop below is entered only
24487 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24488 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24489 	 * bucket, and send the fragment through all crossed
24490 	 * RTF_MULTIRT routes.
24491 	 */
24492 	do {
24493 		if (ire->ire_flags & RTF_MULTIRT) {
24494 			/*
24495 			 * We are in a multiple send case, need to get
24496 			 * the next ire and make a copy of the packet.
24497 			 * ire1 holds here the next ire to process in the
24498 			 * bucket. If multirouting is expected,
24499 			 * any non-RTF_MULTIRT ire that has the
24500 			 * right destination address is ignored.
24501 			 *
24502 			 * We have to take into account the MTU of
24503 			 * each walked ire. max_frag is set by the
24504 			 * the caller and generally refers to
24505 			 * the primary ire entry. Here we ensure that
24506 			 * no route with a lower MTU will be used, as
24507 			 * fragments are carved once for all ires,
24508 			 * then replicated.
24509 			 */
24510 			ASSERT(irb != NULL);
24511 			IRB_REFHOLD(irb);
24512 			for (ire1 = ire->ire_next;
24513 			    ire1 != NULL;
24514 			    ire1 = ire1->ire_next) {
24515 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24516 					continue;
24517 				if (ire1->ire_addr != ire->ire_addr)
24518 					continue;
24519 				if (ire1->ire_marks &
24520 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24521 					continue;
24522 				/*
24523 				 * Ensure we do not exceed the MTU
24524 				 * of the next route.
24525 				 */
24526 				if (ire1->ire_max_frag < max_frag) {
24527 					ip_multirt_bad_mtu(ire1, max_frag);
24528 					continue;
24529 				}
24530 
24531 				/* Got one. */
24532 				IRE_REFHOLD(ire1);
24533 				break;
24534 			}
24535 			IRB_REFRELE(irb);
24536 
24537 			if (ire1 != NULL) {
24538 				next_mp = copyb(mp);
24539 				if ((next_mp == NULL) ||
24540 				    ((mp->b_cont != NULL) &&
24541 				    ((next_mp->b_cont =
24542 				    dupmsg(mp->b_cont)) == NULL))) {
24543 					freemsg(next_mp);
24544 					next_mp = NULL;
24545 					ire_refrele(ire1);
24546 					ire1 = NULL;
24547 				}
24548 			}
24549 
24550 			/* Last multiroute ire; don't loop anymore. */
24551 			if (ire1 == NULL) {
24552 				multirt_send = B_FALSE;
24553 			}
24554 		}
24555 
24556 		ll_hdr_len = 0;
24557 		LOCK_IRE_FP_MP(ire);
24558 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24559 		if (ll_hdr_mp != NULL) {
24560 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24561 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24562 		} else {
24563 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24564 		}
24565 
24566 		/* If there is a transmit header, get a copy for this frag. */
24567 		/*
24568 		 * TODO: should check db_ref before calling ip_carve_mp since
24569 		 * it might give us a dup.
24570 		 */
24571 		if (!ll_hdr_mp) {
24572 			/* No xmit header. */
24573 			xmit_mp = mp;
24574 
24575 		/* We have a link-layer header that can fit in our mblk. */
24576 		} else if (mp->b_datap->db_ref == 1 &&
24577 		    ll_hdr_len != 0 &&
24578 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24579 			/* M_DATA fastpath */
24580 			mp->b_rptr -= ll_hdr_len;
24581 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24582 			xmit_mp = mp;
24583 
24584 		/* Corner case if copyb has failed */
24585 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24586 			UNLOCK_IRE_FP_MP(ire);
24587 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24588 			freeb(hdr_mp);
24589 			freemsg(mp);
24590 			freemsg(mp_orig);
24591 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24592 			    "ip_wput_frag_end:(%S)",
24593 			    "discard");
24594 
24595 			if (multirt_send) {
24596 				ASSERT(ire1);
24597 				ASSERT(next_mp);
24598 
24599 				freemsg(next_mp);
24600 				ire_refrele(ire1);
24601 			}
24602 			if (save_ire != NULL)
24603 				IRE_REFRELE(save_ire);
24604 
24605 			if (first_ire != NULL)
24606 				ire_refrele(first_ire);
24607 			return;
24608 
24609 		/*
24610 		 * Case of res_mp OR the fastpath mp can't fit
24611 		 * in the mblk
24612 		 */
24613 		} else {
24614 			xmit_mp->b_cont = mp;
24615 
24616 			/*
24617 			 * Get priority marking, if any.
24618 			 * We propagate the CoS marking from the
24619 			 * original packet that went to QoS processing
24620 			 * in ip_wput_ire to the newly carved mp.
24621 			 */
24622 			if (DB_TYPE(xmit_mp) == M_DATA)
24623 				xmit_mp->b_band = mp->b_band;
24624 		}
24625 		UNLOCK_IRE_FP_MP(ire);
24626 
24627 		q = ire->ire_stq;
24628 		out_ill = (ill_t *)q->q_ptr;
24629 
24630 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24631 
24632 		DTRACE_PROBE4(ip4__physical__out__start,
24633 		    ill_t *, NULL, ill_t *, out_ill,
24634 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24635 
24636 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24637 		    ipst->ips_ipv4firewall_physical_out,
24638 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24639 
24640 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24641 
24642 		if (xmit_mp != NULL) {
24643 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24644 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24645 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24646 
24647 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24648 
24649 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24650 			UPDATE_MIB(out_ill->ill_ip_mib,
24651 			    ipIfStatsHCOutOctets, i1);
24652 
24653 			if (pkt_type != OB_PKT) {
24654 				/*
24655 				 * Update the packet count and MIB stats
24656 				 * of trailing RTF_MULTIRT ires.
24657 				 */
24658 				UPDATE_OB_PKT_COUNT(ire);
24659 				BUMP_MIB(out_ill->ill_ip_mib,
24660 				    ipIfStatsOutFragReqds);
24661 			}
24662 		}
24663 
24664 		if (multirt_send) {
24665 			/*
24666 			 * We are in a multiple send case; look for
24667 			 * the next ire and re-enter the loop.
24668 			 */
24669 			ASSERT(ire1);
24670 			ASSERT(next_mp);
24671 			/* REFRELE the current ire before looping */
24672 			ire_refrele(ire);
24673 			ire = ire1;
24674 			ire1 = NULL;
24675 			mp = next_mp;
24676 			next_mp = NULL;
24677 		}
24678 	} while (multirt_send);
24679 
24680 	ASSERT(ire1 == NULL);
24681 
24682 	/* Restore the original ire; we need it for the trailing frags */
24683 	if (save_ire != NULL) {
24684 		/* REFRELE the last iterated ire */
24685 		ire_refrele(ire);
24686 		/* save_ire has been REFHOLDed */
24687 		ire = save_ire;
24688 		save_ire = NULL;
24689 		q = ire->ire_stq;
24690 	}
24691 
24692 	if (pkt_type == OB_PKT) {
24693 		UPDATE_OB_PKT_COUNT(ire);
24694 	} else {
24695 		out_ill = (ill_t *)q->q_ptr;
24696 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24697 		UPDATE_IB_PKT_COUNT(ire);
24698 	}
24699 
24700 	/* Advance the offset to the second frag starting point. */
24701 	offset += len;
24702 	/*
24703 	 * Update hdr_len from the copied header - there might be less options
24704 	 * in the later fragments.
24705 	 */
24706 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24707 	/* Loop until done. */
24708 	for (;;) {
24709 		uint16_t	offset_and_flags;
24710 		uint16_t	ip_len;
24711 
24712 		if (ip_data_end - offset > len) {
24713 			/*
24714 			 * Carve off the appropriate amount from the original
24715 			 * datagram.
24716 			 */
24717 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24718 				mp = NULL;
24719 				break;
24720 			}
24721 			/*
24722 			 * More frags after this one.  Get another copy
24723 			 * of the header.
24724 			 */
24725 			if (carve_mp->b_datap->db_ref == 1 &&
24726 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24727 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24728 				/* Inline IP header */
24729 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24730 				    hdr_mp->b_rptr;
24731 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24732 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24733 				mp = carve_mp;
24734 			} else {
24735 				if (!(mp = copyb(hdr_mp))) {
24736 					freemsg(carve_mp);
24737 					break;
24738 				}
24739 				/* Get priority marking, if any. */
24740 				mp->b_band = carve_mp->b_band;
24741 				mp->b_cont = carve_mp;
24742 			}
24743 			ipha = (ipha_t *)mp->b_rptr;
24744 			offset_and_flags = IPH_MF;
24745 		} else {
24746 			/*
24747 			 * Last frag.  Consume the header. Set len to
24748 			 * the length of this last piece.
24749 			 */
24750 			len = ip_data_end - offset;
24751 
24752 			/*
24753 			 * Carve off the appropriate amount from the original
24754 			 * datagram.
24755 			 */
24756 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24757 				mp = NULL;
24758 				break;
24759 			}
24760 			if (carve_mp->b_datap->db_ref == 1 &&
24761 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24762 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24763 				/* Inline IP header */
24764 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24765 				    hdr_mp->b_rptr;
24766 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24767 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24768 				mp = carve_mp;
24769 				freeb(hdr_mp);
24770 				hdr_mp = mp;
24771 			} else {
24772 				mp = hdr_mp;
24773 				/* Get priority marking, if any. */
24774 				mp->b_band = carve_mp->b_band;
24775 				mp->b_cont = carve_mp;
24776 			}
24777 			ipha = (ipha_t *)mp->b_rptr;
24778 			/* A frag of a frag might have IPH_MF non-zero */
24779 			offset_and_flags =
24780 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24781 			    IPH_MF;
24782 		}
24783 		offset_and_flags |= (uint16_t)(offset >> 3);
24784 		offset_and_flags |= (uint16_t)frag_flag;
24785 		/* Store the offset and flags in the IP header. */
24786 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24787 
24788 		/* Store the length in the IP header. */
24789 		ip_len = (uint16_t)(len + hdr_len);
24790 		ipha->ipha_length = htons(ip_len);
24791 
24792 		/*
24793 		 * Set the IP header checksum.	Note that mp is just
24794 		 * the header, so this is easy to pass to ip_csum.
24795 		 */
24796 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24797 
24798 		/* Attach a transmit header, if any, and ship it. */
24799 		if (pkt_type == OB_PKT) {
24800 			UPDATE_OB_PKT_COUNT(ire);
24801 		} else {
24802 			out_ill = (ill_t *)q->q_ptr;
24803 			BUMP_MIB(out_ill->ill_ip_mib,
24804 			    ipIfStatsHCOutForwDatagrams);
24805 			UPDATE_IB_PKT_COUNT(ire);
24806 		}
24807 
24808 		if (ire->ire_flags & RTF_MULTIRT) {
24809 			irb = ire->ire_bucket;
24810 			ASSERT(irb != NULL);
24811 
24812 			multirt_send = B_TRUE;
24813 
24814 			/*
24815 			 * Save the original ire; we will need to restore it
24816 			 * for the tailing frags.
24817 			 */
24818 			save_ire = ire;
24819 			IRE_REFHOLD(save_ire);
24820 		}
24821 		/*
24822 		 * Emission loop for this fragment, similar
24823 		 * to what is done for the first fragment.
24824 		 */
24825 		do {
24826 			if (multirt_send) {
24827 				/*
24828 				 * We are in a multiple send case, need to get
24829 				 * the next ire and make a copy of the packet.
24830 				 */
24831 				ASSERT(irb != NULL);
24832 				IRB_REFHOLD(irb);
24833 				for (ire1 = ire->ire_next;
24834 				    ire1 != NULL;
24835 				    ire1 = ire1->ire_next) {
24836 					if (!(ire1->ire_flags & RTF_MULTIRT))
24837 						continue;
24838 					if (ire1->ire_addr != ire->ire_addr)
24839 						continue;
24840 					if (ire1->ire_marks &
24841 					    (IRE_MARK_CONDEMNED |
24842 					    IRE_MARK_TESTHIDDEN))
24843 						continue;
24844 					/*
24845 					 * Ensure we do not exceed the MTU
24846 					 * of the next route.
24847 					 */
24848 					if (ire1->ire_max_frag < max_frag) {
24849 						ip_multirt_bad_mtu(ire1,
24850 						    max_frag);
24851 						continue;
24852 					}
24853 
24854 					/* Got one. */
24855 					IRE_REFHOLD(ire1);
24856 					break;
24857 				}
24858 				IRB_REFRELE(irb);
24859 
24860 				if (ire1 != NULL) {
24861 					next_mp = copyb(mp);
24862 					if ((next_mp == NULL) ||
24863 					    ((mp->b_cont != NULL) &&
24864 					    ((next_mp->b_cont =
24865 					    dupmsg(mp->b_cont)) == NULL))) {
24866 						freemsg(next_mp);
24867 						next_mp = NULL;
24868 						ire_refrele(ire1);
24869 						ire1 = NULL;
24870 					}
24871 				}
24872 
24873 				/* Last multiroute ire; don't loop anymore. */
24874 				if (ire1 == NULL) {
24875 					multirt_send = B_FALSE;
24876 				}
24877 			}
24878 
24879 			/* Update transmit header */
24880 			ll_hdr_len = 0;
24881 			LOCK_IRE_FP_MP(ire);
24882 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24883 			if (ll_hdr_mp != NULL) {
24884 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24885 				ll_hdr_len = MBLKL(ll_hdr_mp);
24886 			} else {
24887 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24888 			}
24889 
24890 			if (!ll_hdr_mp) {
24891 				xmit_mp = mp;
24892 
24893 			/*
24894 			 * We have link-layer header that can fit in
24895 			 * our mblk.
24896 			 */
24897 			} else if (mp->b_datap->db_ref == 1 &&
24898 			    ll_hdr_len != 0 &&
24899 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24900 				/* M_DATA fastpath */
24901 				mp->b_rptr -= ll_hdr_len;
24902 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24903 				    ll_hdr_len);
24904 				xmit_mp = mp;
24905 
24906 			/*
24907 			 * Case of res_mp OR the fastpath mp can't fit
24908 			 * in the mblk
24909 			 */
24910 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24911 				xmit_mp->b_cont = mp;
24912 				/* Get priority marking, if any. */
24913 				if (DB_TYPE(xmit_mp) == M_DATA)
24914 					xmit_mp->b_band = mp->b_band;
24915 
24916 			/* Corner case if copyb failed */
24917 			} else {
24918 				/*
24919 				 * Exit both the replication and
24920 				 * fragmentation loops.
24921 				 */
24922 				UNLOCK_IRE_FP_MP(ire);
24923 				goto drop_pkt;
24924 			}
24925 			UNLOCK_IRE_FP_MP(ire);
24926 
24927 			mp1 = mp;
24928 			out_ill = (ill_t *)q->q_ptr;
24929 
24930 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24931 
24932 			DTRACE_PROBE4(ip4__physical__out__start,
24933 			    ill_t *, NULL, ill_t *, out_ill,
24934 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24935 
24936 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24937 			    ipst->ips_ipv4firewall_physical_out,
24938 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24939 
24940 			DTRACE_PROBE1(ip4__physical__out__end,
24941 			    mblk_t *, xmit_mp);
24942 
24943 			if (mp != mp1 && hdr_mp == mp1)
24944 				hdr_mp = mp;
24945 			if (mp != mp1 && mp_orig == mp1)
24946 				mp_orig = mp;
24947 
24948 			if (xmit_mp != NULL) {
24949 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24950 				    NULL, void_ip_t *, ipha,
24951 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24952 				    ipha, ip6_t *, NULL, int, 0);
24953 
24954 				ILL_SEND_TX(out_ill, ire, connp,
24955 				    xmit_mp, 0, connp);
24956 
24957 				BUMP_MIB(out_ill->ill_ip_mib,
24958 				    ipIfStatsHCOutTransmits);
24959 				UPDATE_MIB(out_ill->ill_ip_mib,
24960 				    ipIfStatsHCOutOctets, ip_len);
24961 
24962 				if (pkt_type != OB_PKT) {
24963 					/*
24964 					 * Update the packet count of trailing
24965 					 * RTF_MULTIRT ires.
24966 					 */
24967 					UPDATE_OB_PKT_COUNT(ire);
24968 				}
24969 			}
24970 
24971 			/* All done if we just consumed the hdr_mp. */
24972 			if (mp == hdr_mp) {
24973 				last_frag = B_TRUE;
24974 				BUMP_MIB(out_ill->ill_ip_mib,
24975 				    ipIfStatsOutFragOKs);
24976 			}
24977 
24978 			if (multirt_send) {
24979 				/*
24980 				 * We are in a multiple send case; look for
24981 				 * the next ire and re-enter the loop.
24982 				 */
24983 				ASSERT(ire1);
24984 				ASSERT(next_mp);
24985 				/* REFRELE the current ire before looping */
24986 				ire_refrele(ire);
24987 				ire = ire1;
24988 				ire1 = NULL;
24989 				q = ire->ire_stq;
24990 				mp = next_mp;
24991 				next_mp = NULL;
24992 			}
24993 		} while (multirt_send);
24994 		/*
24995 		 * Restore the original ire; we need it for the
24996 		 * trailing frags
24997 		 */
24998 		if (save_ire != NULL) {
24999 			ASSERT(ire1 == NULL);
25000 			/* REFRELE the last iterated ire */
25001 			ire_refrele(ire);
25002 			/* save_ire has been REFHOLDed */
25003 			ire = save_ire;
25004 			q = ire->ire_stq;
25005 			save_ire = NULL;
25006 		}
25007 
25008 		if (last_frag) {
25009 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25010 			    "ip_wput_frag_end:(%S)",
25011 			    "consumed hdr_mp");
25012 
25013 			if (first_ire != NULL)
25014 				ire_refrele(first_ire);
25015 			return;
25016 		}
25017 		/* Otherwise, advance and loop. */
25018 		offset += len;
25019 	}
25020 
25021 drop_pkt:
25022 	/* Clean up following allocation failure. */
25023 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25024 	freemsg(mp);
25025 	if (mp != hdr_mp)
25026 		freeb(hdr_mp);
25027 	if (mp != mp_orig)
25028 		freemsg(mp_orig);
25029 
25030 	if (save_ire != NULL)
25031 		IRE_REFRELE(save_ire);
25032 	if (first_ire != NULL)
25033 		ire_refrele(first_ire);
25034 
25035 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25036 	    "ip_wput_frag_end:(%S)",
25037 	    "end--alloc failure");
25038 }
25039 
25040 /*
25041  * Copy the header plus those options which have the copy bit set
25042  * src is the template to make sure we preserve the cred for TX purposes.
25043  */
25044 static mblk_t *
25045 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
25046     mblk_t *src)
25047 {
25048 	mblk_t	*mp;
25049 	uchar_t	*up;
25050 
25051 	/*
25052 	 * Quick check if we need to look for options without the copy bit
25053 	 * set
25054 	 */
25055 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
25056 	if (!mp)
25057 		return (mp);
25058 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25059 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25060 		bcopy(rptr, mp->b_rptr, hdr_len);
25061 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25062 		return (mp);
25063 	}
25064 	up  = mp->b_rptr;
25065 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25066 	up += IP_SIMPLE_HDR_LENGTH;
25067 	rptr += IP_SIMPLE_HDR_LENGTH;
25068 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25069 	while (hdr_len > 0) {
25070 		uint32_t optval;
25071 		uint32_t optlen;
25072 
25073 		optval = *rptr;
25074 		if (optval == IPOPT_EOL)
25075 			break;
25076 		if (optval == IPOPT_NOP)
25077 			optlen = 1;
25078 		else
25079 			optlen = rptr[1];
25080 		if (optval & IPOPT_COPY) {
25081 			bcopy(rptr, up, optlen);
25082 			up += optlen;
25083 		}
25084 		rptr += optlen;
25085 		hdr_len -= optlen;
25086 	}
25087 	/*
25088 	 * Make sure that we drop an even number of words by filling
25089 	 * with EOL to the next word boundary.
25090 	 */
25091 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25092 	    hdr_len & 0x3; hdr_len++)
25093 		*up++ = IPOPT_EOL;
25094 	mp->b_wptr = up;
25095 	/* Update header length */
25096 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25097 	return (mp);
25098 }
25099 
25100 /*
25101  * Delivery to local recipients including fanout to multiple recipients.
25102  * Does not do checksumming of UDP/TCP.
25103  * Note: q should be the read side queue for either the ill or conn.
25104  * Note: rq should be the read side q for the lower (ill) stream.
25105  * We don't send packets to IPPF processing, thus the last argument
25106  * to all the fanout calls are B_FALSE.
25107  */
25108 void
25109 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25110     int fanout_flags, zoneid_t zoneid)
25111 {
25112 	uint32_t	protocol;
25113 	mblk_t		*first_mp;
25114 	boolean_t	mctl_present;
25115 	int		ire_type;
25116 #define	rptr	((uchar_t *)ipha)
25117 	ip_stack_t	*ipst = ill->ill_ipst;
25118 
25119 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25120 	    "ip_wput_local_start: q %p", q);
25121 
25122 	if (ire != NULL) {
25123 		ire_type = ire->ire_type;
25124 	} else {
25125 		/*
25126 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25127 		 * packet is not multicast, we can't tell the ire type.
25128 		 */
25129 		ASSERT(CLASSD(ipha->ipha_dst));
25130 		ire_type = IRE_BROADCAST;
25131 	}
25132 
25133 	first_mp = mp;
25134 	if (first_mp->b_datap->db_type == M_CTL) {
25135 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25136 		if (!io->ipsec_out_secure) {
25137 			/*
25138 			 * This ipsec_out_t was allocated in ip_wput
25139 			 * for multicast packets to store the ill_index.
25140 			 * As this is being delivered locally, we don't
25141 			 * need this anymore.
25142 			 */
25143 			mp = first_mp->b_cont;
25144 			freeb(first_mp);
25145 			first_mp = mp;
25146 			mctl_present = B_FALSE;
25147 		} else {
25148 			/*
25149 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25150 			 * security properties for the looped-back packet.
25151 			 */
25152 			mctl_present = B_TRUE;
25153 			mp = first_mp->b_cont;
25154 			ASSERT(mp != NULL);
25155 			ipsec_out_to_in(first_mp);
25156 		}
25157 	} else {
25158 		mctl_present = B_FALSE;
25159 	}
25160 
25161 	DTRACE_PROBE4(ip4__loopback__in__start,
25162 	    ill_t *, ill, ill_t *, NULL,
25163 	    ipha_t *, ipha, mblk_t *, first_mp);
25164 
25165 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25166 	    ipst->ips_ipv4firewall_loopback_in,
25167 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25168 
25169 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25170 
25171 	if (first_mp == NULL)
25172 		return;
25173 
25174 	if (ipst->ips_ipobs_enabled) {
25175 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25176 		zoneid_t stackzoneid = netstackid_to_zoneid(
25177 		    ipst->ips_netstack->netstack_stackid);
25178 
25179 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25180 		/*
25181 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25182 		 * address.  Restrict the lookup below to the destination zone.
25183 		 */
25184 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25185 			lookup_zoneid = zoneid;
25186 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25187 		    lookup_zoneid);
25188 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25189 		    IPV4_VERSION, 0, ipst);
25190 	}
25191 
25192 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25193 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25194 	    int, 1);
25195 
25196 	ipst->ips_loopback_packets++;
25197 
25198 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25199 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25200 	if (!IS_SIMPLE_IPH(ipha)) {
25201 		ip_wput_local_options(ipha, ipst);
25202 	}
25203 
25204 	protocol = ipha->ipha_protocol;
25205 	switch (protocol) {
25206 	case IPPROTO_ICMP: {
25207 		ire_t		*ire_zone;
25208 		ilm_t		*ilm;
25209 		mblk_t		*mp1;
25210 		zoneid_t	last_zoneid;
25211 		ilm_walker_t	ilw;
25212 
25213 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25214 			ASSERT(ire_type == IRE_BROADCAST);
25215 			/*
25216 			 * In the multicast case, applications may have joined
25217 			 * the group from different zones, so we need to deliver
25218 			 * the packet to each of them. Loop through the
25219 			 * multicast memberships structures (ilm) on the receive
25220 			 * ill and send a copy of the packet up each matching
25221 			 * one. However, we don't do this for multicasts sent on
25222 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25223 			 * they must stay in the sender's zone.
25224 			 *
25225 			 * ilm_add_v6() ensures that ilms in the same zone are
25226 			 * contiguous in the ill_ilm list. We use this property
25227 			 * to avoid sending duplicates needed when two
25228 			 * applications in the same zone join the same group on
25229 			 * different logical interfaces: we ignore the ilm if
25230 			 * it's zoneid is the same as the last matching one.
25231 			 * In addition, the sending of the packet for
25232 			 * ire_zoneid is delayed until all of the other ilms
25233 			 * have been exhausted.
25234 			 */
25235 			last_zoneid = -1;
25236 			ilm = ilm_walker_start(&ilw, ill);
25237 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25238 				if (ipha->ipha_dst != ilm->ilm_addr ||
25239 				    ilm->ilm_zoneid == last_zoneid ||
25240 				    ilm->ilm_zoneid == zoneid ||
25241 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25242 					continue;
25243 				mp1 = ip_copymsg(first_mp);
25244 				if (mp1 == NULL)
25245 					continue;
25246 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25247 				    0, 0, mctl_present, B_FALSE, ill,
25248 				    ilm->ilm_zoneid);
25249 				last_zoneid = ilm->ilm_zoneid;
25250 			}
25251 			ilm_walker_finish(&ilw);
25252 			/*
25253 			 * Loopback case: the sending endpoint has
25254 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25255 			 * dispatch the multicast packet to the sending zone.
25256 			 */
25257 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25258 				freemsg(first_mp);
25259 				return;
25260 			}
25261 		} else if (ire_type == IRE_BROADCAST) {
25262 			/*
25263 			 * In the broadcast case, there may be many zones
25264 			 * which need a copy of the packet delivered to them.
25265 			 * There is one IRE_BROADCAST per broadcast address
25266 			 * and per zone; we walk those using a helper function.
25267 			 * In addition, the sending of the packet for zoneid is
25268 			 * delayed until all of the other ires have been
25269 			 * processed.
25270 			 */
25271 			IRB_REFHOLD(ire->ire_bucket);
25272 			ire_zone = NULL;
25273 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25274 			    ire)) != NULL) {
25275 				mp1 = ip_copymsg(first_mp);
25276 				if (mp1 == NULL)
25277 					continue;
25278 
25279 				UPDATE_IB_PKT_COUNT(ire_zone);
25280 				ire_zone->ire_last_used_time = lbolt;
25281 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25282 				    mctl_present, B_FALSE, ill,
25283 				    ire_zone->ire_zoneid);
25284 			}
25285 			IRB_REFRELE(ire->ire_bucket);
25286 		}
25287 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25288 		    0, mctl_present, B_FALSE, ill, zoneid);
25289 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25290 		    "ip_wput_local_end: q %p (%S)",
25291 		    q, "icmp");
25292 		return;
25293 	}
25294 	case IPPROTO_IGMP:
25295 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25296 			/* Bad packet - discarded by igmp_input */
25297 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25298 			    "ip_wput_local_end: q %p (%S)",
25299 			    q, "igmp_input--bad packet");
25300 			if (mctl_present)
25301 				freeb(first_mp);
25302 			return;
25303 		}
25304 		/*
25305 		 * igmp_input() may have returned the pulled up message.
25306 		 * So first_mp and ipha need to be reinitialized.
25307 		 */
25308 		ipha = (ipha_t *)mp->b_rptr;
25309 		if (mctl_present)
25310 			first_mp->b_cont = mp;
25311 		else
25312 			first_mp = mp;
25313 		/* deliver to local raw users */
25314 		break;
25315 	case IPPROTO_ENCAP:
25316 		/*
25317 		 * This case is covered by either ip_fanout_proto, or by
25318 		 * the above security processing for self-tunneled packets.
25319 		 */
25320 		break;
25321 	case IPPROTO_UDP: {
25322 		uint16_t	*up;
25323 		uint32_t	ports;
25324 
25325 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25326 		    UDP_PORTS_OFFSET);
25327 		/* Force a 'valid' checksum. */
25328 		up[3] = 0;
25329 
25330 		ports = *(uint32_t *)up;
25331 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25332 		    (ire_type == IRE_BROADCAST),
25333 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25334 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25335 		    ill, zoneid);
25336 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25337 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25338 		return;
25339 	}
25340 	case IPPROTO_TCP: {
25341 
25342 		/*
25343 		 * For TCP, discard broadcast packets.
25344 		 */
25345 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25346 			freemsg(first_mp);
25347 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25348 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25349 			return;
25350 		}
25351 
25352 		if (mp->b_datap->db_type == M_DATA) {
25353 			/*
25354 			 * M_DATA mblk, so init mblk (chain) for no struio().
25355 			 */
25356 			mblk_t	*mp1 = mp;
25357 
25358 			do {
25359 				mp1->b_datap->db_struioflag = 0;
25360 			} while ((mp1 = mp1->b_cont) != NULL);
25361 		}
25362 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25363 		    <= mp->b_wptr);
25364 		ip_fanout_tcp(q, first_mp, ill, ipha,
25365 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25366 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25367 		    mctl_present, B_FALSE, zoneid);
25368 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25369 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25370 		return;
25371 	}
25372 	case IPPROTO_SCTP:
25373 	{
25374 		uint32_t	ports;
25375 
25376 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25377 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25378 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25379 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25380 		return;
25381 	}
25382 
25383 	default:
25384 		break;
25385 	}
25386 	/*
25387 	 * Find a client for some other protocol.  We give
25388 	 * copies to multiple clients, if more than one is
25389 	 * bound.
25390 	 */
25391 	ip_fanout_proto(q, first_mp, ill, ipha,
25392 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25393 	    mctl_present, B_FALSE, ill, zoneid);
25394 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25395 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25396 #undef	rptr
25397 }
25398 
25399 /*
25400  * Update any source route, record route, or timestamp options.
25401  * Check that we are at end of strict source route.
25402  * The options have been sanity checked by ip_wput_options().
25403  */
25404 static void
25405 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25406 {
25407 	ipoptp_t	opts;
25408 	uchar_t		*opt;
25409 	uint8_t		optval;
25410 	uint8_t		optlen;
25411 	ipaddr_t	dst;
25412 	uint32_t	ts;
25413 	ire_t		*ire;
25414 	timestruc_t	now;
25415 
25416 	ip2dbg(("ip_wput_local_options\n"));
25417 	for (optval = ipoptp_first(&opts, ipha);
25418 	    optval != IPOPT_EOL;
25419 	    optval = ipoptp_next(&opts)) {
25420 		opt = opts.ipoptp_cur;
25421 		optlen = opts.ipoptp_len;
25422 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25423 		switch (optval) {
25424 			uint32_t off;
25425 		case IPOPT_SSRR:
25426 		case IPOPT_LSRR:
25427 			off = opt[IPOPT_OFFSET];
25428 			off--;
25429 			if (optlen < IP_ADDR_LEN ||
25430 			    off > optlen - IP_ADDR_LEN) {
25431 				/* End of source route */
25432 				break;
25433 			}
25434 			/*
25435 			 * This will only happen if two consecutive entries
25436 			 * in the source route contains our address or if
25437 			 * it is a packet with a loose source route which
25438 			 * reaches us before consuming the whole source route
25439 			 */
25440 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25441 			if (optval == IPOPT_SSRR) {
25442 				return;
25443 			}
25444 			/*
25445 			 * Hack: instead of dropping the packet truncate the
25446 			 * source route to what has been used by filling the
25447 			 * rest with IPOPT_NOP.
25448 			 */
25449 			opt[IPOPT_OLEN] = (uint8_t)off;
25450 			while (off < optlen) {
25451 				opt[off++] = IPOPT_NOP;
25452 			}
25453 			break;
25454 		case IPOPT_RR:
25455 			off = opt[IPOPT_OFFSET];
25456 			off--;
25457 			if (optlen < IP_ADDR_LEN ||
25458 			    off > optlen - IP_ADDR_LEN) {
25459 				/* No more room - ignore */
25460 				ip1dbg((
25461 				    "ip_wput_forward_options: end of RR\n"));
25462 				break;
25463 			}
25464 			dst = htonl(INADDR_LOOPBACK);
25465 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25466 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25467 			break;
25468 		case IPOPT_TS:
25469 			/* Insert timestamp if there is romm */
25470 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25471 			case IPOPT_TS_TSONLY:
25472 				off = IPOPT_TS_TIMELEN;
25473 				break;
25474 			case IPOPT_TS_PRESPEC:
25475 			case IPOPT_TS_PRESPEC_RFC791:
25476 				/* Verify that the address matched */
25477 				off = opt[IPOPT_OFFSET] - 1;
25478 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25479 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25480 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25481 				    ipst);
25482 				if (ire == NULL) {
25483 					/* Not for us */
25484 					break;
25485 				}
25486 				ire_refrele(ire);
25487 				/* FALLTHRU */
25488 			case IPOPT_TS_TSANDADDR:
25489 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25490 				break;
25491 			default:
25492 				/*
25493 				 * ip_*put_options should have already
25494 				 * dropped this packet.
25495 				 */
25496 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25497 				    "unknown IT - bug in ip_wput_options?\n");
25498 				return;	/* Keep "lint" happy */
25499 			}
25500 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25501 				/* Increase overflow counter */
25502 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25503 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25504 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25505 				    (off << 4);
25506 				break;
25507 			}
25508 			off = opt[IPOPT_OFFSET] - 1;
25509 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25510 			case IPOPT_TS_PRESPEC:
25511 			case IPOPT_TS_PRESPEC_RFC791:
25512 			case IPOPT_TS_TSANDADDR:
25513 				dst = htonl(INADDR_LOOPBACK);
25514 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25515 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25516 				/* FALLTHRU */
25517 			case IPOPT_TS_TSONLY:
25518 				off = opt[IPOPT_OFFSET] - 1;
25519 				/* Compute # of milliseconds since midnight */
25520 				gethrestime(&now);
25521 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25522 				    now.tv_nsec / (NANOSEC / MILLISEC);
25523 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25524 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25525 				break;
25526 			}
25527 			break;
25528 		}
25529 	}
25530 }
25531 
25532 /*
25533  * Send out a multicast packet on interface ipif.
25534  * The sender does not have an conn.
25535  * Caller verifies that this isn't a PHYI_LOOPBACK.
25536  */
25537 void
25538 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25539 {
25540 	ipha_t	*ipha;
25541 	ire_t	*ire;
25542 	ipaddr_t	dst;
25543 	mblk_t		*first_mp;
25544 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25545 
25546 	/* igmp_sendpkt always allocates a ipsec_out_t */
25547 	ASSERT(mp->b_datap->db_type == M_CTL);
25548 	ASSERT(!ipif->ipif_isv6);
25549 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25550 
25551 	first_mp = mp;
25552 	mp = first_mp->b_cont;
25553 	ASSERT(mp->b_datap->db_type == M_DATA);
25554 	ipha = (ipha_t *)mp->b_rptr;
25555 
25556 	/*
25557 	 * Find an IRE which matches the destination and the outgoing
25558 	 * queue (i.e. the outgoing interface.)
25559 	 */
25560 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25561 		dst = ipif->ipif_pp_dst_addr;
25562 	else
25563 		dst = ipha->ipha_dst;
25564 	/*
25565 	 * The source address has already been initialized by the
25566 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25567 	 * be sufficient rather than MATCH_IRE_IPIF.
25568 	 *
25569 	 * This function is used for sending IGMP packets.  For IPMP,
25570 	 * we sidestep IGMP snooping issues by sending all multicast
25571 	 * traffic on a single interface in the IPMP group.
25572 	 */
25573 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25574 	    MATCH_IRE_ILL, ipst);
25575 	if (!ire) {
25576 		/*
25577 		 * Mark this packet to make it be delivered to
25578 		 * ip_wput_ire after the new ire has been
25579 		 * created.
25580 		 */
25581 		mp->b_prev = NULL;
25582 		mp->b_next = NULL;
25583 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25584 		    zoneid, &zero_info);
25585 		return;
25586 	}
25587 
25588 	/*
25589 	 * Honor the RTF_SETSRC flag; this is the only case
25590 	 * where we force this addr whatever the current src addr is,
25591 	 * because this address is set by igmp_sendpkt(), and
25592 	 * cannot be specified by any user.
25593 	 */
25594 	if (ire->ire_flags & RTF_SETSRC) {
25595 		ipha->ipha_src = ire->ire_src_addr;
25596 	}
25597 
25598 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25599 }
25600 
25601 /*
25602  * NOTE : This function does not ire_refrele the ire argument passed in.
25603  *
25604  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25605  * failure. The nce_fp_mp can vanish any time in the case of
25606  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25607  * the ire_lock to access the nce_fp_mp in this case.
25608  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25609  * prepending a fastpath message IPQoS processing must precede it, we also set
25610  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25611  * (IPQoS might have set the b_band for CoS marking).
25612  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25613  * must follow it so that IPQoS can mark the dl_priority field for CoS
25614  * marking, if needed.
25615  */
25616 static mblk_t *
25617 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25618     uint32_t ill_index, ipha_t **iphap)
25619 {
25620 	uint_t	hlen;
25621 	ipha_t *ipha;
25622 	mblk_t *mp1;
25623 	boolean_t qos_done = B_FALSE;
25624 	uchar_t	*ll_hdr;
25625 	ip_stack_t	*ipst = ire->ire_ipst;
25626 
25627 #define	rptr	((uchar_t *)ipha)
25628 
25629 	ipha = (ipha_t *)mp->b_rptr;
25630 	hlen = 0;
25631 	LOCK_IRE_FP_MP(ire);
25632 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25633 		ASSERT(DB_TYPE(mp1) == M_DATA);
25634 		/* Initiate IPPF processing */
25635 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25636 			UNLOCK_IRE_FP_MP(ire);
25637 			ip_process(proc, &mp, ill_index);
25638 			if (mp == NULL)
25639 				return (NULL);
25640 
25641 			ipha = (ipha_t *)mp->b_rptr;
25642 			LOCK_IRE_FP_MP(ire);
25643 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25644 				qos_done = B_TRUE;
25645 				goto no_fp_mp;
25646 			}
25647 			ASSERT(DB_TYPE(mp1) == M_DATA);
25648 		}
25649 		hlen = MBLKL(mp1);
25650 		/*
25651 		 * Check if we have enough room to prepend fastpath
25652 		 * header
25653 		 */
25654 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25655 			ll_hdr = rptr - hlen;
25656 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25657 			/*
25658 			 * Set the b_rptr to the start of the link layer
25659 			 * header
25660 			 */
25661 			mp->b_rptr = ll_hdr;
25662 			mp1 = mp;
25663 		} else {
25664 			mp1 = copyb(mp1);
25665 			if (mp1 == NULL)
25666 				goto unlock_err;
25667 			mp1->b_band = mp->b_band;
25668 			mp1->b_cont = mp;
25669 			/*
25670 			 * XXX disable ICK_VALID and compute checksum
25671 			 * here; can happen if nce_fp_mp changes and
25672 			 * it can't be copied now due to insufficient
25673 			 * space. (unlikely, fp mp can change, but it
25674 			 * does not increase in length)
25675 			 */
25676 		}
25677 		UNLOCK_IRE_FP_MP(ire);
25678 	} else {
25679 no_fp_mp:
25680 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25681 		if (mp1 == NULL) {
25682 unlock_err:
25683 			UNLOCK_IRE_FP_MP(ire);
25684 			freemsg(mp);
25685 			return (NULL);
25686 		}
25687 		UNLOCK_IRE_FP_MP(ire);
25688 		mp1->b_cont = mp;
25689 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25690 			ip_process(proc, &mp1, ill_index);
25691 			if (mp1 == NULL)
25692 				return (NULL);
25693 
25694 			if (mp1->b_cont == NULL)
25695 				ipha = NULL;
25696 			else
25697 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25698 		}
25699 	}
25700 
25701 	*iphap = ipha;
25702 	return (mp1);
25703 #undef rptr
25704 }
25705 
25706 /*
25707  * Finish the outbound IPsec processing for an IPv6 packet. This function
25708  * is called from ipsec_out_process() if the IPsec packet was processed
25709  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25710  * asynchronously.
25711  */
25712 void
25713 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25714     ire_t *ire_arg)
25715 {
25716 	in6_addr_t *v6dstp;
25717 	ire_t *ire;
25718 	mblk_t *mp;
25719 	ip6_t *ip6h1;
25720 	uint_t	ill_index;
25721 	ipsec_out_t *io;
25722 	boolean_t hwaccel;
25723 	uint32_t flags = IP6_NO_IPPOLICY;
25724 	int match_flags;
25725 	zoneid_t zoneid;
25726 	boolean_t ill_need_rele = B_FALSE;
25727 	boolean_t ire_need_rele = B_FALSE;
25728 	ip_stack_t	*ipst;
25729 
25730 	mp = ipsec_mp->b_cont;
25731 	ip6h1 = (ip6_t *)mp->b_rptr;
25732 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25733 	ASSERT(io->ipsec_out_ns != NULL);
25734 	ipst = io->ipsec_out_ns->netstack_ip;
25735 	ill_index = io->ipsec_out_ill_index;
25736 	if (io->ipsec_out_reachable) {
25737 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25738 	}
25739 	hwaccel = io->ipsec_out_accelerated;
25740 	zoneid = io->ipsec_out_zoneid;
25741 	ASSERT(zoneid != ALL_ZONES);
25742 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25743 	/* Multicast addresses should have non-zero ill_index. */
25744 	v6dstp = &ip6h->ip6_dst;
25745 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25746 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25747 
25748 	if (ill == NULL && ill_index != 0) {
25749 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25750 		/* Failure case frees things for us. */
25751 		if (ill == NULL)
25752 			return;
25753 
25754 		ill_need_rele = B_TRUE;
25755 	}
25756 	ASSERT(mp != NULL);
25757 
25758 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25759 		boolean_t unspec_src;
25760 		ipif_t	*ipif;
25761 
25762 		/*
25763 		 * Use the ill_index to get the right ill.
25764 		 */
25765 		unspec_src = io->ipsec_out_unspec_src;
25766 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25767 		if (ipif == NULL) {
25768 			if (ill_need_rele)
25769 				ill_refrele(ill);
25770 			freemsg(ipsec_mp);
25771 			return;
25772 		}
25773 
25774 		if (ire_arg != NULL) {
25775 			ire = ire_arg;
25776 		} else {
25777 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25778 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25779 			ire_need_rele = B_TRUE;
25780 		}
25781 		if (ire != NULL) {
25782 			ipif_refrele(ipif);
25783 			/*
25784 			 * XXX Do the multicast forwarding now, as the IPsec
25785 			 * processing has been done.
25786 			 */
25787 			goto send;
25788 		}
25789 
25790 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25791 		mp->b_prev = NULL;
25792 		mp->b_next = NULL;
25793 
25794 		/*
25795 		 * If the IPsec packet was processed asynchronously,
25796 		 * drop it now.
25797 		 */
25798 		if (q == NULL) {
25799 			if (ill_need_rele)
25800 				ill_refrele(ill);
25801 			freemsg(ipsec_mp);
25802 			return;
25803 		}
25804 
25805 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25806 		    unspec_src, zoneid);
25807 		ipif_refrele(ipif);
25808 	} else {
25809 		if (ire_arg != NULL) {
25810 			ire = ire_arg;
25811 		} else {
25812 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25813 			ire_need_rele = B_TRUE;
25814 		}
25815 		if (ire != NULL)
25816 			goto send;
25817 		/*
25818 		 * ire disappeared underneath.
25819 		 *
25820 		 * What we need to do here is the ip_newroute
25821 		 * logic to get the ire without doing the IPsec
25822 		 * processing. Follow the same old path. But this
25823 		 * time, ip_wput or ire_add_then_send will call us
25824 		 * directly as all the IPsec operations are done.
25825 		 */
25826 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25827 		mp->b_prev = NULL;
25828 		mp->b_next = NULL;
25829 
25830 		/*
25831 		 * If the IPsec packet was processed asynchronously,
25832 		 * drop it now.
25833 		 */
25834 		if (q == NULL) {
25835 			if (ill_need_rele)
25836 				ill_refrele(ill);
25837 			freemsg(ipsec_mp);
25838 			return;
25839 		}
25840 
25841 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25842 		    zoneid, ipst);
25843 	}
25844 	if (ill != NULL && ill_need_rele)
25845 		ill_refrele(ill);
25846 	return;
25847 send:
25848 	if (ill != NULL && ill_need_rele)
25849 		ill_refrele(ill);
25850 
25851 	/* Local delivery */
25852 	if (ire->ire_stq == NULL) {
25853 		ill_t	*out_ill;
25854 		ASSERT(q != NULL);
25855 
25856 		/* PFHooks: LOOPBACK_OUT */
25857 		out_ill = ire_to_ill(ire);
25858 
25859 		/*
25860 		 * DTrace this as ip:::send.  A blocked packet will fire the
25861 		 * send probe, but not the receive probe.
25862 		 */
25863 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25864 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25865 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25866 
25867 		DTRACE_PROBE4(ip6__loopback__out__start,
25868 		    ill_t *, NULL, ill_t *, out_ill,
25869 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25870 
25871 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25872 		    ipst->ips_ipv6firewall_loopback_out,
25873 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25874 
25875 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25876 
25877 		if (ipsec_mp != NULL) {
25878 			ip_wput_local_v6(RD(q), out_ill,
25879 			    ip6h, ipsec_mp, ire, 0, zoneid);
25880 		}
25881 		if (ire_need_rele)
25882 			ire_refrele(ire);
25883 		return;
25884 	}
25885 	/*
25886 	 * Everything is done. Send it out on the wire.
25887 	 * We force the insertion of a fragment header using the
25888 	 * IPH_FRAG_HDR flag in two cases:
25889 	 * - after reception of an ICMPv6 "packet too big" message
25890 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25891 	 * - for multirouted IPv6 packets, so that the receiver can
25892 	 *   discard duplicates according to their fragment identifier
25893 	 */
25894 	/* XXX fix flow control problems. */
25895 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25896 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25897 		if (hwaccel) {
25898 			/*
25899 			 * hardware acceleration does not handle these
25900 			 * "slow path" cases.
25901 			 */
25902 			/* IPsec KSTATS: should bump bean counter here. */
25903 			if (ire_need_rele)
25904 				ire_refrele(ire);
25905 			freemsg(ipsec_mp);
25906 			return;
25907 		}
25908 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25909 		    (mp->b_cont ? msgdsize(mp) :
25910 		    mp->b_wptr - (uchar_t *)ip6h)) {
25911 			/* IPsec KSTATS: should bump bean counter here. */
25912 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25913 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25914 			    msgdsize(mp)));
25915 			if (ire_need_rele)
25916 				ire_refrele(ire);
25917 			freemsg(ipsec_mp);
25918 			return;
25919 		}
25920 		ASSERT(mp->b_prev == NULL);
25921 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25922 		    ntohs(ip6h->ip6_plen) +
25923 		    IPV6_HDR_LEN, ire->ire_max_frag));
25924 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25925 		    ire->ire_max_frag);
25926 	} else {
25927 		UPDATE_OB_PKT_COUNT(ire);
25928 		ire->ire_last_used_time = lbolt;
25929 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25930 	}
25931 	if (ire_need_rele)
25932 		ire_refrele(ire);
25933 	freeb(ipsec_mp);
25934 }
25935 
25936 void
25937 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25938 {
25939 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25940 	da_ipsec_t *hada;	/* data attributes */
25941 	ill_t *ill = (ill_t *)q->q_ptr;
25942 
25943 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25944 
25945 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25946 		/* IPsec KSTATS: Bump lose counter here! */
25947 		freemsg(mp);
25948 		return;
25949 	}
25950 
25951 	/*
25952 	 * It's an IPsec packet that must be
25953 	 * accelerated by the Provider, and the
25954 	 * outbound ill is IPsec acceleration capable.
25955 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25956 	 * to the ill.
25957 	 * IPsec KSTATS: should bump packet counter here.
25958 	 */
25959 
25960 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25961 	if (hada_mp == NULL) {
25962 		/* IPsec KSTATS: should bump packet counter here. */
25963 		freemsg(mp);
25964 		return;
25965 	}
25966 
25967 	hada_mp->b_datap->db_type = M_CTL;
25968 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25969 	hada_mp->b_cont = mp;
25970 
25971 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25972 	bzero(hada, sizeof (da_ipsec_t));
25973 	hada->da_type = IPHADA_M_CTL;
25974 
25975 	putnext(q, hada_mp);
25976 }
25977 
25978 /*
25979  * Finish the outbound IPsec processing. This function is called from
25980  * ipsec_out_process() if the IPsec packet was processed
25981  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25982  * asynchronously.
25983  */
25984 void
25985 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25986     ire_t *ire_arg)
25987 {
25988 	uint32_t v_hlen_tos_len;
25989 	ipaddr_t	dst;
25990 	ipif_t	*ipif = NULL;
25991 	ire_t *ire;
25992 	ire_t *ire1 = NULL;
25993 	mblk_t *next_mp = NULL;
25994 	uint32_t max_frag;
25995 	boolean_t multirt_send = B_FALSE;
25996 	mblk_t *mp;
25997 	ipha_t *ipha1;
25998 	uint_t	ill_index;
25999 	ipsec_out_t *io;
26000 	int match_flags;
26001 	irb_t *irb = NULL;
26002 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26003 	zoneid_t zoneid;
26004 	ipxmit_state_t	pktxmit_state;
26005 	ip_stack_t	*ipst;
26006 
26007 #ifdef	_BIG_ENDIAN
26008 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26009 #else
26010 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26011 #endif
26012 
26013 	mp = ipsec_mp->b_cont;
26014 	ipha1 = (ipha_t *)mp->b_rptr;
26015 	ASSERT(mp != NULL);
26016 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26017 	dst = ipha->ipha_dst;
26018 
26019 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26020 	ill_index = io->ipsec_out_ill_index;
26021 	zoneid = io->ipsec_out_zoneid;
26022 	ASSERT(zoneid != ALL_ZONES);
26023 	ipst = io->ipsec_out_ns->netstack_ip;
26024 	ASSERT(io->ipsec_out_ns != NULL);
26025 
26026 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26027 	if (ill == NULL && ill_index != 0) {
26028 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
26029 		/* Failure case frees things for us. */
26030 		if (ill == NULL)
26031 			return;
26032 
26033 		ill_need_rele = B_TRUE;
26034 	}
26035 
26036 	if (CLASSD(dst)) {
26037 		boolean_t conn_dontroute;
26038 		/*
26039 		 * Use the ill_index to get the right ipif.
26040 		 */
26041 		conn_dontroute = io->ipsec_out_dontroute;
26042 		if (ill_index == 0)
26043 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26044 		else
26045 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26046 		if (ipif == NULL) {
26047 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26048 			    " multicast\n"));
26049 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26050 			freemsg(ipsec_mp);
26051 			goto done;
26052 		}
26053 		/*
26054 		 * ipha_src has already been intialized with the
26055 		 * value of the ipif in ip_wput. All we need now is
26056 		 * an ire to send this downstream.
26057 		 */
26058 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26059 		    msg_getlabel(mp), match_flags, ipst);
26060 		if (ire != NULL) {
26061 			ill_t *ill1;
26062 			/*
26063 			 * Do the multicast forwarding now, as the IPsec
26064 			 * processing has been done.
26065 			 */
26066 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26067 			    (ill1 = ire_to_ill(ire))) {
26068 				if (ip_mforward(ill1, ipha, mp)) {
26069 					freemsg(ipsec_mp);
26070 					ip1dbg(("ip_wput_ipsec_out: mforward "
26071 					    "failed\n"));
26072 					ire_refrele(ire);
26073 					goto done;
26074 				}
26075 			}
26076 			goto send;
26077 		}
26078 
26079 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26080 		mp->b_prev = NULL;
26081 		mp->b_next = NULL;
26082 
26083 		/*
26084 		 * If the IPsec packet was processed asynchronously,
26085 		 * drop it now.
26086 		 */
26087 		if (q == NULL) {
26088 			freemsg(ipsec_mp);
26089 			goto done;
26090 		}
26091 
26092 		/*
26093 		 * We may be using a wrong ipif to create the ire.
26094 		 * But it is okay as the source address is assigned
26095 		 * for the packet already. Next outbound packet would
26096 		 * create the IRE with the right IPIF in ip_wput.
26097 		 *
26098 		 * Also handle RTF_MULTIRT routes.
26099 		 */
26100 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26101 		    zoneid, &zero_info);
26102 	} else {
26103 		if (ire_arg != NULL) {
26104 			ire = ire_arg;
26105 			ire_need_rele = B_FALSE;
26106 		} else {
26107 			ire = ire_cache_lookup(dst, zoneid,
26108 			    msg_getlabel(mp), ipst);
26109 		}
26110 		if (ire != NULL) {
26111 			goto send;
26112 		}
26113 
26114 		/*
26115 		 * ire disappeared underneath.
26116 		 *
26117 		 * What we need to do here is the ip_newroute
26118 		 * logic to get the ire without doing the IPsec
26119 		 * processing. Follow the same old path. But this
26120 		 * time, ip_wput or ire_add_then_put will call us
26121 		 * directly as all the IPsec operations are done.
26122 		 */
26123 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26124 		mp->b_prev = NULL;
26125 		mp->b_next = NULL;
26126 
26127 		/*
26128 		 * If the IPsec packet was processed asynchronously,
26129 		 * drop it now.
26130 		 */
26131 		if (q == NULL) {
26132 			freemsg(ipsec_mp);
26133 			goto done;
26134 		}
26135 
26136 		/*
26137 		 * Since we're going through ip_newroute() again, we
26138 		 * need to make sure we don't:
26139 		 *
26140 		 *	1.) Trigger the ASSERT() with the ipha_ident
26141 		 *	    overloading.
26142 		 *	2.) Redo transport-layer checksumming, since we've
26143 		 *	    already done all that to get this far.
26144 		 *
26145 		 * The easiest way not do either of the above is to set
26146 		 * the ipha_ident field to IP_HDR_INCLUDED.
26147 		 */
26148 		ipha->ipha_ident = IP_HDR_INCLUDED;
26149 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26150 		    zoneid, ipst);
26151 	}
26152 	goto done;
26153 send:
26154 	if (ire->ire_stq == NULL) {
26155 		ill_t	*out_ill;
26156 		/*
26157 		 * Loopbacks go through ip_wput_local except for one case.
26158 		 * We come here if we generate a icmp_frag_needed message
26159 		 * after IPsec processing is over. When this function calls
26160 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26161 		 * icmp_frag_needed. The message generated comes back here
26162 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26163 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26164 		 * source address as it is usually set in ip_wput_ire. As
26165 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26166 		 * and we end up here. We can't enter ip_wput_ire once the
26167 		 * IPsec processing is over and hence we need to do it here.
26168 		 */
26169 		ASSERT(q != NULL);
26170 		UPDATE_OB_PKT_COUNT(ire);
26171 		ire->ire_last_used_time = lbolt;
26172 		if (ipha->ipha_src == 0)
26173 			ipha->ipha_src = ire->ire_src_addr;
26174 
26175 		/* PFHooks: LOOPBACK_OUT */
26176 		out_ill = ire_to_ill(ire);
26177 
26178 		/*
26179 		 * DTrace this as ip:::send.  A blocked packet will fire the
26180 		 * send probe, but not the receive probe.
26181 		 */
26182 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26183 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26184 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26185 
26186 		DTRACE_PROBE4(ip4__loopback__out__start,
26187 		    ill_t *, NULL, ill_t *, out_ill,
26188 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26189 
26190 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26191 		    ipst->ips_ipv4firewall_loopback_out,
26192 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26193 
26194 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26195 
26196 		if (ipsec_mp != NULL)
26197 			ip_wput_local(RD(q), out_ill,
26198 			    ipha, ipsec_mp, ire, 0, zoneid);
26199 		if (ire_need_rele)
26200 			ire_refrele(ire);
26201 		goto done;
26202 	}
26203 
26204 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26205 		/*
26206 		 * We are through with IPsec processing.
26207 		 * Fragment this and send it on the wire.
26208 		 */
26209 		if (io->ipsec_out_accelerated) {
26210 			/*
26211 			 * The packet has been accelerated but must
26212 			 * be fragmented. This should not happen
26213 			 * since AH and ESP must not accelerate
26214 			 * packets that need fragmentation, however
26215 			 * the configuration could have changed
26216 			 * since the AH or ESP processing.
26217 			 * Drop packet.
26218 			 * IPsec KSTATS: bump bean counter here.
26219 			 */
26220 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26221 			    "fragmented accelerated packet!\n"));
26222 			freemsg(ipsec_mp);
26223 		} else {
26224 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26225 			    zoneid, ipst, NULL);
26226 		}
26227 		if (ire_need_rele)
26228 			ire_refrele(ire);
26229 		goto done;
26230 	}
26231 
26232 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26233 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26234 	    (void *)ire->ire_ipif, (void *)ipif));
26235 
26236 	/*
26237 	 * Multiroute the secured packet.
26238 	 */
26239 	if (ire->ire_flags & RTF_MULTIRT) {
26240 		ire_t *first_ire;
26241 		irb = ire->ire_bucket;
26242 		ASSERT(irb != NULL);
26243 		/*
26244 		 * This ire has been looked up as the one that
26245 		 * goes through the given ipif;
26246 		 * make sure we do not omit any other multiroute ire
26247 		 * that may be present in the bucket before this one.
26248 		 */
26249 		IRB_REFHOLD(irb);
26250 		for (first_ire = irb->irb_ire;
26251 		    first_ire != NULL;
26252 		    first_ire = first_ire->ire_next) {
26253 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26254 			    (first_ire->ire_addr == ire->ire_addr) &&
26255 			    !(first_ire->ire_marks &
26256 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26257 				break;
26258 		}
26259 
26260 		if ((first_ire != NULL) && (first_ire != ire)) {
26261 			/*
26262 			 * Don't change the ire if the packet must
26263 			 * be fragmented if sent via this new one.
26264 			 */
26265 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26266 				IRE_REFHOLD(first_ire);
26267 				if (ire_need_rele)
26268 					ire_refrele(ire);
26269 				else
26270 					ire_need_rele = B_TRUE;
26271 				ire = first_ire;
26272 			}
26273 		}
26274 		IRB_REFRELE(irb);
26275 
26276 		multirt_send = B_TRUE;
26277 		max_frag = ire->ire_max_frag;
26278 	}
26279 
26280 	/*
26281 	 * In most cases, the emission loop below is entered only once.
26282 	 * Only in the case where the ire holds the RTF_MULTIRT
26283 	 * flag, we loop to process all RTF_MULTIRT ires in the
26284 	 * bucket, and send the packet through all crossed
26285 	 * RTF_MULTIRT routes.
26286 	 */
26287 	do {
26288 		if (multirt_send) {
26289 			/*
26290 			 * ire1 holds here the next ire to process in the
26291 			 * bucket. If multirouting is expected,
26292 			 * any non-RTF_MULTIRT ire that has the
26293 			 * right destination address is ignored.
26294 			 */
26295 			ASSERT(irb != NULL);
26296 			IRB_REFHOLD(irb);
26297 			for (ire1 = ire->ire_next;
26298 			    ire1 != NULL;
26299 			    ire1 = ire1->ire_next) {
26300 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26301 					continue;
26302 				if (ire1->ire_addr != ire->ire_addr)
26303 					continue;
26304 				if (ire1->ire_marks &
26305 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26306 					continue;
26307 				/* No loopback here */
26308 				if (ire1->ire_stq == NULL)
26309 					continue;
26310 				/*
26311 				 * Ensure we do not exceed the MTU
26312 				 * of the next route.
26313 				 */
26314 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26315 					ip_multirt_bad_mtu(ire1, max_frag);
26316 					continue;
26317 				}
26318 
26319 				IRE_REFHOLD(ire1);
26320 				break;
26321 			}
26322 			IRB_REFRELE(irb);
26323 			if (ire1 != NULL) {
26324 				/*
26325 				 * We are in a multiple send case, need to
26326 				 * make a copy of the packet.
26327 				 */
26328 				next_mp = copymsg(ipsec_mp);
26329 				if (next_mp == NULL) {
26330 					ire_refrele(ire1);
26331 					ire1 = NULL;
26332 				}
26333 			}
26334 		}
26335 		/*
26336 		 * Everything is done. Send it out on the wire
26337 		 *
26338 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26339 		 * either send it on the wire or, in the case of
26340 		 * HW acceleration, call ipsec_hw_putnext.
26341 		 */
26342 		if (ire->ire_nce &&
26343 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26344 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26345 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26346 			/*
26347 			 * If ire's link-layer is unresolved (this
26348 			 * would only happen if the incomplete ire
26349 			 * was added to cachetable via forwarding path)
26350 			 * don't bother going to ip_xmit_v4. Just drop the
26351 			 * packet.
26352 			 * There is a slight risk here, in that, if we
26353 			 * have the forwarding path create an incomplete
26354 			 * IRE, then until the IRE is completed, any
26355 			 * transmitted IPsec packets will be dropped
26356 			 * instead of being queued waiting for resolution.
26357 			 *
26358 			 * But the likelihood of a forwarding packet and a wput
26359 			 * packet sending to the same dst at the same time
26360 			 * and there not yet be an ARP entry for it is small.
26361 			 * Furthermore, if this actually happens, it might
26362 			 * be likely that wput would generate multiple
26363 			 * packets (and forwarding would also have a train
26364 			 * of packets) for that destination. If this is
26365 			 * the case, some of them would have been dropped
26366 			 * anyway, since ARP only queues a few packets while
26367 			 * waiting for resolution
26368 			 *
26369 			 * NOTE: We should really call ip_xmit_v4,
26370 			 * and let it queue the packet and send the
26371 			 * ARP query and have ARP come back thus:
26372 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26373 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26374 			 * hw accel work. But it's too complex to get
26375 			 * the IPsec hw  acceleration approach to fit
26376 			 * well with ip_xmit_v4 doing ARP without
26377 			 * doing IPsec simplification. For now, we just
26378 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26379 			 * that we can continue with the send on the next
26380 			 * attempt.
26381 			 *
26382 			 * XXX THis should be revisited, when
26383 			 * the IPsec/IP interaction is cleaned up
26384 			 */
26385 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26386 			    " - dropping packet\n"));
26387 			freemsg(ipsec_mp);
26388 			/*
26389 			 * Call ip_xmit_v4() to trigger ARP query
26390 			 * in case the nce_state is ND_INITIAL
26391 			 */
26392 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26393 			goto drop_pkt;
26394 		}
26395 
26396 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26397 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26398 		    mblk_t *, ipsec_mp);
26399 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26400 		    ipst->ips_ipv4firewall_physical_out, NULL,
26401 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26402 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26403 		if (ipsec_mp == NULL)
26404 			goto drop_pkt;
26405 
26406 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26407 		pktxmit_state = ip_xmit_v4(mp, ire,
26408 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26409 
26410 		if ((pktxmit_state ==  SEND_FAILED) ||
26411 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26412 
26413 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26414 drop_pkt:
26415 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26416 			    ipIfStatsOutDiscards);
26417 			if (ire_need_rele)
26418 				ire_refrele(ire);
26419 			if (ire1 != NULL) {
26420 				ire_refrele(ire1);
26421 				freemsg(next_mp);
26422 			}
26423 			goto done;
26424 		}
26425 
26426 		freeb(ipsec_mp);
26427 		if (ire_need_rele)
26428 			ire_refrele(ire);
26429 
26430 		if (ire1 != NULL) {
26431 			ire = ire1;
26432 			ire_need_rele = B_TRUE;
26433 			ASSERT(next_mp);
26434 			ipsec_mp = next_mp;
26435 			mp = ipsec_mp->b_cont;
26436 			ire1 = NULL;
26437 			next_mp = NULL;
26438 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26439 		} else {
26440 			multirt_send = B_FALSE;
26441 		}
26442 	} while (multirt_send);
26443 done:
26444 	if (ill != NULL && ill_need_rele)
26445 		ill_refrele(ill);
26446 	if (ipif != NULL)
26447 		ipif_refrele(ipif);
26448 }
26449 
26450 /*
26451  * Get the ill corresponding to the specified ire, and compare its
26452  * capabilities with the protocol and algorithms specified by the
26453  * the SA obtained from ipsec_out. If they match, annotate the
26454  * ipsec_out structure to indicate that the packet needs acceleration.
26455  *
26456  *
26457  * A packet is eligible for outbound hardware acceleration if the
26458  * following conditions are satisfied:
26459  *
26460  * 1. the packet will not be fragmented
26461  * 2. the provider supports the algorithm
26462  * 3. there is no pending control message being exchanged
26463  * 4. snoop is not attached
26464  * 5. the destination address is not a broadcast or multicast address.
26465  *
26466  * Rationale:
26467  *	- Hardware drivers do not support fragmentation with
26468  *	  the current interface.
26469  *	- snoop, multicast, and broadcast may result in exposure of
26470  *	  a cleartext datagram.
26471  * We check all five of these conditions here.
26472  *
26473  * XXX would like to nuke "ire_t *" parameter here; problem is that
26474  * IRE is only way to figure out if a v4 address is a broadcast and
26475  * thus ineligible for acceleration...
26476  */
26477 static void
26478 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26479 {
26480 	ipsec_out_t *io;
26481 	mblk_t *data_mp;
26482 	uint_t plen, overhead;
26483 	ip_stack_t	*ipst;
26484 	phyint_t	*phyint;
26485 
26486 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26487 		return;
26488 
26489 	if (ill == NULL)
26490 		return;
26491 	ipst = ill->ill_ipst;
26492 	phyint = ill->ill_phyint;
26493 
26494 	/*
26495 	 * Destination address is a broadcast or multicast.  Punt.
26496 	 */
26497 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26498 	    IRE_LOCAL)))
26499 		return;
26500 
26501 	data_mp = ipsec_mp->b_cont;
26502 
26503 	if (ill->ill_isv6) {
26504 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26505 
26506 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26507 			return;
26508 
26509 		plen = ip6h->ip6_plen;
26510 	} else {
26511 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26512 
26513 		if (CLASSD(ipha->ipha_dst))
26514 			return;
26515 
26516 		plen = ipha->ipha_length;
26517 	}
26518 	/*
26519 	 * Is there a pending DLPI control message being exchanged
26520 	 * between IP/IPsec and the DLS Provider? If there is, it
26521 	 * could be a SADB update, and the state of the DLS Provider
26522 	 * SADB might not be in sync with the SADB maintained by
26523 	 * IPsec. To avoid dropping packets or using the wrong keying
26524 	 * material, we do not accelerate this packet.
26525 	 */
26526 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26527 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26528 		    "ill_dlpi_pending! don't accelerate packet\n"));
26529 		return;
26530 	}
26531 
26532 	/*
26533 	 * Is the Provider in promiscous mode? If it does, we don't
26534 	 * accelerate the packet since it will bounce back up to the
26535 	 * listeners in the clear.
26536 	 */
26537 	if (phyint->phyint_flags & PHYI_PROMISC) {
26538 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26539 		    "ill in promiscous mode, don't accelerate packet\n"));
26540 		return;
26541 	}
26542 
26543 	/*
26544 	 * Will the packet require fragmentation?
26545 	 */
26546 
26547 	/*
26548 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26549 	 * as is used elsewhere.
26550 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26551 	 *	+ 2-byte trailer
26552 	 */
26553 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26554 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26555 
26556 	if ((plen + overhead) > ill->ill_max_mtu)
26557 		return;
26558 
26559 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26560 
26561 	/*
26562 	 * Can the ill accelerate this IPsec protocol and algorithm
26563 	 * specified by the SA?
26564 	 */
26565 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26566 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26567 		return;
26568 	}
26569 
26570 	/*
26571 	 * Tell AH or ESP that the outbound ill is capable of
26572 	 * accelerating this packet.
26573 	 */
26574 	io->ipsec_out_is_capab_ill = B_TRUE;
26575 }
26576 
26577 /*
26578  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26579  *
26580  * If this function returns B_TRUE, the requested SA's have been filled
26581  * into the ipsec_out_*_sa pointers.
26582  *
26583  * If the function returns B_FALSE, the packet has been "consumed", most
26584  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26585  *
26586  * The SA references created by the protocol-specific "select"
26587  * function will be released when the ipsec_mp is freed, thanks to the
26588  * ipsec_out_free destructor -- see spd.c.
26589  */
26590 static boolean_t
26591 ipsec_out_select_sa(mblk_t *ipsec_mp)
26592 {
26593 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26594 	ipsec_out_t *io;
26595 	ipsec_policy_t *pp;
26596 	ipsec_action_t *ap;
26597 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26598 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26599 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26600 
26601 	if (!io->ipsec_out_secure) {
26602 		/*
26603 		 * We came here by mistake.
26604 		 * Don't bother with ipsec processing
26605 		 * We should "discourage" this path in the future.
26606 		 */
26607 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26608 		return (B_FALSE);
26609 	}
26610 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26611 	ASSERT((io->ipsec_out_policy != NULL) ||
26612 	    (io->ipsec_out_act != NULL));
26613 
26614 	ASSERT(io->ipsec_out_failed == B_FALSE);
26615 
26616 	/*
26617 	 * IPsec processing has started.
26618 	 */
26619 	io->ipsec_out_proc_begin = B_TRUE;
26620 	ap = io->ipsec_out_act;
26621 	if (ap == NULL) {
26622 		pp = io->ipsec_out_policy;
26623 		ASSERT(pp != NULL);
26624 		ap = pp->ipsp_act;
26625 		ASSERT(ap != NULL);
26626 	}
26627 
26628 	/*
26629 	 * We have an action.  now, let's select SA's.
26630 	 * (In the future, we can cache this in the conn_t..)
26631 	 */
26632 	if (ap->ipa_want_esp) {
26633 		if (io->ipsec_out_esp_sa == NULL) {
26634 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26635 			    IPPROTO_ESP);
26636 		}
26637 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26638 	}
26639 
26640 	if (ap->ipa_want_ah) {
26641 		if (io->ipsec_out_ah_sa == NULL) {
26642 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26643 			    IPPROTO_AH);
26644 		}
26645 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26646 		/*
26647 		 * The ESP and AH processing order needs to be preserved
26648 		 * when both protocols are required (ESP should be applied
26649 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26650 		 * when both ESP and AH are required, and an AH ACQUIRE
26651 		 * is needed.
26652 		 */
26653 		if (ap->ipa_want_esp && need_ah_acquire)
26654 			need_esp_acquire = B_TRUE;
26655 	}
26656 
26657 	/*
26658 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26659 	 * Release SAs that got referenced, but will not be used until we
26660 	 * acquire _all_ of the SAs we need.
26661 	 */
26662 	if (need_ah_acquire || need_esp_acquire) {
26663 		if (io->ipsec_out_ah_sa != NULL) {
26664 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26665 			io->ipsec_out_ah_sa = NULL;
26666 		}
26667 		if (io->ipsec_out_esp_sa != NULL) {
26668 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26669 			io->ipsec_out_esp_sa = NULL;
26670 		}
26671 
26672 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26673 		return (B_FALSE);
26674 	}
26675 
26676 	return (B_TRUE);
26677 }
26678 
26679 /*
26680  * Process an IPSEC_OUT message and see what you can
26681  * do with it.
26682  * IPQoS Notes:
26683  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26684  * IPsec.
26685  * XXX would like to nuke ire_t.
26686  * XXX ill_index better be "real"
26687  */
26688 void
26689 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26690 {
26691 	ipsec_out_t *io;
26692 	ipsec_policy_t *pp;
26693 	ipsec_action_t *ap;
26694 	ipha_t *ipha;
26695 	ip6_t *ip6h;
26696 	mblk_t *mp;
26697 	ill_t *ill;
26698 	zoneid_t zoneid;
26699 	ipsec_status_t ipsec_rc;
26700 	boolean_t ill_need_rele = B_FALSE;
26701 	ip_stack_t	*ipst;
26702 	ipsec_stack_t	*ipss;
26703 
26704 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26705 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26706 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26707 	ipst = io->ipsec_out_ns->netstack_ip;
26708 	mp = ipsec_mp->b_cont;
26709 
26710 	/*
26711 	 * Initiate IPPF processing. We do it here to account for packets
26712 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26713 	 * We can check for ipsec_out_proc_begin even for such packets, as
26714 	 * they will always be false (asserted below).
26715 	 */
26716 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26717 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26718 		    io->ipsec_out_ill_index : ill_index);
26719 		if (mp == NULL) {
26720 			ip2dbg(("ipsec_out_process: packet dropped "\
26721 			    "during IPPF processing\n"));
26722 			freeb(ipsec_mp);
26723 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26724 			return;
26725 		}
26726 	}
26727 
26728 	if (!io->ipsec_out_secure) {
26729 		/*
26730 		 * We came here by mistake.
26731 		 * Don't bother with ipsec processing
26732 		 * Should "discourage" this path in the future.
26733 		 */
26734 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26735 		goto done;
26736 	}
26737 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26738 	ASSERT((io->ipsec_out_policy != NULL) ||
26739 	    (io->ipsec_out_act != NULL));
26740 	ASSERT(io->ipsec_out_failed == B_FALSE);
26741 
26742 	ipss = ipst->ips_netstack->netstack_ipsec;
26743 	if (!ipsec_loaded(ipss)) {
26744 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26745 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26746 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26747 		} else {
26748 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26749 		}
26750 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26751 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26752 		    &ipss->ipsec_dropper);
26753 		return;
26754 	}
26755 
26756 	/*
26757 	 * IPsec processing has started.
26758 	 */
26759 	io->ipsec_out_proc_begin = B_TRUE;
26760 	ap = io->ipsec_out_act;
26761 	if (ap == NULL) {
26762 		pp = io->ipsec_out_policy;
26763 		ASSERT(pp != NULL);
26764 		ap = pp->ipsp_act;
26765 		ASSERT(ap != NULL);
26766 	}
26767 
26768 	/*
26769 	 * Save the outbound ill index. When the packet comes back
26770 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26771 	 * before sending it the accelerated packet.
26772 	 */
26773 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26774 		ill = ire_to_ill(ire);
26775 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26776 	}
26777 
26778 	/*
26779 	 * The order of processing is first insert a IP header if needed.
26780 	 * Then insert the ESP header and then the AH header.
26781 	 */
26782 	if ((io->ipsec_out_se_done == B_FALSE) &&
26783 	    (ap->ipa_want_se)) {
26784 		/*
26785 		 * First get the outer IP header before sending
26786 		 * it to ESP.
26787 		 */
26788 		ipha_t *oipha, *iipha;
26789 		mblk_t *outer_mp, *inner_mp;
26790 
26791 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26792 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26793 			    "ipsec_out_process: "
26794 			    "Self-Encapsulation failed: Out of memory\n");
26795 			freemsg(ipsec_mp);
26796 			if (ill != NULL) {
26797 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26798 			} else {
26799 				BUMP_MIB(&ipst->ips_ip_mib,
26800 				    ipIfStatsOutDiscards);
26801 			}
26802 			return;
26803 		}
26804 		inner_mp = ipsec_mp->b_cont;
26805 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26806 		oipha = (ipha_t *)outer_mp->b_rptr;
26807 		iipha = (ipha_t *)inner_mp->b_rptr;
26808 		*oipha = *iipha;
26809 		outer_mp->b_wptr += sizeof (ipha_t);
26810 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26811 		    sizeof (ipha_t));
26812 		oipha->ipha_protocol = IPPROTO_ENCAP;
26813 		oipha->ipha_version_and_hdr_length =
26814 		    IP_SIMPLE_HDR_VERSION;
26815 		oipha->ipha_hdr_checksum = 0;
26816 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26817 		outer_mp->b_cont = inner_mp;
26818 		ipsec_mp->b_cont = outer_mp;
26819 
26820 		io->ipsec_out_se_done = B_TRUE;
26821 		io->ipsec_out_tunnel = B_TRUE;
26822 	}
26823 
26824 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26825 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26826 	    !ipsec_out_select_sa(ipsec_mp))
26827 		return;
26828 
26829 	/*
26830 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26831 	 * to do the heavy lifting.
26832 	 */
26833 	zoneid = io->ipsec_out_zoneid;
26834 	ASSERT(zoneid != ALL_ZONES);
26835 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26836 		ASSERT(io->ipsec_out_esp_sa != NULL);
26837 		io->ipsec_out_esp_done = B_TRUE;
26838 		/*
26839 		 * Note that since hw accel can only apply one transform,
26840 		 * not two, we skip hw accel for ESP if we also have AH
26841 		 * This is an design limitation of the interface
26842 		 * which should be revisited.
26843 		 */
26844 		ASSERT(ire != NULL);
26845 		if (io->ipsec_out_ah_sa == NULL) {
26846 			ill = (ill_t *)ire->ire_stq->q_ptr;
26847 			ipsec_out_is_accelerated(ipsec_mp,
26848 			    io->ipsec_out_esp_sa, ill, ire);
26849 		}
26850 
26851 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26852 		switch (ipsec_rc) {
26853 		case IPSEC_STATUS_SUCCESS:
26854 			break;
26855 		case IPSEC_STATUS_FAILED:
26856 			if (ill != NULL) {
26857 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26858 			} else {
26859 				BUMP_MIB(&ipst->ips_ip_mib,
26860 				    ipIfStatsOutDiscards);
26861 			}
26862 			/* FALLTHRU */
26863 		case IPSEC_STATUS_PENDING:
26864 			return;
26865 		}
26866 	}
26867 
26868 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26869 		ASSERT(io->ipsec_out_ah_sa != NULL);
26870 		io->ipsec_out_ah_done = B_TRUE;
26871 		if (ire == NULL) {
26872 			int idx = io->ipsec_out_capab_ill_index;
26873 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26874 			    NULL, NULL, NULL, NULL, ipst);
26875 			ill_need_rele = B_TRUE;
26876 		} else {
26877 			ill = (ill_t *)ire->ire_stq->q_ptr;
26878 		}
26879 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26880 		    ire);
26881 
26882 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26883 		switch (ipsec_rc) {
26884 		case IPSEC_STATUS_SUCCESS:
26885 			break;
26886 		case IPSEC_STATUS_FAILED:
26887 			if (ill != NULL) {
26888 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26889 			} else {
26890 				BUMP_MIB(&ipst->ips_ip_mib,
26891 				    ipIfStatsOutDiscards);
26892 			}
26893 			/* FALLTHRU */
26894 		case IPSEC_STATUS_PENDING:
26895 			if (ill != NULL && ill_need_rele)
26896 				ill_refrele(ill);
26897 			return;
26898 		}
26899 	}
26900 	/*
26901 	 * We are done with IPsec processing. Send it over the wire.
26902 	 */
26903 done:
26904 	mp = ipsec_mp->b_cont;
26905 	ipha = (ipha_t *)mp->b_rptr;
26906 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26907 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26908 		    ire);
26909 	} else {
26910 		ip6h = (ip6_t *)ipha;
26911 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26912 		    ire);
26913 	}
26914 	if (ill != NULL && ill_need_rele)
26915 		ill_refrele(ill);
26916 }
26917 
26918 /* ARGSUSED */
26919 void
26920 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26921 {
26922 	opt_restart_t	*or;
26923 	int	err;
26924 	conn_t	*connp;
26925 	cred_t	*cr;
26926 
26927 	ASSERT(CONN_Q(q));
26928 	connp = Q_TO_CONN(q);
26929 
26930 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26931 	or = (opt_restart_t *)first_mp->b_rptr;
26932 	/*
26933 	 * We checked for a db_credp the first time svr4_optcom_req
26934 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26935 	 */
26936 	cr = msg_getcred(first_mp, NULL);
26937 	ASSERT(cr != NULL);
26938 
26939 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26940 		err = svr4_optcom_req(q, first_mp, cr,
26941 		    &ip_opt_obj, B_FALSE);
26942 	} else {
26943 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26944 		err = tpi_optcom_req(q, first_mp, cr,
26945 		    &ip_opt_obj, B_FALSE);
26946 	}
26947 	if (err != EINPROGRESS) {
26948 		/* operation is done */
26949 		CONN_OPER_PENDING_DONE(connp);
26950 	}
26951 }
26952 
26953 /*
26954  * ioctls that go through a down/up sequence may need to wait for the down
26955  * to complete. This involves waiting for the ire and ipif refcnts to go down
26956  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26957  */
26958 /* ARGSUSED */
26959 void
26960 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26961 {
26962 	struct iocblk *iocp;
26963 	mblk_t *mp1;
26964 	ip_ioctl_cmd_t *ipip;
26965 	int err;
26966 	sin_t	*sin;
26967 	struct lifreq *lifr;
26968 	struct ifreq *ifr;
26969 
26970 	iocp = (struct iocblk *)mp->b_rptr;
26971 	ASSERT(ipsq != NULL);
26972 	/* Existence of mp1 verified in ip_wput_nondata */
26973 	mp1 = mp->b_cont->b_cont;
26974 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26975 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26976 		/*
26977 		 * Special case where ipx_current_ipif is not set:
26978 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26979 		 * We are here as were not able to complete the operation in
26980 		 * ipif_set_values because we could not become exclusive on
26981 		 * the new ipsq.
26982 		 */
26983 		ill_t *ill = q->q_ptr;
26984 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26985 	}
26986 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26987 
26988 	if (ipip->ipi_cmd_type == IF_CMD) {
26989 		/* This a old style SIOC[GS]IF* command */
26990 		ifr = (struct ifreq *)mp1->b_rptr;
26991 		sin = (sin_t *)&ifr->ifr_addr;
26992 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26993 		/* This a new style SIOC[GS]LIF* command */
26994 		lifr = (struct lifreq *)mp1->b_rptr;
26995 		sin = (sin_t *)&lifr->lifr_addr;
26996 	} else {
26997 		sin = NULL;
26998 	}
26999 
27000 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
27001 	    q, mp, ipip, mp1->b_rptr);
27002 
27003 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27004 }
27005 
27006 /*
27007  * ioctl processing
27008  *
27009  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27010  * the ioctl command in the ioctl tables, determines the copyin data size
27011  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27012  *
27013  * ioctl processing then continues when the M_IOCDATA makes its way down to
27014  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27015  * associated 'conn' is refheld till the end of the ioctl and the general
27016  * ioctl processing function ip_process_ioctl() is called to extract the
27017  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27018  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27019  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27020  * is used to extract the ioctl's arguments.
27021  *
27022  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27023  * so goes thru the serialization primitive ipsq_try_enter. Then the
27024  * appropriate function to handle the ioctl is called based on the entry in
27025  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27026  * which also refreleases the 'conn' that was refheld at the start of the
27027  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27028  *
27029  * Many exclusive ioctls go thru an internal down up sequence as part of
27030  * the operation. For example an attempt to change the IP address of an
27031  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27032  * does all the cleanup such as deleting all ires that use this address.
27033  * Then we need to wait till all references to the interface go away.
27034  */
27035 void
27036 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27037 {
27038 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27039 	ip_ioctl_cmd_t *ipip = arg;
27040 	ip_extract_func_t *extract_funcp;
27041 	cmd_info_t ci;
27042 	int err;
27043 	boolean_t entered_ipsq = B_FALSE;
27044 
27045 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27046 
27047 	if (ipip == NULL)
27048 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27049 
27050 	/*
27051 	 * SIOCLIFADDIF needs to go thru a special path since the
27052 	 * ill may not exist yet. This happens in the case of lo0
27053 	 * which is created using this ioctl.
27054 	 */
27055 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27056 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27057 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27058 		return;
27059 	}
27060 
27061 	ci.ci_ipif = NULL;
27062 	if (ipip->ipi_cmd_type == MISC_CMD) {
27063 		/*
27064 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27065 		 */
27066 		if (ipip->ipi_cmd == IF_UNITSEL) {
27067 			/* ioctl comes down the ill */
27068 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27069 			ipif_refhold(ci.ci_ipif);
27070 		}
27071 		err = 0;
27072 		ci.ci_sin = NULL;
27073 		ci.ci_sin6 = NULL;
27074 		ci.ci_lifr = NULL;
27075 	} else {
27076 		switch (ipip->ipi_cmd_type) {
27077 		case IF_CMD:
27078 		case LIF_CMD:
27079 			extract_funcp = ip_extract_lifreq;
27080 			break;
27081 
27082 		case ARP_CMD:
27083 		case XARP_CMD:
27084 			extract_funcp = ip_extract_arpreq;
27085 			break;
27086 
27087 		case TUN_CMD:
27088 			extract_funcp = ip_extract_tunreq;
27089 			break;
27090 
27091 		case MSFILT_CMD:
27092 			extract_funcp = ip_extract_msfilter;
27093 			break;
27094 
27095 		default:
27096 			ASSERT(0);
27097 		}
27098 
27099 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27100 		if (err != 0) {
27101 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27102 			return;
27103 		}
27104 
27105 		/*
27106 		 * All of the extraction functions return a refheld ipif.
27107 		 */
27108 		ASSERT(ci.ci_ipif != NULL);
27109 	}
27110 
27111 	if (!(ipip->ipi_flags & IPI_WR)) {
27112 		/*
27113 		 * A return value of EINPROGRESS means the ioctl is
27114 		 * either queued and waiting for some reason or has
27115 		 * already completed.
27116 		 */
27117 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27118 		    ci.ci_lifr);
27119 		if (ci.ci_ipif != NULL)
27120 			ipif_refrele(ci.ci_ipif);
27121 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27122 		return;
27123 	}
27124 
27125 	ASSERT(ci.ci_ipif != NULL);
27126 
27127 	/*
27128 	 * If ipsq is non-NULL, we are already being called exclusively.
27129 	 */
27130 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27131 	if (ipsq == NULL) {
27132 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27133 		    NEW_OP, B_TRUE);
27134 		if (ipsq == NULL) {
27135 			ipif_refrele(ci.ci_ipif);
27136 			return;
27137 		}
27138 		entered_ipsq = B_TRUE;
27139 	}
27140 
27141 	/*
27142 	 * Release the ipif so that ipif_down and friends that wait for
27143 	 * references to go away are not misled about the current ipif_refcnt
27144 	 * values. We are writer so we can access the ipif even after releasing
27145 	 * the ipif.
27146 	 */
27147 	ipif_refrele(ci.ci_ipif);
27148 
27149 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27150 
27151 	/*
27152 	 * A return value of EINPROGRESS means the ioctl is
27153 	 * either queued and waiting for some reason or has
27154 	 * already completed.
27155 	 */
27156 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27157 
27158 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27159 
27160 	if (entered_ipsq)
27161 		ipsq_exit(ipsq);
27162 }
27163 
27164 /*
27165  * Complete the ioctl. Typically ioctls use the mi package and need to
27166  * do mi_copyout/mi_copy_done.
27167  */
27168 void
27169 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27170 {
27171 	conn_t	*connp = NULL;
27172 
27173 	if (err == EINPROGRESS)
27174 		return;
27175 
27176 	if (CONN_Q(q)) {
27177 		connp = Q_TO_CONN(q);
27178 		ASSERT(connp->conn_ref >= 2);
27179 	}
27180 
27181 	switch (mode) {
27182 	case COPYOUT:
27183 		if (err == 0)
27184 			mi_copyout(q, mp);
27185 		else
27186 			mi_copy_done(q, mp, err);
27187 		break;
27188 
27189 	case NO_COPYOUT:
27190 		mi_copy_done(q, mp, err);
27191 		break;
27192 
27193 	default:
27194 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27195 		break;
27196 	}
27197 
27198 	/*
27199 	 * The refhold placed at the start of the ioctl is released here.
27200 	 */
27201 	if (connp != NULL)
27202 		CONN_OPER_PENDING_DONE(connp);
27203 
27204 	if (ipsq != NULL)
27205 		ipsq_current_finish(ipsq);
27206 }
27207 
27208 /* Called from ip_wput for all non data messages */
27209 /* ARGSUSED */
27210 void
27211 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27212 {
27213 	mblk_t		*mp1;
27214 	ire_t		*ire, *fake_ire;
27215 	ill_t		*ill;
27216 	struct iocblk	*iocp;
27217 	ip_ioctl_cmd_t	*ipip;
27218 	cred_t		*cr;
27219 	conn_t		*connp;
27220 	int		err;
27221 	nce_t		*nce;
27222 	ipif_t		*ipif;
27223 	ip_stack_t	*ipst;
27224 	char		*proto_str;
27225 
27226 	if (CONN_Q(q)) {
27227 		connp = Q_TO_CONN(q);
27228 		ipst = connp->conn_netstack->netstack_ip;
27229 	} else {
27230 		connp = NULL;
27231 		ipst = ILLQ_TO_IPST(q);
27232 	}
27233 
27234 	switch (DB_TYPE(mp)) {
27235 	case M_IOCTL:
27236 		/*
27237 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27238 		 * will arrange to copy in associated control structures.
27239 		 */
27240 		ip_sioctl_copyin_setup(q, mp);
27241 		return;
27242 	case M_IOCDATA:
27243 		/*
27244 		 * Ensure that this is associated with one of our trans-
27245 		 * parent ioctls.  If it's not ours, discard it if we're
27246 		 * running as a driver, or pass it on if we're a module.
27247 		 */
27248 		iocp = (struct iocblk *)mp->b_rptr;
27249 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27250 		if (ipip == NULL) {
27251 			if (q->q_next == NULL) {
27252 				goto nak;
27253 			} else {
27254 				putnext(q, mp);
27255 			}
27256 			return;
27257 		}
27258 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27259 			/*
27260 			 * the ioctl is one we recognise, but is not
27261 			 * consumed by IP as a module, pass M_IOCDATA
27262 			 * for processing downstream, but only for
27263 			 * common Streams ioctls.
27264 			 */
27265 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27266 				putnext(q, mp);
27267 				return;
27268 			} else {
27269 				goto nak;
27270 			}
27271 		}
27272 
27273 		/* IOCTL continuation following copyin or copyout. */
27274 		if (mi_copy_state(q, mp, NULL) == -1) {
27275 			/*
27276 			 * The copy operation failed.  mi_copy_state already
27277 			 * cleaned up, so we're out of here.
27278 			 */
27279 			return;
27280 		}
27281 		/*
27282 		 * If we just completed a copy in, we become writer and
27283 		 * continue processing in ip_sioctl_copyin_done.  If it
27284 		 * was a copy out, we call mi_copyout again.  If there is
27285 		 * nothing more to copy out, it will complete the IOCTL.
27286 		 */
27287 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27288 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27289 				mi_copy_done(q, mp, EPROTO);
27290 				return;
27291 			}
27292 			/*
27293 			 * Check for cases that need more copying.  A return
27294 			 * value of 0 means a second copyin has been started,
27295 			 * so we return; a return value of 1 means no more
27296 			 * copying is needed, so we continue.
27297 			 */
27298 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27299 			    MI_COPY_COUNT(mp) == 1) {
27300 				if (ip_copyin_msfilter(q, mp) == 0)
27301 					return;
27302 			}
27303 			/*
27304 			 * Refhold the conn, till the ioctl completes. This is
27305 			 * needed in case the ioctl ends up in the pending mp
27306 			 * list. Every mp in the ill_pending_mp list and
27307 			 * the ipx_pending_mp must have a refhold on the conn
27308 			 * to resume processing. The refhold is released when
27309 			 * the ioctl completes. (normally or abnormally)
27310 			 * In all cases ip_ioctl_finish is called to finish
27311 			 * the ioctl.
27312 			 */
27313 			if (connp != NULL) {
27314 				/* This is not a reentry */
27315 				ASSERT(ipsq == NULL);
27316 				CONN_INC_REF(connp);
27317 			} else {
27318 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27319 					mi_copy_done(q, mp, EINVAL);
27320 					return;
27321 				}
27322 			}
27323 
27324 			ip_process_ioctl(ipsq, q, mp, ipip);
27325 
27326 		} else {
27327 			mi_copyout(q, mp);
27328 		}
27329 		return;
27330 nak:
27331 		iocp->ioc_error = EINVAL;
27332 		mp->b_datap->db_type = M_IOCNAK;
27333 		iocp->ioc_count = 0;
27334 		qreply(q, mp);
27335 		return;
27336 
27337 	case M_IOCNAK:
27338 		/*
27339 		 * The only way we could get here is if a resolver didn't like
27340 		 * an IOCTL we sent it.	 This shouldn't happen.
27341 		 */
27342 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27343 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27344 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27345 		freemsg(mp);
27346 		return;
27347 	case M_IOCACK:
27348 		/* /dev/ip shouldn't see this */
27349 		if (CONN_Q(q))
27350 			goto nak;
27351 
27352 		/*
27353 		 * Finish socket ioctls passed through to ARP.  We use the
27354 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27355 		 * we need to become writer before calling ip_sioctl_iocack().
27356 		 * Note that qwriter_ip() will release the refhold, and that a
27357 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27358 		 * ill stream.
27359 		 */
27360 		iocp = (struct iocblk *)mp->b_rptr;
27361 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27362 			ip_sioctl_iocack(NULL, q, mp, NULL);
27363 			return;
27364 		}
27365 
27366 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27367 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27368 		ill = q->q_ptr;
27369 		ill_refhold(ill);
27370 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27371 		return;
27372 	case M_FLUSH:
27373 		if (*mp->b_rptr & FLUSHW)
27374 			flushq(q, FLUSHALL);
27375 		if (q->q_next) {
27376 			putnext(q, mp);
27377 			return;
27378 		}
27379 		if (*mp->b_rptr & FLUSHR) {
27380 			*mp->b_rptr &= ~FLUSHW;
27381 			qreply(q, mp);
27382 			return;
27383 		}
27384 		freemsg(mp);
27385 		return;
27386 	case IRE_DB_REQ_TYPE:
27387 		if (connp == NULL) {
27388 			proto_str = "IRE_DB_REQ_TYPE";
27389 			goto protonak;
27390 		}
27391 		/* An Upper Level Protocol wants a copy of an IRE. */
27392 		ip_ire_req(q, mp);
27393 		return;
27394 	case M_CTL:
27395 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27396 			break;
27397 
27398 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27399 		    TUN_HELLO) {
27400 			ASSERT(connp != NULL);
27401 			connp->conn_flags |= IPCL_IPTUN;
27402 			freeb(mp);
27403 			return;
27404 		}
27405 
27406 		/* M_CTL messages are used by ARP to tell us things. */
27407 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27408 			break;
27409 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27410 		case AR_ENTRY_SQUERY:
27411 			putnext(q, mp);
27412 			return;
27413 		case AR_CLIENT_NOTIFY:
27414 			ip_arp_news(q, mp);
27415 			return;
27416 		case AR_DLPIOP_DONE:
27417 			ASSERT(q->q_next != NULL);
27418 			ill = (ill_t *)q->q_ptr;
27419 			/* qwriter_ip releases the refhold */
27420 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27421 			ill_refhold(ill);
27422 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27423 			return;
27424 		case AR_ARP_CLOSING:
27425 			/*
27426 			 * ARP (above us) is closing. If no ARP bringup is
27427 			 * currently pending, ack the message so that ARP
27428 			 * can complete its close. Also mark ill_arp_closing
27429 			 * so that new ARP bringups will fail. If any
27430 			 * ARP bringup is currently in progress, we will
27431 			 * ack this when the current ARP bringup completes.
27432 			 */
27433 			ASSERT(q->q_next != NULL);
27434 			ill = (ill_t *)q->q_ptr;
27435 			mutex_enter(&ill->ill_lock);
27436 			ill->ill_arp_closing = 1;
27437 			if (!ill->ill_arp_bringup_pending) {
27438 				mutex_exit(&ill->ill_lock);
27439 				qreply(q, mp);
27440 			} else {
27441 				mutex_exit(&ill->ill_lock);
27442 				freemsg(mp);
27443 			}
27444 			return;
27445 		case AR_ARP_EXTEND:
27446 			/*
27447 			 * The ARP module above us is capable of duplicate
27448 			 * address detection.  Old ATM drivers will not send
27449 			 * this message.
27450 			 */
27451 			ASSERT(q->q_next != NULL);
27452 			ill = (ill_t *)q->q_ptr;
27453 			ill->ill_arp_extend = B_TRUE;
27454 			freemsg(mp);
27455 			return;
27456 		default:
27457 			break;
27458 		}
27459 		break;
27460 	case M_PROTO:
27461 	case M_PCPROTO:
27462 		/*
27463 		 * The only PROTO messages we expect are copies of option
27464 		 * negotiation acknowledgements, AH and ESP bind requests
27465 		 * are also expected.
27466 		 */
27467 		switch (((union T_primitives *)mp->b_rptr)->type) {
27468 		case O_T_BIND_REQ:
27469 		case T_BIND_REQ: {
27470 			/* Request can get queued in bind */
27471 			if (connp == NULL) {
27472 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27473 				goto protonak;
27474 			}
27475 			/*
27476 			 * The transports except SCTP call ip_bind_{v4,v6}()
27477 			 * directly instead of a a putnext. SCTP doesn't
27478 			 * generate any T_BIND_REQ since it has its own
27479 			 * fanout data structures. However, ESP and AH
27480 			 * come in for regular binds; all other cases are
27481 			 * bind retries.
27482 			 */
27483 			ASSERT(!IPCL_IS_SCTP(connp));
27484 
27485 			/* Don't increment refcnt if this is a re-entry */
27486 			if (ipsq == NULL)
27487 				CONN_INC_REF(connp);
27488 
27489 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27490 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27491 			ASSERT(mp != NULL);
27492 
27493 			ASSERT(!IPCL_IS_TCP(connp));
27494 			ASSERT(!IPCL_IS_UDP(connp));
27495 			ASSERT(!IPCL_IS_RAWIP(connp));
27496 
27497 			/* The case of AH and ESP */
27498 			qreply(q, mp);
27499 			CONN_OPER_PENDING_DONE(connp);
27500 			return;
27501 		}
27502 		case T_SVR4_OPTMGMT_REQ:
27503 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27504 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27505 
27506 			if (connp == NULL) {
27507 				proto_str = "T_SVR4_OPTMGMT_REQ";
27508 				goto protonak;
27509 			}
27510 
27511 			/*
27512 			 * All Solaris components should pass a db_credp
27513 			 * for this TPI message, hence we ASSERT.
27514 			 * But in case there is some other M_PROTO that looks
27515 			 * like a TPI message sent by some other kernel
27516 			 * component, we check and return an error.
27517 			 */
27518 			cr = msg_getcred(mp, NULL);
27519 			ASSERT(cr != NULL);
27520 			if (cr == NULL) {
27521 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27522 				if (mp != NULL)
27523 					qreply(q, mp);
27524 				return;
27525 			}
27526 
27527 			if (!snmpcom_req(q, mp, ip_snmp_set,
27528 			    ip_snmp_get, cr)) {
27529 				/*
27530 				 * Call svr4_optcom_req so that it can
27531 				 * generate the ack. We don't come here
27532 				 * if this operation is being restarted.
27533 				 * ip_restart_optmgmt will drop the conn ref.
27534 				 * In the case of ipsec option after the ipsec
27535 				 * load is complete conn_restart_ipsec_waiter
27536 				 * drops the conn ref.
27537 				 */
27538 				ASSERT(ipsq == NULL);
27539 				CONN_INC_REF(connp);
27540 				if (ip_check_for_ipsec_opt(q, mp))
27541 					return;
27542 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27543 				    B_FALSE);
27544 				if (err != EINPROGRESS) {
27545 					/* Operation is done */
27546 					CONN_OPER_PENDING_DONE(connp);
27547 				}
27548 			}
27549 			return;
27550 		case T_OPTMGMT_REQ:
27551 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27552 			/*
27553 			 * Note: No snmpcom_req support through new
27554 			 * T_OPTMGMT_REQ.
27555 			 * Call tpi_optcom_req so that it can
27556 			 * generate the ack.
27557 			 */
27558 			if (connp == NULL) {
27559 				proto_str = "T_OPTMGMT_REQ";
27560 				goto protonak;
27561 			}
27562 
27563 			/*
27564 			 * All Solaris components should pass a db_credp
27565 			 * for this TPI message, hence we ASSERT.
27566 			 * But in case there is some other M_PROTO that looks
27567 			 * like a TPI message sent by some other kernel
27568 			 * component, we check and return an error.
27569 			 */
27570 			cr = msg_getcred(mp, NULL);
27571 			ASSERT(cr != NULL);
27572 			if (cr == NULL) {
27573 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27574 				if (mp != NULL)
27575 					qreply(q, mp);
27576 				return;
27577 			}
27578 			ASSERT(ipsq == NULL);
27579 			/*
27580 			 * We don't come here for restart. ip_restart_optmgmt
27581 			 * will drop the conn ref. In the case of ipsec option
27582 			 * after the ipsec load is complete
27583 			 * conn_restart_ipsec_waiter drops the conn ref.
27584 			 */
27585 			CONN_INC_REF(connp);
27586 			if (ip_check_for_ipsec_opt(q, mp))
27587 				return;
27588 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27589 			if (err != EINPROGRESS) {
27590 				/* Operation is done */
27591 				CONN_OPER_PENDING_DONE(connp);
27592 			}
27593 			return;
27594 		case T_UNBIND_REQ:
27595 			if (connp == NULL) {
27596 				proto_str = "T_UNBIND_REQ";
27597 				goto protonak;
27598 			}
27599 			ip_unbind(Q_TO_CONN(q));
27600 			mp = mi_tpi_ok_ack_alloc(mp);
27601 			qreply(q, mp);
27602 			return;
27603 		default:
27604 			/*
27605 			 * Have to drop any DLPI messages coming down from
27606 			 * arp (such as an info_req which would cause ip
27607 			 * to receive an extra info_ack if it was passed
27608 			 * through.
27609 			 */
27610 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27611 			    (int)*(uint_t *)mp->b_rptr));
27612 			freemsg(mp);
27613 			return;
27614 		}
27615 		/* NOTREACHED */
27616 	case IRE_DB_TYPE: {
27617 		nce_t		*nce;
27618 		ill_t		*ill;
27619 		in6_addr_t	gw_addr_v6;
27620 
27621 		/*
27622 		 * This is a response back from a resolver.  It
27623 		 * consists of a message chain containing:
27624 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27625 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27626 		 * The LL_HDR_MBLK is the DLPI header to use to get
27627 		 * the attached packet, and subsequent ones for the
27628 		 * same destination, transmitted.
27629 		 */
27630 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27631 			break;
27632 		/*
27633 		 * First, check to make sure the resolution succeeded.
27634 		 * If it failed, the second mblk will be empty.
27635 		 * If it is, free the chain, dropping the packet.
27636 		 * (We must ire_delete the ire; that frees the ire mblk)
27637 		 * We're doing this now to support PVCs for ATM; it's
27638 		 * a partial xresolv implementation. When we fully implement
27639 		 * xresolv interfaces, instead of freeing everything here
27640 		 * we'll initiate neighbor discovery.
27641 		 *
27642 		 * For v4 (ARP and other external resolvers) the resolver
27643 		 * frees the message, so no check is needed. This check
27644 		 * is required, though, for a full xresolve implementation.
27645 		 * Including this code here now both shows how external
27646 		 * resolvers can NACK a resolution request using an
27647 		 * existing design that has no specific provisions for NACKs,
27648 		 * and also takes into account that the current non-ARP
27649 		 * external resolver has been coded to use this method of
27650 		 * NACKing for all IPv6 (xresolv) cases,
27651 		 * whether our xresolv implementation is complete or not.
27652 		 *
27653 		 */
27654 		ire = (ire_t *)mp->b_rptr;
27655 		ill = ire_to_ill(ire);
27656 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27657 		if (mp1->b_rptr == mp1->b_wptr) {
27658 			if (ire->ire_ipversion == IPV6_VERSION) {
27659 				/*
27660 				 * XRESOLV interface.
27661 				 */
27662 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27663 				mutex_enter(&ire->ire_lock);
27664 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27665 				mutex_exit(&ire->ire_lock);
27666 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27667 					nce = ndp_lookup_v6(ill, B_FALSE,
27668 					    &ire->ire_addr_v6, B_FALSE);
27669 				} else {
27670 					nce = ndp_lookup_v6(ill, B_FALSE,
27671 					    &gw_addr_v6, B_FALSE);
27672 				}
27673 				if (nce != NULL) {
27674 					nce_resolv_failed(nce);
27675 					ndp_delete(nce);
27676 					NCE_REFRELE(nce);
27677 				}
27678 			}
27679 			mp->b_cont = NULL;
27680 			freemsg(mp1);		/* frees the pkt as well */
27681 			ASSERT(ire->ire_nce == NULL);
27682 			ire_delete((ire_t *)mp->b_rptr);
27683 			return;
27684 		}
27685 
27686 		/*
27687 		 * Split them into IRE_MBLK and pkt and feed it into
27688 		 * ire_add_then_send. Then in ire_add_then_send
27689 		 * the IRE will be added, and then the packet will be
27690 		 * run back through ip_wput. This time it will make
27691 		 * it to the wire.
27692 		 */
27693 		mp->b_cont = NULL;
27694 		mp = mp1->b_cont;		/* now, mp points to pkt */
27695 		mp1->b_cont = NULL;
27696 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27697 		if (ire->ire_ipversion == IPV6_VERSION) {
27698 			/*
27699 			 * XRESOLV interface. Find the nce and put a copy
27700 			 * of the dl_unitdata_req in nce_res_mp
27701 			 */
27702 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27703 			mutex_enter(&ire->ire_lock);
27704 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27705 			mutex_exit(&ire->ire_lock);
27706 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27707 				nce = ndp_lookup_v6(ill, B_FALSE,
27708 				    &ire->ire_addr_v6, B_FALSE);
27709 			} else {
27710 				nce = ndp_lookup_v6(ill, B_FALSE,
27711 				    &gw_addr_v6, B_FALSE);
27712 			}
27713 			if (nce != NULL) {
27714 				/*
27715 				 * We have to protect nce_res_mp here
27716 				 * from being accessed by other threads
27717 				 * while we change the mblk pointer.
27718 				 * Other functions will also lock the nce when
27719 				 * accessing nce_res_mp.
27720 				 *
27721 				 * The reason we change the mblk pointer
27722 				 * here rather than copying the resolved address
27723 				 * into the template is that, unlike with
27724 				 * ethernet, we have no guarantee that the
27725 				 * resolved address length will be
27726 				 * smaller than or equal to the lla length
27727 				 * with which the template was allocated,
27728 				 * (for ethernet, they're equal)
27729 				 * so we have to use the actual resolved
27730 				 * address mblk - which holds the real
27731 				 * dl_unitdata_req with the resolved address.
27732 				 *
27733 				 * Doing this is the same behavior as was
27734 				 * previously used in the v4 ARP case.
27735 				 */
27736 				mutex_enter(&nce->nce_lock);
27737 				if (nce->nce_res_mp != NULL)
27738 					freemsg(nce->nce_res_mp);
27739 				nce->nce_res_mp = mp1;
27740 				mutex_exit(&nce->nce_lock);
27741 				/*
27742 				 * We do a fastpath probe here because
27743 				 * we have resolved the address without
27744 				 * using Neighbor Discovery.
27745 				 * In the non-XRESOLV v6 case, the fastpath
27746 				 * probe is done right after neighbor
27747 				 * discovery completes.
27748 				 */
27749 				if (nce->nce_res_mp != NULL) {
27750 					int res;
27751 					nce_fastpath_list_add(nce);
27752 					res = ill_fastpath_probe(ill,
27753 					    nce->nce_res_mp);
27754 					if (res != 0 && res != EAGAIN)
27755 						nce_fastpath_list_delete(nce);
27756 				}
27757 
27758 				ire_add_then_send(q, ire, mp);
27759 				/*
27760 				 * Now we have to clean out any packets
27761 				 * that may have been queued on the nce
27762 				 * while it was waiting for address resolution
27763 				 * to complete.
27764 				 */
27765 				mutex_enter(&nce->nce_lock);
27766 				mp1 = nce->nce_qd_mp;
27767 				nce->nce_qd_mp = NULL;
27768 				mutex_exit(&nce->nce_lock);
27769 				while (mp1 != NULL) {
27770 					mblk_t *nxt_mp;
27771 					queue_t *fwdq = NULL;
27772 					ill_t   *inbound_ill;
27773 					uint_t ifindex;
27774 
27775 					nxt_mp = mp1->b_next;
27776 					mp1->b_next = NULL;
27777 					/*
27778 					 * Retrieve ifindex stored in
27779 					 * ip_rput_data_v6()
27780 					 */
27781 					ifindex =
27782 					    (uint_t)(uintptr_t)mp1->b_prev;
27783 					inbound_ill =
27784 					    ill_lookup_on_ifindex(ifindex,
27785 					    B_TRUE, NULL, NULL, NULL,
27786 					    NULL, ipst);
27787 					mp1->b_prev = NULL;
27788 					if (inbound_ill != NULL)
27789 						fwdq = inbound_ill->ill_rq;
27790 
27791 					if (fwdq != NULL) {
27792 						put(fwdq, mp1);
27793 						ill_refrele(inbound_ill);
27794 					} else
27795 						put(WR(ill->ill_rq), mp1);
27796 					mp1 = nxt_mp;
27797 				}
27798 				NCE_REFRELE(nce);
27799 			} else {	/* nce is NULL; clean up */
27800 				ire_delete(ire);
27801 				freemsg(mp);
27802 				freemsg(mp1);
27803 				return;
27804 			}
27805 		} else {
27806 			nce_t *arpce;
27807 			/*
27808 			 * Link layer resolution succeeded. Recompute the
27809 			 * ire_nce.
27810 			 */
27811 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27812 			if ((arpce = ndp_lookup_v4(ill,
27813 			    (ire->ire_gateway_addr != INADDR_ANY ?
27814 			    &ire->ire_gateway_addr : &ire->ire_addr),
27815 			    B_FALSE)) == NULL) {
27816 				freeb(ire->ire_mp);
27817 				freeb(mp1);
27818 				freemsg(mp);
27819 				return;
27820 			}
27821 			mutex_enter(&arpce->nce_lock);
27822 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27823 			if (arpce->nce_state == ND_REACHABLE) {
27824 				/*
27825 				 * Someone resolved this before us;
27826 				 * cleanup the res_mp. Since ire has
27827 				 * not been added yet, the call to ire_add_v4
27828 				 * from ire_add_then_send (when a dup is
27829 				 * detected) will clean up the ire.
27830 				 */
27831 				freeb(mp1);
27832 			} else {
27833 				ASSERT(arpce->nce_res_mp == NULL);
27834 				arpce->nce_res_mp = mp1;
27835 				arpce->nce_state = ND_REACHABLE;
27836 			}
27837 			mutex_exit(&arpce->nce_lock);
27838 			if (ire->ire_marks & IRE_MARK_NOADD) {
27839 				/*
27840 				 * this ire will not be added to the ire
27841 				 * cache table, so we can set the ire_nce
27842 				 * here, as there are no atomicity constraints.
27843 				 */
27844 				ire->ire_nce = arpce;
27845 				/*
27846 				 * We are associating this nce with the ire
27847 				 * so change the nce ref taken in
27848 				 * ndp_lookup_v4() from
27849 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27850 				 */
27851 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27852 			} else {
27853 				NCE_REFRELE(arpce);
27854 			}
27855 			ire_add_then_send(q, ire, mp);
27856 		}
27857 		return;	/* All is well, the packet has been sent. */
27858 	}
27859 	case IRE_ARPRESOLVE_TYPE: {
27860 
27861 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27862 			break;
27863 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27864 		mp->b_cont = NULL;
27865 		/*
27866 		 * First, check to make sure the resolution succeeded.
27867 		 * If it failed, the second mblk will be empty.
27868 		 */
27869 		if (mp1->b_rptr == mp1->b_wptr) {
27870 			/* cleanup  the incomplete ire, free queued packets */
27871 			freemsg(mp); /* fake ire */
27872 			freeb(mp1);  /* dl_unitdata response */
27873 			return;
27874 		}
27875 
27876 		/*
27877 		 * Update any incomplete nce_t found. We search the ctable
27878 		 * and find the nce from the ire->ire_nce because we need
27879 		 * to pass the ire to ip_xmit_v4 later, and can find both
27880 		 * ire and nce in one lookup.
27881 		 */
27882 		fake_ire = (ire_t *)mp->b_rptr;
27883 
27884 		/*
27885 		 * By the time we come back here from ARP the logical outgoing
27886 		 * interface of the incomplete ire we added in ire_forward()
27887 		 * could have disappeared, causing the incomplete ire to also
27888 		 * disappear.  So we need to retreive the proper ipif for the
27889 		 * ire before looking in ctable.  In the case of IPMP, the
27890 		 * ipif may be on the IPMP ill, so look it up based on the
27891 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27892 		 * Then, we can verify that ire_ipif_seqid still exists.
27893 		 */
27894 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27895 		    NULL, NULL, NULL, NULL, ipst);
27896 		if (ill == NULL) {
27897 			ip1dbg(("ill for incomplete ire vanished\n"));
27898 			freemsg(mp); /* fake ire */
27899 			freeb(mp1);  /* dl_unitdata response */
27900 			return;
27901 		}
27902 
27903 		/* Get the outgoing ipif */
27904 		mutex_enter(&ill->ill_lock);
27905 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27906 		if (ipif == NULL) {
27907 			mutex_exit(&ill->ill_lock);
27908 			ill_refrele(ill);
27909 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27910 			freemsg(mp); /* fake_ire */
27911 			freeb(mp1);  /* dl_unitdata response */
27912 			return;
27913 		}
27914 
27915 		ipif_refhold_locked(ipif);
27916 		mutex_exit(&ill->ill_lock);
27917 		ill_refrele(ill);
27918 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27919 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27920 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27921 		ipif_refrele(ipif);
27922 		if (ire == NULL) {
27923 			/*
27924 			 * no ire was found; check if there is an nce
27925 			 * for this lookup; if it has no ire's pointing at it
27926 			 * cleanup.
27927 			 */
27928 			if ((nce = ndp_lookup_v4(q->q_ptr,
27929 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27930 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27931 			    B_FALSE)) != NULL) {
27932 				/*
27933 				 * cleanup:
27934 				 * We check for refcnt 2 (one for the nce
27935 				 * hash list + 1 for the ref taken by
27936 				 * ndp_lookup_v4) to check that there are
27937 				 * no ire's pointing at the nce.
27938 				 */
27939 				if (nce->nce_refcnt == 2)
27940 					ndp_delete(nce);
27941 				NCE_REFRELE(nce);
27942 			}
27943 			freeb(mp1);  /* dl_unitdata response */
27944 			freemsg(mp); /* fake ire */
27945 			return;
27946 		}
27947 
27948 		nce = ire->ire_nce;
27949 		DTRACE_PROBE2(ire__arpresolve__type,
27950 		    ire_t *, ire, nce_t *, nce);
27951 		mutex_enter(&nce->nce_lock);
27952 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27953 		if (nce->nce_state == ND_REACHABLE) {
27954 			/*
27955 			 * Someone resolved this before us;
27956 			 * our response is not needed any more.
27957 			 */
27958 			mutex_exit(&nce->nce_lock);
27959 			freeb(mp1);  /* dl_unitdata response */
27960 		} else {
27961 			ASSERT(nce->nce_res_mp == NULL);
27962 			nce->nce_res_mp = mp1;
27963 			nce->nce_state = ND_REACHABLE;
27964 			mutex_exit(&nce->nce_lock);
27965 			nce_fastpath(nce);
27966 		}
27967 		/*
27968 		 * The cached nce_t has been updated to be reachable;
27969 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27970 		 */
27971 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27972 		freemsg(mp);
27973 		/*
27974 		 * send out queued packets.
27975 		 */
27976 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27977 
27978 		IRE_REFRELE(ire);
27979 		return;
27980 	}
27981 	default:
27982 		break;
27983 	}
27984 	if (q->q_next) {
27985 		putnext(q, mp);
27986 	} else
27987 		freemsg(mp);
27988 	return;
27989 
27990 protonak:
27991 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27992 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27993 		qreply(q, mp);
27994 }
27995 
27996 /*
27997  * Process IP options in an outbound packet.  Modify the destination if there
27998  * is a source route option.
27999  * Returns non-zero if something fails in which case an ICMP error has been
28000  * sent and mp freed.
28001  */
28002 static int
28003 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28004     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28005 {
28006 	ipoptp_t	opts;
28007 	uchar_t		*opt;
28008 	uint8_t		optval;
28009 	uint8_t		optlen;
28010 	ipaddr_t	dst;
28011 	intptr_t	code = 0;
28012 	mblk_t		*mp;
28013 	ire_t		*ire = NULL;
28014 
28015 	ip2dbg(("ip_wput_options\n"));
28016 	mp = ipsec_mp;
28017 	if (mctl_present) {
28018 		mp = ipsec_mp->b_cont;
28019 	}
28020 
28021 	dst = ipha->ipha_dst;
28022 	for (optval = ipoptp_first(&opts, ipha);
28023 	    optval != IPOPT_EOL;
28024 	    optval = ipoptp_next(&opts)) {
28025 		opt = opts.ipoptp_cur;
28026 		optlen = opts.ipoptp_len;
28027 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28028 		    optval, optlen));
28029 		switch (optval) {
28030 			uint32_t off;
28031 		case IPOPT_SSRR:
28032 		case IPOPT_LSRR:
28033 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28034 				ip1dbg((
28035 				    "ip_wput_options: bad option offset\n"));
28036 				code = (char *)&opt[IPOPT_OLEN] -
28037 				    (char *)ipha;
28038 				goto param_prob;
28039 			}
28040 			off = opt[IPOPT_OFFSET];
28041 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28042 			    ntohl(dst)));
28043 			/*
28044 			 * For strict: verify that dst is directly
28045 			 * reachable.
28046 			 */
28047 			if (optval == IPOPT_SSRR) {
28048 				ire = ire_ftable_lookup(dst, 0, 0,
28049 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28050 				    msg_getlabel(mp),
28051 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28052 				if (ire == NULL) {
28053 					ip1dbg(("ip_wput_options: SSRR not"
28054 					    " directly reachable: 0x%x\n",
28055 					    ntohl(dst)));
28056 					goto bad_src_route;
28057 				}
28058 				ire_refrele(ire);
28059 			}
28060 			break;
28061 		case IPOPT_RR:
28062 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28063 				ip1dbg((
28064 				    "ip_wput_options: bad option offset\n"));
28065 				code = (char *)&opt[IPOPT_OLEN] -
28066 				    (char *)ipha;
28067 				goto param_prob;
28068 			}
28069 			break;
28070 		case IPOPT_TS:
28071 			/*
28072 			 * Verify that length >=5 and that there is either
28073 			 * room for another timestamp or that the overflow
28074 			 * counter is not maxed out.
28075 			 */
28076 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28077 			if (optlen < IPOPT_MINLEN_IT) {
28078 				goto param_prob;
28079 			}
28080 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28081 				ip1dbg((
28082 				    "ip_wput_options: bad option offset\n"));
28083 				code = (char *)&opt[IPOPT_OFFSET] -
28084 				    (char *)ipha;
28085 				goto param_prob;
28086 			}
28087 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28088 			case IPOPT_TS_TSONLY:
28089 				off = IPOPT_TS_TIMELEN;
28090 				break;
28091 			case IPOPT_TS_TSANDADDR:
28092 			case IPOPT_TS_PRESPEC:
28093 			case IPOPT_TS_PRESPEC_RFC791:
28094 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28095 				break;
28096 			default:
28097 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28098 				    (char *)ipha;
28099 				goto param_prob;
28100 			}
28101 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28102 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28103 				/*
28104 				 * No room and the overflow counter is 15
28105 				 * already.
28106 				 */
28107 				goto param_prob;
28108 			}
28109 			break;
28110 		}
28111 	}
28112 
28113 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28114 		return (0);
28115 
28116 	ip1dbg(("ip_wput_options: error processing IP options."));
28117 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28118 
28119 param_prob:
28120 	/*
28121 	 * Since ip_wput() isn't close to finished, we fill
28122 	 * in enough of the header for credible error reporting.
28123 	 */
28124 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28125 		/* Failed */
28126 		freemsg(ipsec_mp);
28127 		return (-1);
28128 	}
28129 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28130 	return (-1);
28131 
28132 bad_src_route:
28133 	/*
28134 	 * Since ip_wput() isn't close to finished, we fill
28135 	 * in enough of the header for credible error reporting.
28136 	 */
28137 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28138 		/* Failed */
28139 		freemsg(ipsec_mp);
28140 		return (-1);
28141 	}
28142 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28143 	return (-1);
28144 }
28145 
28146 /*
28147  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28148  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28149  * thru /etc/system.
28150  */
28151 #define	CONN_MAXDRAINCNT	64
28152 
28153 static void
28154 conn_drain_init(ip_stack_t *ipst)
28155 {
28156 	int i, j;
28157 	idl_tx_list_t *itl_tx;
28158 
28159 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28160 
28161 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28162 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28163 		/*
28164 		 * Default value of the number of drainers is the
28165 		 * number of cpus, subject to maximum of 8 drainers.
28166 		 */
28167 		if (boot_max_ncpus != -1)
28168 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28169 		else
28170 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28171 	}
28172 
28173 	ipst->ips_idl_tx_list =
28174 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28175 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28176 		itl_tx =  &ipst->ips_idl_tx_list[i];
28177 		itl_tx->txl_drain_list =
28178 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28179 		    sizeof (idl_t), KM_SLEEP);
28180 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28181 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28182 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28183 			    MUTEX_DEFAULT, NULL);
28184 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28185 		}
28186 	}
28187 }
28188 
28189 static void
28190 conn_drain_fini(ip_stack_t *ipst)
28191 {
28192 	int i;
28193 	idl_tx_list_t *itl_tx;
28194 
28195 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28196 		itl_tx =  &ipst->ips_idl_tx_list[i];
28197 		kmem_free(itl_tx->txl_drain_list,
28198 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28199 	}
28200 	kmem_free(ipst->ips_idl_tx_list,
28201 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28202 	ipst->ips_idl_tx_list = NULL;
28203 }
28204 
28205 /*
28206  * Note: For an overview of how flowcontrol is handled in IP please see the
28207  * IP Flowcontrol notes at the top of this file.
28208  *
28209  * Flow control has blocked us from proceeding. Insert the given conn in one
28210  * of the conn drain lists. These conn wq's will be qenabled later on when
28211  * STREAMS flow control does a backenable. conn_walk_drain will enable
28212  * the first conn in each of these drain lists. Each of these qenabled conns
28213  * in turn enables the next in the list, after it runs, or when it closes,
28214  * thus sustaining the drain process.
28215  */
28216 void
28217 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28218 {
28219 	idl_t	*idl = tx_list->txl_drain_list;
28220 	uint_t	index;
28221 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28222 
28223 	mutex_enter(&connp->conn_lock);
28224 	if (connp->conn_state_flags & CONN_CLOSING) {
28225 		/*
28226 		 * The conn is closing as a result of which CONN_CLOSING
28227 		 * is set. Return.
28228 		 */
28229 		mutex_exit(&connp->conn_lock);
28230 		return;
28231 	} else if (connp->conn_idl == NULL) {
28232 		/*
28233 		 * Assign the next drain list round robin. We dont' use
28234 		 * a lock, and thus it may not be strictly round robin.
28235 		 * Atomicity of load/stores is enough to make sure that
28236 		 * conn_drain_list_index is always within bounds.
28237 		 */
28238 		index = tx_list->txl_drain_index;
28239 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28240 		connp->conn_idl = &tx_list->txl_drain_list[index];
28241 		index++;
28242 		if (index == ipst->ips_conn_drain_list_cnt)
28243 			index = 0;
28244 		tx_list->txl_drain_index = index;
28245 	}
28246 	mutex_exit(&connp->conn_lock);
28247 
28248 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28249 	if ((connp->conn_drain_prev != NULL) ||
28250 	    (connp->conn_state_flags & CONN_CLOSING)) {
28251 		/*
28252 		 * The conn is already in the drain list, OR
28253 		 * the conn is closing. We need to check again for
28254 		 * the closing case again since close can happen
28255 		 * after we drop the conn_lock, and before we
28256 		 * acquire the CONN_DRAIN_LIST_LOCK.
28257 		 */
28258 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28259 		return;
28260 	} else {
28261 		idl = connp->conn_idl;
28262 	}
28263 
28264 	/*
28265 	 * The conn is not in the drain list. Insert it at the
28266 	 * tail of the drain list. The drain list is circular
28267 	 * and doubly linked. idl_conn points to the 1st element
28268 	 * in the list.
28269 	 */
28270 	if (idl->idl_conn == NULL) {
28271 		idl->idl_conn = connp;
28272 		connp->conn_drain_next = connp;
28273 		connp->conn_drain_prev = connp;
28274 	} else {
28275 		conn_t *head = idl->idl_conn;
28276 
28277 		connp->conn_drain_next = head;
28278 		connp->conn_drain_prev = head->conn_drain_prev;
28279 		head->conn_drain_prev->conn_drain_next = connp;
28280 		head->conn_drain_prev = connp;
28281 	}
28282 	/*
28283 	 * For non streams based sockets assert flow control.
28284 	 */
28285 	if (IPCL_IS_NONSTR(connp)) {
28286 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28287 		(*connp->conn_upcalls->su_txq_full)
28288 		    (connp->conn_upper_handle, B_TRUE);
28289 	} else {
28290 		conn_setqfull(connp);
28291 		noenable(connp->conn_wq);
28292 	}
28293 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28294 }
28295 
28296 /*
28297  * This conn is closing, and we are called from ip_close. OR
28298  * This conn has been serviced by ip_wsrv, and we need to do the tail
28299  * processing.
28300  * If this conn is part of the drain list, we may need to sustain the drain
28301  * process by qenabling the next conn in the drain list. We may also need to
28302  * remove this conn from the list, if it is done.
28303  */
28304 static void
28305 conn_drain_tail(conn_t *connp, boolean_t closing)
28306 {
28307 	idl_t *idl;
28308 
28309 	/*
28310 	 * connp->conn_idl is stable at this point, and no lock is needed
28311 	 * to check it. If we are called from ip_close, close has already
28312 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28313 	 * called us only because conn_idl is non-null. If we are called thru
28314 	 * service, conn_idl could be null, but it cannot change because
28315 	 * service is single-threaded per queue, and there cannot be another
28316 	 * instance of service trying to call conn_drain_insert on this conn
28317 	 * now.
28318 	 */
28319 	ASSERT(!closing || (connp->conn_idl != NULL));
28320 
28321 	/*
28322 	 * If connp->conn_idl is null, the conn has not been inserted into any
28323 	 * drain list even once since creation of the conn. Just return.
28324 	 */
28325 	if (connp->conn_idl == NULL)
28326 		return;
28327 
28328 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28329 
28330 	if (connp->conn_drain_prev == NULL) {
28331 		/* This conn is currently not in the drain list.  */
28332 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28333 		return;
28334 	}
28335 	idl = connp->conn_idl;
28336 	if (idl->idl_conn_draining == connp) {
28337 		/*
28338 		 * This conn is the current drainer. If this is the last conn
28339 		 * in the drain list, we need to do more checks, in the 'if'
28340 		 * below. Otherwwise we need to just qenable the next conn,
28341 		 * to sustain the draining, and is handled in the 'else'
28342 		 * below.
28343 		 */
28344 		if (connp->conn_drain_next == idl->idl_conn) {
28345 			/*
28346 			 * This conn is the last in this list. This round
28347 			 * of draining is complete. If idl_repeat is set,
28348 			 * it means another flow enabling has happened from
28349 			 * the driver/streams and we need to another round
28350 			 * of draining.
28351 			 * If there are more than 2 conns in the drain list,
28352 			 * do a left rotate by 1, so that all conns except the
28353 			 * conn at the head move towards the head by 1, and the
28354 			 * the conn at the head goes to the tail. This attempts
28355 			 * a more even share for all queues that are being
28356 			 * drained.
28357 			 */
28358 			if ((connp->conn_drain_next != connp) &&
28359 			    (idl->idl_conn->conn_drain_next != connp)) {
28360 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28361 			}
28362 			if (idl->idl_repeat) {
28363 				qenable(idl->idl_conn->conn_wq);
28364 				idl->idl_conn_draining = idl->idl_conn;
28365 				idl->idl_repeat = 0;
28366 			} else {
28367 				idl->idl_conn_draining = NULL;
28368 			}
28369 		} else {
28370 			/*
28371 			 * If the next queue that we are now qenable'ing,
28372 			 * is closing, it will remove itself from this list
28373 			 * and qenable the subsequent queue in ip_close().
28374 			 * Serialization is acheived thru idl_lock.
28375 			 */
28376 			qenable(connp->conn_drain_next->conn_wq);
28377 			idl->idl_conn_draining = connp->conn_drain_next;
28378 		}
28379 	}
28380 	if (!connp->conn_did_putbq || closing) {
28381 		/*
28382 		 * Remove ourself from the drain list, if we did not do
28383 		 * a putbq, or if the conn is closing.
28384 		 * Note: It is possible that q->q_first is non-null. It means
28385 		 * that these messages landed after we did a enableok() in
28386 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28387 		 * service them.
28388 		 */
28389 		if (connp->conn_drain_next == connp) {
28390 			/* Singleton in the list */
28391 			ASSERT(connp->conn_drain_prev == connp);
28392 			idl->idl_conn = NULL;
28393 			idl->idl_conn_draining = NULL;
28394 		} else {
28395 			connp->conn_drain_prev->conn_drain_next =
28396 			    connp->conn_drain_next;
28397 			connp->conn_drain_next->conn_drain_prev =
28398 			    connp->conn_drain_prev;
28399 			if (idl->idl_conn == connp)
28400 				idl->idl_conn = connp->conn_drain_next;
28401 			ASSERT(idl->idl_conn_draining != connp);
28402 
28403 		}
28404 		connp->conn_drain_next = NULL;
28405 		connp->conn_drain_prev = NULL;
28406 
28407 		/*
28408 		 * For non streams based sockets open up flow control.
28409 		 */
28410 		if (IPCL_IS_NONSTR(connp)) {
28411 			(*connp->conn_upcalls->su_txq_full)
28412 			    (connp->conn_upper_handle, B_FALSE);
28413 		} else {
28414 			conn_clrqfull(connp);
28415 			enableok(connp->conn_wq);
28416 		}
28417 	}
28418 
28419 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28420 }
28421 
28422 /*
28423  * Write service routine. Shared perimeter entry point.
28424  * ip_wsrv can be called in any of the following ways.
28425  * 1. The device queue's messages has fallen below the low water mark
28426  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28427  *    the drain lists and backenable the first conn in each list.
28428  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28429  *    qenabled non-tcp upper layers. We start dequeing messages and call
28430  *    ip_wput for each message.
28431  */
28432 
28433 void
28434 ip_wsrv(queue_t *q)
28435 {
28436 	conn_t	*connp;
28437 	ill_t	*ill;
28438 	mblk_t	*mp;
28439 
28440 	if (q->q_next) {
28441 		ill = (ill_t *)q->q_ptr;
28442 		if (ill->ill_state_flags == 0) {
28443 			ip_stack_t *ipst = ill->ill_ipst;
28444 
28445 			/*
28446 			 * The device flow control has opened up.
28447 			 * Walk through conn drain lists and qenable the
28448 			 * first conn in each list. This makes sense only
28449 			 * if the stream is fully plumbed and setup.
28450 			 * Hence the if check above.
28451 			 */
28452 			ip1dbg(("ip_wsrv: walking\n"));
28453 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28454 		}
28455 		return;
28456 	}
28457 
28458 	connp = Q_TO_CONN(q);
28459 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28460 
28461 	/*
28462 	 * 1. Set conn_draining flag to signal that service is active.
28463 	 *
28464 	 * 2. ip_output determines whether it has been called from service,
28465 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28466 	 *    has been called from service.
28467 	 *
28468 	 * 3. Message ordering is preserved by the following logic.
28469 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28470 	 *    the message at the tail, if conn_draining is set (i.e. service
28471 	 *    is running) or if q->q_first is non-null.
28472 	 *
28473 	 *    ii. If ip_output is called from service, and if ip_output cannot
28474 	 *    putnext due to flow control, it does a putbq.
28475 	 *
28476 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28477 	 *    (causing an infinite loop).
28478 	 */
28479 	ASSERT(!connp->conn_did_putbq);
28480 
28481 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28482 		connp->conn_draining = 1;
28483 		noenable(q);
28484 		while ((mp = getq(q)) != NULL) {
28485 			ASSERT(CONN_Q(q));
28486 
28487 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28488 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28489 			if (connp->conn_did_putbq) {
28490 				/* ip_wput did a putbq */
28491 				break;
28492 			}
28493 		}
28494 		/*
28495 		 * At this point, a thread coming down from top, calling
28496 		 * ip_wput, may end up queueing the message. We have not yet
28497 		 * enabled the queue, so ip_wsrv won't be called again.
28498 		 * To avoid this race, check q->q_first again (in the loop)
28499 		 * If the other thread queued the message before we call
28500 		 * enableok(), we will catch it in the q->q_first check.
28501 		 * If the other thread queues the message after we call
28502 		 * enableok(), ip_wsrv will be called again by STREAMS.
28503 		 */
28504 		connp->conn_draining = 0;
28505 		enableok(q);
28506 	}
28507 
28508 	/* Enable the next conn for draining */
28509 	conn_drain_tail(connp, B_FALSE);
28510 
28511 	/*
28512 	 * conn_direct_blocked is used to indicate blocked
28513 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28514 	 * This is the only place where it is set without
28515 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28516 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28517 	 */
28518 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28519 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28520 		connp->conn_direct_blocked = B_FALSE;
28521 	}
28522 
28523 	connp->conn_did_putbq = 0;
28524 }
28525 
28526 /*
28527  * Callback to disable flow control in IP.
28528  *
28529  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28530  * is enabled.
28531  *
28532  * When MAC_TX() is not able to send any more packets, dld sets its queue
28533  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28534  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28535  * function and wakes up corresponding mac worker threads, which in turn
28536  * calls this callback function, and disables flow control.
28537  */
28538 void
28539 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28540 {
28541 	ill_t *ill = (ill_t *)arg;
28542 	ip_stack_t *ipst = ill->ill_ipst;
28543 	idl_tx_list_t *idl_txl;
28544 
28545 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28546 	mutex_enter(&idl_txl->txl_lock);
28547 	/* add code to to set a flag to indicate idl_txl is enabled */
28548 	conn_walk_drain(ipst, idl_txl);
28549 	mutex_exit(&idl_txl->txl_lock);
28550 }
28551 
28552 /*
28553  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28554  * of conns that need to be drained, check if drain is already in progress.
28555  * If so set the idl_repeat bit, indicating that the last conn in the list
28556  * needs to reinitiate the drain once again, for the list. If drain is not
28557  * in progress for the list, initiate the draining, by qenabling the 1st
28558  * conn in the list. The drain is self-sustaining, each qenabled conn will
28559  * in turn qenable the next conn, when it is done/blocked/closing.
28560  */
28561 static void
28562 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28563 {
28564 	int i;
28565 	idl_t *idl;
28566 
28567 	IP_STAT(ipst, ip_conn_walk_drain);
28568 
28569 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28570 		idl = &tx_list->txl_drain_list[i];
28571 		mutex_enter(&idl->idl_lock);
28572 		if (idl->idl_conn == NULL) {
28573 			mutex_exit(&idl->idl_lock);
28574 			continue;
28575 		}
28576 		/*
28577 		 * If this list is not being drained currently by
28578 		 * an ip_wsrv thread, start the process.
28579 		 */
28580 		if (idl->idl_conn_draining == NULL) {
28581 			ASSERT(idl->idl_repeat == 0);
28582 			qenable(idl->idl_conn->conn_wq);
28583 			idl->idl_conn_draining = idl->idl_conn;
28584 		} else {
28585 			idl->idl_repeat = 1;
28586 		}
28587 		mutex_exit(&idl->idl_lock);
28588 	}
28589 }
28590 
28591 /*
28592  * Determine if the ill and multicast aspects of that packets
28593  * "matches" the conn.
28594  */
28595 boolean_t
28596 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28597     zoneid_t zoneid)
28598 {
28599 	ill_t *bound_ill;
28600 	boolean_t found;
28601 	ipif_t *ipif;
28602 	ire_t *ire;
28603 	ipaddr_t dst, src;
28604 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28605 
28606 	dst = ipha->ipha_dst;
28607 	src = ipha->ipha_src;
28608 
28609 	/*
28610 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28611 	 * unicast, broadcast and multicast reception to
28612 	 * conn_incoming_ill. conn_wantpacket itself is called
28613 	 * only for BROADCAST and multicast.
28614 	 */
28615 	bound_ill = connp->conn_incoming_ill;
28616 	if (bound_ill != NULL) {
28617 		if (IS_IPMP(bound_ill)) {
28618 			if (bound_ill->ill_grp != ill->ill_grp)
28619 				return (B_FALSE);
28620 		} else {
28621 			if (bound_ill != ill)
28622 				return (B_FALSE);
28623 		}
28624 	}
28625 
28626 	if (!CLASSD(dst)) {
28627 		if (IPCL_ZONE_MATCH(connp, zoneid))
28628 			return (B_TRUE);
28629 		/*
28630 		 * The conn is in a different zone; we need to check that this
28631 		 * broadcast address is configured in the application's zone.
28632 		 */
28633 		ipif = ipif_get_next_ipif(NULL, ill);
28634 		if (ipif == NULL)
28635 			return (B_FALSE);
28636 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28637 		    connp->conn_zoneid, NULL,
28638 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28639 		ipif_refrele(ipif);
28640 		if (ire != NULL) {
28641 			ire_refrele(ire);
28642 			return (B_TRUE);
28643 		} else {
28644 			return (B_FALSE);
28645 		}
28646 	}
28647 
28648 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28649 	    connp->conn_zoneid == zoneid) {
28650 		/*
28651 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28652 		 * disabled, therefore we don't dispatch the multicast packet to
28653 		 * the sending zone.
28654 		 */
28655 		return (B_FALSE);
28656 	}
28657 
28658 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28659 		/*
28660 		 * Multicast packet on the loopback interface: we only match
28661 		 * conns who joined the group in the specified zone.
28662 		 */
28663 		return (B_FALSE);
28664 	}
28665 
28666 	if (connp->conn_multi_router) {
28667 		/* multicast packet and multicast router socket: send up */
28668 		return (B_TRUE);
28669 	}
28670 
28671 	mutex_enter(&connp->conn_lock);
28672 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28673 	mutex_exit(&connp->conn_lock);
28674 	return (found);
28675 }
28676 
28677 static void
28678 conn_setqfull(conn_t *connp)
28679 {
28680 	queue_t *q = connp->conn_wq;
28681 
28682 	if (!(q->q_flag & QFULL)) {
28683 		mutex_enter(QLOCK(q));
28684 		if (!(q->q_flag & QFULL)) {
28685 			/* still need to set QFULL */
28686 			q->q_flag |= QFULL;
28687 			mutex_exit(QLOCK(q));
28688 		} else {
28689 			mutex_exit(QLOCK(q));
28690 		}
28691 	}
28692 }
28693 
28694 static void
28695 conn_clrqfull(conn_t *connp)
28696 {
28697 	queue_t *q = connp->conn_wq;
28698 
28699 	if (q->q_flag & QFULL) {
28700 		mutex_enter(QLOCK(q));
28701 		if (q->q_flag & QFULL) {
28702 			q->q_flag &= ~QFULL;
28703 			mutex_exit(QLOCK(q));
28704 			if (q->q_flag & QWANTW)
28705 				qbackenable(q, 0);
28706 		} else {
28707 			mutex_exit(QLOCK(q));
28708 		}
28709 	}
28710 }
28711 
28712 /*
28713  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28714  */
28715 /* ARGSUSED */
28716 static void
28717 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28718 {
28719 	ill_t *ill = (ill_t *)q->q_ptr;
28720 	mblk_t	*mp1, *mp2;
28721 	ipif_t  *ipif;
28722 	int err = 0;
28723 	conn_t *connp = NULL;
28724 	ipsq_t	*ipsq;
28725 	arc_t	*arc;
28726 
28727 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28728 
28729 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28730 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28731 
28732 	ASSERT(IAM_WRITER_ILL(ill));
28733 	mp2 = mp->b_cont;
28734 	mp->b_cont = NULL;
28735 
28736 	/*
28737 	 * We have now received the arp bringup completion message
28738 	 * from ARP. Mark the arp bringup as done. Also if the arp
28739 	 * stream has already started closing, send up the AR_ARP_CLOSING
28740 	 * ack now since ARP is waiting in close for this ack.
28741 	 */
28742 	mutex_enter(&ill->ill_lock);
28743 	ill->ill_arp_bringup_pending = 0;
28744 	if (ill->ill_arp_closing) {
28745 		mutex_exit(&ill->ill_lock);
28746 		/* Let's reuse the mp for sending the ack */
28747 		arc = (arc_t *)mp->b_rptr;
28748 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28749 		arc->arc_cmd = AR_ARP_CLOSING;
28750 		qreply(q, mp);
28751 	} else {
28752 		mutex_exit(&ill->ill_lock);
28753 		freeb(mp);
28754 	}
28755 
28756 	ipsq = ill->ill_phyint->phyint_ipsq;
28757 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28758 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28759 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28760 	if (mp1 == NULL) {
28761 		/* bringup was aborted by the user */
28762 		freemsg(mp2);
28763 		return;
28764 	}
28765 
28766 	/*
28767 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28768 	 * must have an associated conn_t.  Otherwise, we're bringing this
28769 	 * interface back up as part of handling an asynchronous event (e.g.,
28770 	 * physical address change).
28771 	 */
28772 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28773 		ASSERT(connp != NULL);
28774 		q = CONNP_TO_WQ(connp);
28775 	} else {
28776 		ASSERT(connp == NULL);
28777 		q = ill->ill_rq;
28778 	}
28779 
28780 	/*
28781 	 * If the DL_BIND_REQ fails, it is noted
28782 	 * in arc_name_offset.
28783 	 */
28784 	err = *((int *)mp2->b_rptr);
28785 	if (err == 0) {
28786 		if (ipif->ipif_isv6) {
28787 			if ((err = ipif_up_done_v6(ipif)) != 0)
28788 				ip0dbg(("ip_arp_done: init failed\n"));
28789 		} else {
28790 			if ((err = ipif_up_done(ipif)) != 0)
28791 				ip0dbg(("ip_arp_done: init failed\n"));
28792 		}
28793 	} else {
28794 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28795 	}
28796 
28797 	freemsg(mp2);
28798 
28799 	if ((err == 0) && (ill->ill_up_ipifs)) {
28800 		err = ill_up_ipifs(ill, q, mp1);
28801 		if (err == EINPROGRESS)
28802 			return;
28803 	}
28804 
28805 	/*
28806 	 * If we have a moved ipif to bring up, and everything has succeeded
28807 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28808 	 * down -- the admin can try to bring it up by hand if need be.
28809 	 */
28810 	if (ill->ill_move_ipif != NULL) {
28811 		ipif = ill->ill_move_ipif;
28812 		ill->ill_move_ipif = NULL;
28813 		if (err == 0) {
28814 			err = ipif_up(ipif, q, mp1);
28815 			if (err == EINPROGRESS)
28816 				return;
28817 		}
28818 	}
28819 
28820 	/*
28821 	 * The operation must complete without EINPROGRESS since
28822 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28823 	 * operation will be stuck forever in the ipsq.
28824 	 */
28825 	ASSERT(err != EINPROGRESS);
28826 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28827 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28828 	else
28829 		ipsq_current_finish(ipsq);
28830 }
28831 
28832 /* Allocate the private structure */
28833 static int
28834 ip_priv_alloc(void **bufp)
28835 {
28836 	void	*buf;
28837 
28838 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28839 		return (ENOMEM);
28840 
28841 	*bufp = buf;
28842 	return (0);
28843 }
28844 
28845 /* Function to delete the private structure */
28846 void
28847 ip_priv_free(void *buf)
28848 {
28849 	ASSERT(buf != NULL);
28850 	kmem_free(buf, sizeof (ip_priv_t));
28851 }
28852 
28853 /*
28854  * The entry point for IPPF processing.
28855  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28856  * routine just returns.
28857  *
28858  * When called, ip_process generates an ipp_packet_t structure
28859  * which holds the state information for this packet and invokes the
28860  * the classifier (via ipp_packet_process). The classification, depending on
28861  * configured filters, results in a list of actions for this packet. Invoking
28862  * an action may cause the packet to be dropped, in which case the resulting
28863  * mblk (*mpp) is NULL. proc indicates the callout position for
28864  * this packet and ill_index is the interface this packet on or will leave
28865  * on (inbound and outbound resp.).
28866  */
28867 void
28868 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28869 {
28870 	mblk_t		*mp;
28871 	ip_priv_t	*priv;
28872 	ipp_action_id_t	aid;
28873 	int		rc = 0;
28874 	ipp_packet_t	*pp;
28875 #define	IP_CLASS	"ip"
28876 
28877 	/* If the classifier is not loaded, return  */
28878 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28879 		return;
28880 	}
28881 
28882 	mp = *mpp;
28883 	ASSERT(mp != NULL);
28884 
28885 	/* Allocate the packet structure */
28886 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28887 	if (rc != 0) {
28888 		*mpp = NULL;
28889 		freemsg(mp);
28890 		return;
28891 	}
28892 
28893 	/* Allocate the private structure */
28894 	rc = ip_priv_alloc((void **)&priv);
28895 	if (rc != 0) {
28896 		*mpp = NULL;
28897 		freemsg(mp);
28898 		ipp_packet_free(pp);
28899 		return;
28900 	}
28901 	priv->proc = proc;
28902 	priv->ill_index = ill_index;
28903 	ipp_packet_set_private(pp, priv, ip_priv_free);
28904 	ipp_packet_set_data(pp, mp);
28905 
28906 	/* Invoke the classifier */
28907 	rc = ipp_packet_process(&pp);
28908 	if (pp != NULL) {
28909 		mp = ipp_packet_get_data(pp);
28910 		ipp_packet_free(pp);
28911 		if (rc != 0) {
28912 			freemsg(mp);
28913 			*mpp = NULL;
28914 		}
28915 	} else {
28916 		*mpp = NULL;
28917 	}
28918 #undef	IP_CLASS
28919 }
28920 
28921 /*
28922  * Propagate a multicast group membership operation (add/drop) on
28923  * all the interfaces crossed by the related multirt routes.
28924  * The call is considered successful if the operation succeeds
28925  * on at least one interface.
28926  */
28927 static int
28928 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28929     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28930     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28931     mblk_t *first_mp)
28932 {
28933 	ire_t		*ire_gw;
28934 	irb_t		*irb;
28935 	int		error = 0;
28936 	opt_restart_t	*or;
28937 	ip_stack_t	*ipst = ire->ire_ipst;
28938 
28939 	irb = ire->ire_bucket;
28940 	ASSERT(irb != NULL);
28941 
28942 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28943 
28944 	or = (opt_restart_t *)first_mp->b_rptr;
28945 	IRB_REFHOLD(irb);
28946 	for (; ire != NULL; ire = ire->ire_next) {
28947 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28948 			continue;
28949 		if (ire->ire_addr != group)
28950 			continue;
28951 
28952 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28953 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28954 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28955 		/* No resolver exists for the gateway; skip this ire. */
28956 		if (ire_gw == NULL)
28957 			continue;
28958 
28959 		/*
28960 		 * This function can return EINPROGRESS. If so the operation
28961 		 * will be restarted from ip_restart_optmgmt which will
28962 		 * call ip_opt_set and option processing will restart for
28963 		 * this option. So we may end up calling 'fn' more than once.
28964 		 * This requires that 'fn' is idempotent except for the
28965 		 * return value. The operation is considered a success if
28966 		 * it succeeds at least once on any one interface.
28967 		 */
28968 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28969 		    NULL, fmode, src, first_mp);
28970 		if (error == 0)
28971 			or->or_private = CGTP_MCAST_SUCCESS;
28972 
28973 		if (ip_debug > 0) {
28974 			ulong_t	off;
28975 			char	*ksym;
28976 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28977 			ip2dbg(("ip_multirt_apply_membership: "
28978 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28979 			    "error %d [success %u]\n",
28980 			    ksym ? ksym : "?",
28981 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28982 			    error, or->or_private));
28983 		}
28984 
28985 		ire_refrele(ire_gw);
28986 		if (error == EINPROGRESS) {
28987 			IRB_REFRELE(irb);
28988 			return (error);
28989 		}
28990 	}
28991 	IRB_REFRELE(irb);
28992 	/*
28993 	 * Consider the call as successful if we succeeded on at least
28994 	 * one interface. Otherwise, return the last encountered error.
28995 	 */
28996 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28997 }
28998 
28999 /*
29000  * Issue a warning regarding a route crossing an interface with an
29001  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29002  * amount of time is logged.
29003  */
29004 static void
29005 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29006 {
29007 	hrtime_t	current = gethrtime();
29008 	char		buf[INET_ADDRSTRLEN];
29009 	ip_stack_t	*ipst = ire->ire_ipst;
29010 
29011 	/* Convert interval in ms to hrtime in ns */
29012 	if (ipst->ips_multirt_bad_mtu_last_time +
29013 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29014 	    current) {
29015 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29016 		    "to %s, incorrect MTU %u (expected %u)\n",
29017 		    ip_dot_addr(ire->ire_addr, buf),
29018 		    ire->ire_max_frag, max_frag);
29019 
29020 		ipst->ips_multirt_bad_mtu_last_time = current;
29021 	}
29022 }
29023 
29024 /*
29025  * Get the CGTP (multirouting) filtering status.
29026  * If 0, the CGTP hooks are transparent.
29027  */
29028 /* ARGSUSED */
29029 static int
29030 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29031 {
29032 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29033 
29034 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29035 	return (0);
29036 }
29037 
29038 /*
29039  * Set the CGTP (multirouting) filtering status.
29040  * If the status is changed from active to transparent
29041  * or from transparent to active, forward the new status
29042  * to the filtering module (if loaded).
29043  */
29044 /* ARGSUSED */
29045 static int
29046 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29047     cred_t *ioc_cr)
29048 {
29049 	long		new_value;
29050 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29051 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29052 
29053 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29054 		return (EPERM);
29055 
29056 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29057 	    new_value < 0 || new_value > 1) {
29058 		return (EINVAL);
29059 	}
29060 
29061 	if ((!*ip_cgtp_filter_value) && new_value) {
29062 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29063 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29064 		    " (module not loaded)" : "");
29065 	}
29066 	if (*ip_cgtp_filter_value && (!new_value)) {
29067 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29068 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29069 		    " (module not loaded)" : "");
29070 	}
29071 
29072 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29073 		int	res;
29074 		netstackid_t stackid;
29075 
29076 		stackid = ipst->ips_netstack->netstack_stackid;
29077 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29078 		    new_value);
29079 		if (res)
29080 			return (res);
29081 	}
29082 
29083 	*ip_cgtp_filter_value = (boolean_t)new_value;
29084 
29085 	return (0);
29086 }
29087 
29088 /*
29089  * Return the expected CGTP hooks version number.
29090  */
29091 int
29092 ip_cgtp_filter_supported(void)
29093 {
29094 	return (ip_cgtp_filter_rev);
29095 }
29096 
29097 /*
29098  * CGTP hooks can be registered by invoking this function.
29099  * Checks that the version number matches.
29100  */
29101 int
29102 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29103 {
29104 	netstack_t *ns;
29105 	ip_stack_t *ipst;
29106 
29107 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29108 		return (ENOTSUP);
29109 
29110 	ns = netstack_find_by_stackid(stackid);
29111 	if (ns == NULL)
29112 		return (EINVAL);
29113 	ipst = ns->netstack_ip;
29114 	ASSERT(ipst != NULL);
29115 
29116 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29117 		netstack_rele(ns);
29118 		return (EALREADY);
29119 	}
29120 
29121 	ipst->ips_ip_cgtp_filter_ops = ops;
29122 	netstack_rele(ns);
29123 	return (0);
29124 }
29125 
29126 /*
29127  * CGTP hooks can be unregistered by invoking this function.
29128  * Returns ENXIO if there was no registration.
29129  * Returns EBUSY if the ndd variable has not been turned off.
29130  */
29131 int
29132 ip_cgtp_filter_unregister(netstackid_t stackid)
29133 {
29134 	netstack_t *ns;
29135 	ip_stack_t *ipst;
29136 
29137 	ns = netstack_find_by_stackid(stackid);
29138 	if (ns == NULL)
29139 		return (EINVAL);
29140 	ipst = ns->netstack_ip;
29141 	ASSERT(ipst != NULL);
29142 
29143 	if (ipst->ips_ip_cgtp_filter) {
29144 		netstack_rele(ns);
29145 		return (EBUSY);
29146 	}
29147 
29148 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29149 		netstack_rele(ns);
29150 		return (ENXIO);
29151 	}
29152 	ipst->ips_ip_cgtp_filter_ops = NULL;
29153 	netstack_rele(ns);
29154 	return (0);
29155 }
29156 
29157 /*
29158  * Check whether there is a CGTP filter registration.
29159  * Returns non-zero if there is a registration, otherwise returns zero.
29160  * Note: returns zero if bad stackid.
29161  */
29162 int
29163 ip_cgtp_filter_is_registered(netstackid_t stackid)
29164 {
29165 	netstack_t *ns;
29166 	ip_stack_t *ipst;
29167 	int ret;
29168 
29169 	ns = netstack_find_by_stackid(stackid);
29170 	if (ns == NULL)
29171 		return (0);
29172 	ipst = ns->netstack_ip;
29173 	ASSERT(ipst != NULL);
29174 
29175 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29176 		ret = 1;
29177 	else
29178 		ret = 0;
29179 
29180 	netstack_rele(ns);
29181 	return (ret);
29182 }
29183 
29184 static int
29185 ip_squeue_switch(int val)
29186 {
29187 	int rval = SQ_FILL;
29188 
29189 	switch (val) {
29190 	case IP_SQUEUE_ENTER_NODRAIN:
29191 		rval = SQ_NODRAIN;
29192 		break;
29193 	case IP_SQUEUE_ENTER:
29194 		rval = SQ_PROCESS;
29195 		break;
29196 	default:
29197 		break;
29198 	}
29199 	return (rval);
29200 }
29201 
29202 /* ARGSUSED */
29203 static int
29204 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29205     caddr_t addr, cred_t *cr)
29206 {
29207 	int *v = (int *)addr;
29208 	long new_value;
29209 
29210 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29211 		return (EPERM);
29212 
29213 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29214 		return (EINVAL);
29215 
29216 	ip_squeue_flag = ip_squeue_switch(new_value);
29217 	*v = new_value;
29218 	return (0);
29219 }
29220 
29221 /*
29222  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29223  * ip_debug.
29224  */
29225 /* ARGSUSED */
29226 static int
29227 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29228     caddr_t addr, cred_t *cr)
29229 {
29230 	int *v = (int *)addr;
29231 	long new_value;
29232 
29233 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29234 		return (EPERM);
29235 
29236 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29237 		return (EINVAL);
29238 
29239 	*v = new_value;
29240 	return (0);
29241 }
29242 
29243 static void *
29244 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29245 {
29246 	kstat_t *ksp;
29247 
29248 	ip_stat_t template = {
29249 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29250 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29251 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29252 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29253 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29254 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29255 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29256 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29257 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29258 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29259 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29260 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29261 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29262 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29263 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29264 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29265 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29266 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29267 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29268 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29269 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29270 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29271 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29272 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29273 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29274 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29275 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29276 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29277 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29278 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29279 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29280 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29281 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29282 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29283 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29284 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29285 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29286 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29287 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29288 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29289 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29290 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29291 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29292 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29293 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29294 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29295 	};
29296 
29297 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29298 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29299 	    KSTAT_FLAG_VIRTUAL, stackid);
29300 
29301 	if (ksp == NULL)
29302 		return (NULL);
29303 
29304 	bcopy(&template, ip_statisticsp, sizeof (template));
29305 	ksp->ks_data = (void *)ip_statisticsp;
29306 	ksp->ks_private = (void *)(uintptr_t)stackid;
29307 
29308 	kstat_install(ksp);
29309 	return (ksp);
29310 }
29311 
29312 static void
29313 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29314 {
29315 	if (ksp != NULL) {
29316 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29317 		kstat_delete_netstack(ksp, stackid);
29318 	}
29319 }
29320 
29321 static void *
29322 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29323 {
29324 	kstat_t	*ksp;
29325 
29326 	ip_named_kstat_t template = {
29327 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29328 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29329 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29330 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29331 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29332 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29333 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29334 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29335 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29336 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29337 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29338 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29339 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29340 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29341 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29342 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29343 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29344 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29345 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29346 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29347 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29348 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29349 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29350 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29351 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29352 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29353 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29354 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29355 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29356 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29357 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29358 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29359 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29360 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29361 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29362 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29363 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29364 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29365 	};
29366 
29367 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29368 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29369 	if (ksp == NULL || ksp->ks_data == NULL)
29370 		return (NULL);
29371 
29372 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29373 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29374 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29375 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29376 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29377 
29378 	template.netToMediaEntrySize.value.i32 =
29379 	    sizeof (mib2_ipNetToMediaEntry_t);
29380 
29381 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29382 
29383 	bcopy(&template, ksp->ks_data, sizeof (template));
29384 	ksp->ks_update = ip_kstat_update;
29385 	ksp->ks_private = (void *)(uintptr_t)stackid;
29386 
29387 	kstat_install(ksp);
29388 	return (ksp);
29389 }
29390 
29391 static void
29392 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29393 {
29394 	if (ksp != NULL) {
29395 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29396 		kstat_delete_netstack(ksp, stackid);
29397 	}
29398 }
29399 
29400 static int
29401 ip_kstat_update(kstat_t *kp, int rw)
29402 {
29403 	ip_named_kstat_t *ipkp;
29404 	mib2_ipIfStatsEntry_t ipmib;
29405 	ill_walk_context_t ctx;
29406 	ill_t *ill;
29407 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29408 	netstack_t	*ns;
29409 	ip_stack_t	*ipst;
29410 
29411 	if (kp == NULL || kp->ks_data == NULL)
29412 		return (EIO);
29413 
29414 	if (rw == KSTAT_WRITE)
29415 		return (EACCES);
29416 
29417 	ns = netstack_find_by_stackid(stackid);
29418 	if (ns == NULL)
29419 		return (-1);
29420 	ipst = ns->netstack_ip;
29421 	if (ipst == NULL) {
29422 		netstack_rele(ns);
29423 		return (-1);
29424 	}
29425 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29426 
29427 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29428 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29429 	ill = ILL_START_WALK_V4(&ctx, ipst);
29430 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29431 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29432 	rw_exit(&ipst->ips_ill_g_lock);
29433 
29434 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29435 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29436 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29437 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29438 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29439 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29440 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29441 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29442 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29443 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29444 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29445 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29446 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29447 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29448 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29449 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29450 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29451 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29452 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29453 
29454 	ipkp->routingDiscards.value.ui32 =	0;
29455 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29456 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29457 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29458 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29459 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29460 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29461 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29462 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29463 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29464 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29465 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29466 
29467 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29468 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29469 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29470 
29471 	netstack_rele(ns);
29472 
29473 	return (0);
29474 }
29475 
29476 static void *
29477 icmp_kstat_init(netstackid_t stackid)
29478 {
29479 	kstat_t	*ksp;
29480 
29481 	icmp_named_kstat_t template = {
29482 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29483 		{ "inErrors",		KSTAT_DATA_UINT32 },
29484 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29485 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29486 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29487 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29488 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29489 		{ "inEchos",		KSTAT_DATA_UINT32 },
29490 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29491 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29492 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29493 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29494 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29495 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29496 		{ "outErrors",		KSTAT_DATA_UINT32 },
29497 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29498 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29499 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29500 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29501 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29502 		{ "outEchos",		KSTAT_DATA_UINT32 },
29503 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29504 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29505 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29506 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29507 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29508 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29509 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29510 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29511 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29512 		{ "outDrops",		KSTAT_DATA_UINT32 },
29513 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29514 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29515 	};
29516 
29517 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29518 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29519 	if (ksp == NULL || ksp->ks_data == NULL)
29520 		return (NULL);
29521 
29522 	bcopy(&template, ksp->ks_data, sizeof (template));
29523 
29524 	ksp->ks_update = icmp_kstat_update;
29525 	ksp->ks_private = (void *)(uintptr_t)stackid;
29526 
29527 	kstat_install(ksp);
29528 	return (ksp);
29529 }
29530 
29531 static void
29532 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29533 {
29534 	if (ksp != NULL) {
29535 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29536 		kstat_delete_netstack(ksp, stackid);
29537 	}
29538 }
29539 
29540 static int
29541 icmp_kstat_update(kstat_t *kp, int rw)
29542 {
29543 	icmp_named_kstat_t *icmpkp;
29544 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29545 	netstack_t	*ns;
29546 	ip_stack_t	*ipst;
29547 
29548 	if ((kp == NULL) || (kp->ks_data == NULL))
29549 		return (EIO);
29550 
29551 	if (rw == KSTAT_WRITE)
29552 		return (EACCES);
29553 
29554 	ns = netstack_find_by_stackid(stackid);
29555 	if (ns == NULL)
29556 		return (-1);
29557 	ipst = ns->netstack_ip;
29558 	if (ipst == NULL) {
29559 		netstack_rele(ns);
29560 		return (-1);
29561 	}
29562 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29563 
29564 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29565 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29566 	icmpkp->inDestUnreachs.value.ui32 =
29567 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29568 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29569 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29570 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29571 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29572 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29573 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29574 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29575 	icmpkp->inTimestampReps.value.ui32 =
29576 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29577 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29578 	icmpkp->inAddrMaskReps.value.ui32 =
29579 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29580 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29581 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29582 	icmpkp->outDestUnreachs.value.ui32 =
29583 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29584 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29585 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29586 	icmpkp->outSrcQuenchs.value.ui32 =
29587 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29588 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29589 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29590 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29591 	icmpkp->outTimestamps.value.ui32 =
29592 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29593 	icmpkp->outTimestampReps.value.ui32 =
29594 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29595 	icmpkp->outAddrMasks.value.ui32 =
29596 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29597 	icmpkp->outAddrMaskReps.value.ui32 =
29598 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29599 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29600 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29601 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29602 	icmpkp->outFragNeeded.value.ui32 =
29603 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29604 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29605 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29606 	icmpkp->inBadRedirects.value.ui32 =
29607 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29608 
29609 	netstack_rele(ns);
29610 	return (0);
29611 }
29612 
29613 /*
29614  * This is the fanout function for raw socket opened for SCTP.  Note
29615  * that it is called after SCTP checks that there is no socket which
29616  * wants a packet.  Then before SCTP handles this out of the blue packet,
29617  * this function is called to see if there is any raw socket for SCTP.
29618  * If there is and it is bound to the correct address, the packet will
29619  * be sent to that socket.  Note that only one raw socket can be bound to
29620  * a port.  This is assured in ipcl_sctp_hash_insert();
29621  */
29622 void
29623 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29624     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29625     zoneid_t zoneid)
29626 {
29627 	conn_t		*connp;
29628 	queue_t		*rq;
29629 	mblk_t		*first_mp;
29630 	boolean_t	secure;
29631 	ip6_t		*ip6h;
29632 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29633 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29634 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29635 	boolean_t	sctp_csum_err = B_FALSE;
29636 
29637 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29638 		sctp_csum_err = B_TRUE;
29639 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29640 	}
29641 
29642 	first_mp = mp;
29643 	if (mctl_present) {
29644 		mp = first_mp->b_cont;
29645 		secure = ipsec_in_is_secure(first_mp);
29646 		ASSERT(mp != NULL);
29647 	} else {
29648 		secure = B_FALSE;
29649 	}
29650 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29651 
29652 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29653 	if (connp == NULL) {
29654 		/*
29655 		 * Although raw sctp is not summed, OOB chunks must be.
29656 		 * Drop the packet here if the sctp checksum failed.
29657 		 */
29658 		if (sctp_csum_err) {
29659 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29660 			freemsg(first_mp);
29661 			return;
29662 		}
29663 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29664 		return;
29665 	}
29666 	rq = connp->conn_rq;
29667 	if (!canputnext(rq)) {
29668 		CONN_DEC_REF(connp);
29669 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29670 		freemsg(first_mp);
29671 		return;
29672 	}
29673 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29674 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29675 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29676 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29677 		if (first_mp == NULL) {
29678 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29679 			CONN_DEC_REF(connp);
29680 			return;
29681 		}
29682 	}
29683 	/*
29684 	 * We probably should not send M_CTL message up to
29685 	 * raw socket.
29686 	 */
29687 	if (mctl_present)
29688 		freeb(first_mp);
29689 
29690 	/* Initiate IPPF processing here if needed. */
29691 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29692 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29693 		ip_process(IPP_LOCAL_IN, &mp,
29694 		    recv_ill->ill_phyint->phyint_ifindex);
29695 		if (mp == NULL) {
29696 			CONN_DEC_REF(connp);
29697 			return;
29698 		}
29699 	}
29700 
29701 	if (connp->conn_recvif || connp->conn_recvslla ||
29702 	    ((connp->conn_ip_recvpktinfo ||
29703 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29704 	    (flags & IP_FF_IPINFO))) {
29705 		int in_flags = 0;
29706 
29707 		/*
29708 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29709 		 * IPF_RECVIF.
29710 		 */
29711 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29712 			in_flags = IPF_RECVIF;
29713 		}
29714 		if (connp->conn_recvslla) {
29715 			in_flags |= IPF_RECVSLLA;
29716 		}
29717 		if (isv4) {
29718 			mp = ip_add_info(mp, recv_ill, in_flags,
29719 			    IPCL_ZONEID(connp), ipst);
29720 		} else {
29721 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29722 			if (mp == NULL) {
29723 				BUMP_MIB(recv_ill->ill_ip_mib,
29724 				    ipIfStatsInDiscards);
29725 				CONN_DEC_REF(connp);
29726 				return;
29727 			}
29728 		}
29729 	}
29730 
29731 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29732 	/*
29733 	 * We are sending the IPSEC_IN message also up. Refer
29734 	 * to comments above this function.
29735 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29736 	 */
29737 	(connp->conn_recv)(connp, mp, NULL);
29738 	CONN_DEC_REF(connp);
29739 }
29740 
29741 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29742 {									\
29743 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29744 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29745 }
29746 /*
29747  * This function should be called only if all packet processing
29748  * including fragmentation is complete. Callers of this function
29749  * must set mp->b_prev to one of these values:
29750  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29751  * prior to handing over the mp as first argument to this function.
29752  *
29753  * If the ire passed by caller is incomplete, this function
29754  * queues the packet and if necessary, sends ARP request and bails.
29755  * If the ire passed is fully resolved, we simply prepend
29756  * the link-layer header to the packet, do ipsec hw acceleration
29757  * work if necessary, and send the packet out on the wire.
29758  *
29759  * NOTE: IPsec will only call this function with fully resolved
29760  * ires if hw acceleration is involved.
29761  * TODO list :
29762  * 	a Handle M_MULTIDATA so that
29763  *	  tcp_multisend->tcp_multisend_data can
29764  *	  call ip_xmit_v4 directly
29765  *	b Handle post-ARP work for fragments so that
29766  *	  ip_wput_frag can call this function.
29767  */
29768 ipxmit_state_t
29769 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29770     boolean_t flow_ctl_enabled, conn_t *connp)
29771 {
29772 	nce_t		*arpce;
29773 	ipha_t		*ipha;
29774 	queue_t		*q;
29775 	int		ill_index;
29776 	mblk_t		*nxt_mp, *first_mp;
29777 	boolean_t	xmit_drop = B_FALSE;
29778 	ip_proc_t	proc;
29779 	ill_t		*out_ill;
29780 	int		pkt_len;
29781 
29782 	arpce = ire->ire_nce;
29783 	ASSERT(arpce != NULL);
29784 
29785 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29786 
29787 	mutex_enter(&arpce->nce_lock);
29788 	switch (arpce->nce_state) {
29789 	case ND_REACHABLE:
29790 		/* If there are other queued packets, queue this packet */
29791 		if (arpce->nce_qd_mp != NULL) {
29792 			if (mp != NULL)
29793 				nce_queue_mp_common(arpce, mp, B_FALSE);
29794 			mp = arpce->nce_qd_mp;
29795 		}
29796 		arpce->nce_qd_mp = NULL;
29797 		mutex_exit(&arpce->nce_lock);
29798 
29799 		/*
29800 		 * Flush the queue.  In the common case, where the
29801 		 * ARP is already resolved,  it will go through the
29802 		 * while loop only once.
29803 		 */
29804 		while (mp != NULL) {
29805 
29806 			nxt_mp = mp->b_next;
29807 			mp->b_next = NULL;
29808 			ASSERT(mp->b_datap->db_type != M_CTL);
29809 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29810 			/*
29811 			 * This info is needed for IPQOS to do COS marking
29812 			 * in ip_wput_attach_llhdr->ip_process.
29813 			 */
29814 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29815 			mp->b_prev = NULL;
29816 
29817 			/* set up ill index for outbound qos processing */
29818 			out_ill = ire_to_ill(ire);
29819 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29820 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29821 			    ill_index, &ipha);
29822 			if (first_mp == NULL) {
29823 				xmit_drop = B_TRUE;
29824 				BUMP_MIB(out_ill->ill_ip_mib,
29825 				    ipIfStatsOutDiscards);
29826 				goto next_mp;
29827 			}
29828 
29829 			/* non-ipsec hw accel case */
29830 			if (io == NULL || !io->ipsec_out_accelerated) {
29831 				/* send it */
29832 				q = ire->ire_stq;
29833 				if (proc == IPP_FWD_OUT) {
29834 					UPDATE_IB_PKT_COUNT(ire);
29835 				} else {
29836 					UPDATE_OB_PKT_COUNT(ire);
29837 				}
29838 				ire->ire_last_used_time = lbolt;
29839 
29840 				if (flow_ctl_enabled || canputnext(q)) {
29841 					if (proc == IPP_FWD_OUT) {
29842 
29843 					BUMP_MIB(out_ill->ill_ip_mib,
29844 					    ipIfStatsHCOutForwDatagrams);
29845 
29846 					}
29847 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29848 					    pkt_len);
29849 
29850 					DTRACE_IP7(send, mblk_t *, first_mp,
29851 					    conn_t *, NULL, void_ip_t *, ipha,
29852 					    __dtrace_ipsr_ill_t *, out_ill,
29853 					    ipha_t *, ipha, ip6_t *, NULL, int,
29854 					    0);
29855 
29856 					ILL_SEND_TX(out_ill,
29857 					    ire, connp, first_mp, 0, connp);
29858 				} else {
29859 					BUMP_MIB(out_ill->ill_ip_mib,
29860 					    ipIfStatsOutDiscards);
29861 					xmit_drop = B_TRUE;
29862 					freemsg(first_mp);
29863 				}
29864 			} else {
29865 				/*
29866 				 * Safety Pup says: make sure this
29867 				 *  is going to the right interface!
29868 				 */
29869 				ill_t *ill1 =
29870 				    (ill_t *)ire->ire_stq->q_ptr;
29871 				int ifindex =
29872 				    ill1->ill_phyint->phyint_ifindex;
29873 				if (ifindex !=
29874 				    io->ipsec_out_capab_ill_index) {
29875 					xmit_drop = B_TRUE;
29876 					freemsg(mp);
29877 				} else {
29878 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29879 					    pkt_len);
29880 
29881 					DTRACE_IP7(send, mblk_t *, first_mp,
29882 					    conn_t *, NULL, void_ip_t *, ipha,
29883 					    __dtrace_ipsr_ill_t *, ill1,
29884 					    ipha_t *, ipha, ip6_t *, NULL,
29885 					    int, 0);
29886 
29887 					ipsec_hw_putnext(ire->ire_stq, mp);
29888 				}
29889 			}
29890 next_mp:
29891 			mp = nxt_mp;
29892 		} /* while (mp != NULL) */
29893 		if (xmit_drop)
29894 			return (SEND_FAILED);
29895 		else
29896 			return (SEND_PASSED);
29897 
29898 	case ND_INITIAL:
29899 	case ND_INCOMPLETE:
29900 
29901 		/*
29902 		 * While we do send off packets to dests that
29903 		 * use fully-resolved CGTP routes, we do not
29904 		 * handle unresolved CGTP routes.
29905 		 */
29906 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29907 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29908 
29909 		if (mp != NULL) {
29910 			/* queue the packet */
29911 			nce_queue_mp_common(arpce, mp, B_FALSE);
29912 		}
29913 
29914 		if (arpce->nce_state == ND_INCOMPLETE) {
29915 			mutex_exit(&arpce->nce_lock);
29916 			DTRACE_PROBE3(ip__xmit__incomplete,
29917 			    (ire_t *), ire, (mblk_t *), mp,
29918 			    (ipsec_out_t *), io);
29919 			return (LOOKUP_IN_PROGRESS);
29920 		}
29921 
29922 		arpce->nce_state = ND_INCOMPLETE;
29923 		mutex_exit(&arpce->nce_lock);
29924 
29925 		/*
29926 		 * Note that ire_add() (called from ire_forward())
29927 		 * holds a ref on the ire until ARP is completed.
29928 		 */
29929 		ire_arpresolve(ire);
29930 		return (LOOKUP_IN_PROGRESS);
29931 	default:
29932 		ASSERT(0);
29933 		mutex_exit(&arpce->nce_lock);
29934 		return (LLHDR_RESLV_FAILED);
29935 	}
29936 }
29937 
29938 #undef	UPDATE_IP_MIB_OB_COUNTERS
29939 
29940 /*
29941  * Return B_TRUE if the buffers differ in length or content.
29942  * This is used for comparing extension header buffers.
29943  * Note that an extension header would be declared different
29944  * even if all that changed was the next header value in that header i.e.
29945  * what really changed is the next extension header.
29946  */
29947 boolean_t
29948 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29949     uint_t blen)
29950 {
29951 	if (!b_valid)
29952 		blen = 0;
29953 
29954 	if (alen != blen)
29955 		return (B_TRUE);
29956 	if (alen == 0)
29957 		return (B_FALSE);	/* Both zero length */
29958 	return (bcmp(abuf, bbuf, alen));
29959 }
29960 
29961 /*
29962  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29963  * Return B_FALSE if memory allocation fails - don't change any state!
29964  */
29965 boolean_t
29966 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29967     const void *src, uint_t srclen)
29968 {
29969 	void *dst;
29970 
29971 	if (!src_valid)
29972 		srclen = 0;
29973 
29974 	ASSERT(*dstlenp == 0);
29975 	if (src != NULL && srclen != 0) {
29976 		dst = mi_alloc(srclen, BPRI_MED);
29977 		if (dst == NULL)
29978 			return (B_FALSE);
29979 	} else {
29980 		dst = NULL;
29981 	}
29982 	if (*dstp != NULL)
29983 		mi_free(*dstp);
29984 	*dstp = dst;
29985 	*dstlenp = dst == NULL ? 0 : srclen;
29986 	return (B_TRUE);
29987 }
29988 
29989 /*
29990  * Replace what is in *dst, *dstlen with the source.
29991  * Assumes ip_allocbuf has already been called.
29992  */
29993 void
29994 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29995     const void *src, uint_t srclen)
29996 {
29997 	if (!src_valid)
29998 		srclen = 0;
29999 
30000 	ASSERT(*dstlenp == srclen);
30001 	if (src != NULL && srclen != 0)
30002 		bcopy(src, *dstp, srclen);
30003 }
30004 
30005 /*
30006  * Free the storage pointed to by the members of an ip6_pkt_t.
30007  */
30008 void
30009 ip6_pkt_free(ip6_pkt_t *ipp)
30010 {
30011 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30012 
30013 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30014 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30015 		ipp->ipp_hopopts = NULL;
30016 		ipp->ipp_hopoptslen = 0;
30017 	}
30018 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30019 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30020 		ipp->ipp_rtdstopts = NULL;
30021 		ipp->ipp_rtdstoptslen = 0;
30022 	}
30023 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30024 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30025 		ipp->ipp_dstopts = NULL;
30026 		ipp->ipp_dstoptslen = 0;
30027 	}
30028 	if (ipp->ipp_fields & IPPF_RTHDR) {
30029 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30030 		ipp->ipp_rthdr = NULL;
30031 		ipp->ipp_rthdrlen = 0;
30032 	}
30033 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30034 	    IPPF_RTHDR);
30035 }
30036 
30037 zoneid_t
30038 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30039     zoneid_t lookup_zoneid)
30040 {
30041 	ire_t		*ire;
30042 	int		ire_flags = MATCH_IRE_TYPE;
30043 	zoneid_t	zoneid = ALL_ZONES;
30044 
30045 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30046 		return (ALL_ZONES);
30047 
30048 	if (lookup_zoneid != ALL_ZONES)
30049 		ire_flags |= MATCH_IRE_ZONEONLY;
30050 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30051 	    lookup_zoneid, NULL, ire_flags, ipst);
30052 	if (ire != NULL) {
30053 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30054 		ire_refrele(ire);
30055 	}
30056 	return (zoneid);
30057 }
30058 
30059 zoneid_t
30060 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30061     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30062 {
30063 	ire_t		*ire;
30064 	int		ire_flags = MATCH_IRE_TYPE;
30065 	zoneid_t	zoneid = ALL_ZONES;
30066 	ipif_t		*ipif_arg = NULL;
30067 
30068 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30069 		return (ALL_ZONES);
30070 
30071 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30072 		ire_flags |= MATCH_IRE_ILL;
30073 		ipif_arg = ill->ill_ipif;
30074 	}
30075 	if (lookup_zoneid != ALL_ZONES)
30076 		ire_flags |= MATCH_IRE_ZONEONLY;
30077 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30078 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30079 	if (ire != NULL) {
30080 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30081 		ire_refrele(ire);
30082 	}
30083 	return (zoneid);
30084 }
30085 
30086 /*
30087  * IP obserability hook support functions.
30088  */
30089 
30090 static void
30091 ipobs_init(ip_stack_t *ipst)
30092 {
30093 	ipst->ips_ipobs_enabled = B_FALSE;
30094 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30095 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30096 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30097 	ipst->ips_ipobs_cb_nwalkers = 0;
30098 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30099 }
30100 
30101 static void
30102 ipobs_fini(ip_stack_t *ipst)
30103 {
30104 	ipobs_cb_t *cb;
30105 
30106 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30107 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30108 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30109 
30110 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30111 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30112 		kmem_free(cb, sizeof (*cb));
30113 	}
30114 	list_destroy(&ipst->ips_ipobs_cb_list);
30115 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30116 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30117 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30118 }
30119 
30120 void
30121 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30122     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30123 {
30124 	mblk_t *mp2;
30125 	ipobs_cb_t *ipobs_cb;
30126 	ipobs_hook_data_t *ihd;
30127 	uint64_t grifindex = 0;
30128 
30129 	ASSERT(DB_TYPE(mp) == M_DATA);
30130 
30131 	if (IS_UNDER_IPMP(ill))
30132 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30133 
30134 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30135 	ipst->ips_ipobs_cb_nwalkers++;
30136 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30137 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30138 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30139 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30140 		if (mp2 != NULL) {
30141 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30142 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30143 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30144 				freemsg(mp2);
30145 				continue;
30146 			}
30147 			ihd->ihd_mp->b_rptr += hlen;
30148 			ihd->ihd_htype = htype;
30149 			ihd->ihd_ipver = ipver;
30150 			ihd->ihd_zsrc = zsrc;
30151 			ihd->ihd_zdst = zdst;
30152 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30153 			ihd->ihd_grifindex = grifindex;
30154 			ihd->ihd_stack = ipst->ips_netstack;
30155 			mp2->b_wptr += sizeof (*ihd);
30156 			ipobs_cb->ipobs_cbfunc(mp2);
30157 		}
30158 	}
30159 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30160 	ipst->ips_ipobs_cb_nwalkers--;
30161 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30162 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30163 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30164 }
30165 
30166 void
30167 ipobs_register_hook(netstack_t *ns, pfv_t func)
30168 {
30169 	ipobs_cb_t   *cb;
30170 	ip_stack_t *ipst = ns->netstack_ip;
30171 
30172 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30173 
30174 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30175 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30176 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30177 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30178 
30179 	cb->ipobs_cbfunc = func;
30180 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30181 	ipst->ips_ipobs_enabled = B_TRUE;
30182 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30183 }
30184 
30185 void
30186 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30187 {
30188 	ipobs_cb_t	*curcb;
30189 	ip_stack_t	*ipst = ns->netstack_ip;
30190 
30191 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30192 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30193 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30194 
30195 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30196 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30197 		if (func == curcb->ipobs_cbfunc) {
30198 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30199 			kmem_free(curcb, sizeof (*curcb));
30200 			break;
30201 		}
30202 	}
30203 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30204 		ipst->ips_ipobs_enabled = B_FALSE;
30205 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30206 }
30207