xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision d67944fbe3fa0b31893a7116a09b0718eecf6078)
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 peers label (aka
4313  * conn_peercred), which is needed for MLP on TCP/SCTP. Last priority is the
4314  * open credentials.
4315  */
4316 cred_t *
4317 ip_best_cred(mblk_t *mp, conn_t *connp)
4318 {
4319 	cred_t *cr;
4320 
4321 	cr = msg_getcred(mp, NULL);
4322 	if (cr != NULL && crgetlabel(cr) != NULL)
4323 		return (cr);
4324 	return (CONN_CRED(connp));
4325 }
4326 
4327 /*
4328  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4329  * part of the bind request.
4330  */
4331 
4332 boolean_t
4333 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4334 {
4335 	ipsec_in_t *ii;
4336 
4337 	ASSERT(policy_mp != NULL);
4338 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4339 
4340 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4341 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4342 
4343 	connp->conn_policy = ii->ipsec_in_policy;
4344 	ii->ipsec_in_policy = NULL;
4345 
4346 	if (ii->ipsec_in_action != NULL) {
4347 		if (connp->conn_latch == NULL) {
4348 			connp->conn_latch = iplatch_create();
4349 			if (connp->conn_latch == NULL)
4350 				return (B_FALSE);
4351 		}
4352 		ipsec_latch_inbound(connp->conn_latch, ii);
4353 	}
4354 	return (B_TRUE);
4355 }
4356 
4357 static void
4358 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4359 {
4360 	/*
4361 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4362 	 * We can't do this in ip_bind_get_ire because the policy
4363 	 * may not have been inherited at that point in time and hence
4364 	 * conn_out_enforce_policy may not be set.
4365 	 */
4366 	if (ire_requested && connp->conn_out_enforce_policy &&
4367 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4368 		ire_t *ire = (ire_t *)mp->b_rptr;
4369 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4370 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4371 	}
4372 }
4373 
4374 /*
4375  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4376  * and to arrange for power-fanout assist.  The ULP is identified by
4377  * adding a single byte at the end of the original bind message.
4378  * A ULP other than UDP or TCP that wishes to be recognized passes
4379  * down a bind with a zero length address.
4380  *
4381  * The binding works as follows:
4382  * - A zero byte address means just bind to the protocol.
4383  * - A four byte address is treated as a request to validate
4384  *   that the address is a valid local address, appropriate for
4385  *   an application to bind to. This does not affect any fanout
4386  *   information in IP.
4387  * - A sizeof sin_t byte address is used to bind to only the local address
4388  *   and port.
4389  * - A sizeof ipa_conn_t byte address contains complete fanout information
4390  *   consisting of local and remote addresses and ports.  In
4391  *   this case, the addresses are both validated as appropriate
4392  *   for this operation, and, if so, the information is retained
4393  *   for use in the inbound fanout.
4394  *
4395  * The ULP (except in the zero-length bind) can append an
4396  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4397  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4398  * a copy of the source or destination IRE (source for local bind;
4399  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4400  * policy information contained should be copied on to the conn.
4401  *
4402  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4403  */
4404 mblk_t *
4405 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4406 {
4407 	ssize_t		len;
4408 	struct T_bind_req	*tbr;
4409 	sin_t		*sin;
4410 	ipa_conn_t	*ac;
4411 	uchar_t		*ucp;
4412 	mblk_t		*mp1;
4413 	boolean_t	ire_requested;
4414 	int		error = 0;
4415 	int		protocol;
4416 	ipa_conn_x_t	*acx;
4417 	cred_t		*cr;
4418 
4419 	/*
4420 	 * All Solaris components should pass a db_credp
4421 	 * for this TPI message, hence we ASSERT.
4422 	 * But in case there is some other M_PROTO that looks
4423 	 * like a TPI message sent by some other kernel
4424 	 * component, we check and return an error.
4425 	 */
4426 	cr = msg_getcred(mp, NULL);
4427 	ASSERT(cr != NULL);
4428 	if (cr == NULL) {
4429 		error = EINVAL;
4430 		goto bad_addr;
4431 	}
4432 
4433 	ASSERT(!connp->conn_af_isv6);
4434 	connp->conn_pkt_isv6 = B_FALSE;
4435 
4436 	len = MBLKL(mp);
4437 	if (len < (sizeof (*tbr) + 1)) {
4438 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4439 		    "ip_bind: bogus msg, len %ld", len);
4440 		/* XXX: Need to return something better */
4441 		goto bad_addr;
4442 	}
4443 	/* Back up and extract the protocol identifier. */
4444 	mp->b_wptr--;
4445 	protocol = *mp->b_wptr & 0xFF;
4446 	tbr = (struct T_bind_req *)mp->b_rptr;
4447 	/* Reset the message type in preparation for shipping it back. */
4448 	DB_TYPE(mp) = M_PCPROTO;
4449 
4450 	connp->conn_ulp = (uint8_t)protocol;
4451 
4452 	/*
4453 	 * Check for a zero length address.  This is from a protocol that
4454 	 * wants to register to receive all packets of its type.
4455 	 */
4456 	if (tbr->ADDR_length == 0) {
4457 		/*
4458 		 * These protocols are now intercepted in ip_bind_v6().
4459 		 * Reject protocol-level binds here for now.
4460 		 *
4461 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4462 		 * so that the protocol type cannot be SCTP.
4463 		 */
4464 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4465 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4466 			goto bad_addr;
4467 		}
4468 
4469 		/*
4470 		 *
4471 		 * The udp module never sends down a zero-length address,
4472 		 * and allowing this on a labeled system will break MLP
4473 		 * functionality.
4474 		 */
4475 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4476 			goto bad_addr;
4477 
4478 		if (connp->conn_mac_exempt)
4479 			goto bad_addr;
4480 
4481 		/* No hash here really.  The table is big enough. */
4482 		connp->conn_srcv6 = ipv6_all_zeros;
4483 
4484 		ipcl_proto_insert(connp, protocol);
4485 
4486 		tbr->PRIM_type = T_BIND_ACK;
4487 		return (mp);
4488 	}
4489 
4490 	/* Extract the address pointer from the message. */
4491 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4492 	    tbr->ADDR_length);
4493 	if (ucp == NULL) {
4494 		ip1dbg(("ip_bind: no address\n"));
4495 		goto bad_addr;
4496 	}
4497 	if (!OK_32PTR(ucp)) {
4498 		ip1dbg(("ip_bind: unaligned address\n"));
4499 		goto bad_addr;
4500 	}
4501 	/*
4502 	 * Check for trailing mps.
4503 	 */
4504 
4505 	mp1 = mp->b_cont;
4506 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4507 
4508 	switch (tbr->ADDR_length) {
4509 	default:
4510 		ip1dbg(("ip_bind: bad address length %d\n",
4511 		    (int)tbr->ADDR_length));
4512 		goto bad_addr;
4513 
4514 	case IP_ADDR_LEN:
4515 		/* Verification of local address only */
4516 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4517 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4518 		break;
4519 
4520 	case sizeof (sin_t):
4521 		sin = (sin_t *)ucp;
4522 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4523 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4524 		break;
4525 
4526 	case sizeof (ipa_conn_t):
4527 		ac = (ipa_conn_t *)ucp;
4528 		/* For raw socket, the local port is not set. */
4529 		if (ac->ac_lport == 0)
4530 			ac->ac_lport = connp->conn_lport;
4531 		/* Always verify destination reachability. */
4532 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4533 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4534 		    B_TRUE, B_TRUE, cr);
4535 		break;
4536 
4537 	case sizeof (ipa_conn_x_t):
4538 		acx = (ipa_conn_x_t *)ucp;
4539 		/*
4540 		 * Whether or not to verify destination reachability depends
4541 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4542 		 */
4543 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4544 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4545 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4546 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4547 		break;
4548 	}
4549 	ASSERT(error != EINPROGRESS);
4550 	if (error != 0)
4551 		goto bad_addr;
4552 
4553 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4554 
4555 	/* Send it home. */
4556 	mp->b_datap->db_type = M_PCPROTO;
4557 	tbr->PRIM_type = T_BIND_ACK;
4558 	return (mp);
4559 
4560 bad_addr:
4561 	/*
4562 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4563 	 * a unix errno.
4564 	 */
4565 	if (error > 0)
4566 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4567 	else
4568 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4569 	return (mp);
4570 }
4571 
4572 /*
4573  * Here address is verified to be a valid local address.
4574  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4575  * address is also considered a valid local address.
4576  * In the case of a broadcast/multicast address, however, the
4577  * upper protocol is expected to reset the src address
4578  * to 0 if it sees a IRE_BROADCAST type returned so that
4579  * no packets are emitted with broadcast/multicast address as
4580  * source address (that violates hosts requirements RFC 1122)
4581  * The addresses valid for bind are:
4582  *	(1) - INADDR_ANY (0)
4583  *	(2) - IP address of an UP interface
4584  *	(3) - IP address of a DOWN interface
4585  *	(4) - valid local IP broadcast addresses. In this case
4586  *	the conn will only receive packets destined to
4587  *	the specified broadcast address.
4588  *	(5) - a multicast address. In this case
4589  *	the conn will only receive packets destined to
4590  *	the specified multicast address. Note: the
4591  *	application still has to issue an
4592  *	IP_ADD_MEMBERSHIP socket option.
4593  *
4594  * On error, return -1 for TBADADDR otherwise pass the
4595  * errno with TSYSERR reply.
4596  *
4597  * In all the above cases, the bound address must be valid in the current zone.
4598  * When the address is loopback, multicast or broadcast, there might be many
4599  * matching IREs so bind has to look up based on the zone.
4600  *
4601  * Note: lport is in network byte order.
4602  *
4603  */
4604 int
4605 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4606     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4607 {
4608 	int		error = 0;
4609 	ire_t		*src_ire;
4610 	zoneid_t	zoneid;
4611 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4612 	mblk_t		*mp = NULL;
4613 	boolean_t	ire_requested = B_FALSE;
4614 	boolean_t	ipsec_policy_set = B_FALSE;
4615 
4616 	if (mpp)
4617 		mp = *mpp;
4618 
4619 	if (mp != NULL) {
4620 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4621 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4622 	}
4623 
4624 	/*
4625 	 * If it was previously connected, conn_fully_bound would have
4626 	 * been set.
4627 	 */
4628 	connp->conn_fully_bound = B_FALSE;
4629 
4630 	src_ire = NULL;
4631 
4632 	zoneid = IPCL_ZONEID(connp);
4633 
4634 	if (src_addr) {
4635 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4636 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4637 		/*
4638 		 * If an address other than 0.0.0.0 is requested,
4639 		 * we verify that it is a valid address for bind
4640 		 * Note: Following code is in if-else-if form for
4641 		 * readability compared to a condition check.
4642 		 */
4643 		/* LINTED - statement has no consequence */
4644 		if (IRE_IS_LOCAL(src_ire)) {
4645 			/*
4646 			 * (2) Bind to address of local UP interface
4647 			 */
4648 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4649 			/*
4650 			 * (4) Bind to broadcast address
4651 			 * Note: permitted only from transports that
4652 			 * request IRE
4653 			 */
4654 			if (!ire_requested)
4655 				error = EADDRNOTAVAIL;
4656 		} else {
4657 			/*
4658 			 * (3) Bind to address of local DOWN interface
4659 			 * (ipif_lookup_addr() looks up all interfaces
4660 			 * but we do not get here for UP interfaces
4661 			 * - case (2) above)
4662 			 */
4663 			/* LINTED - statement has no consequent */
4664 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4665 				/* The address exists */
4666 			} else if (CLASSD(src_addr)) {
4667 				error = 0;
4668 				if (src_ire != NULL)
4669 					ire_refrele(src_ire);
4670 				/*
4671 				 * (5) bind to multicast address.
4672 				 * Fake out the IRE returned to upper
4673 				 * layer to be a broadcast IRE.
4674 				 */
4675 				src_ire = ire_ctable_lookup(
4676 				    INADDR_BROADCAST, INADDR_ANY,
4677 				    IRE_BROADCAST, NULL, zoneid, NULL,
4678 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4679 				    ipst);
4680 				if (src_ire == NULL || !ire_requested)
4681 					error = EADDRNOTAVAIL;
4682 			} else {
4683 				/*
4684 				 * Not a valid address for bind
4685 				 */
4686 				error = EADDRNOTAVAIL;
4687 			}
4688 		}
4689 		if (error) {
4690 			/* Red Alert!  Attempting to be a bogon! */
4691 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4692 			    ntohl(src_addr)));
4693 			goto bad_addr;
4694 		}
4695 	}
4696 
4697 	/*
4698 	 * Allow setting new policies. For example, disconnects come
4699 	 * down as ipa_t bind. As we would have set conn_policy_cached
4700 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4701 	 * can change after the disconnect.
4702 	 */
4703 	connp->conn_policy_cached = B_FALSE;
4704 
4705 	/*
4706 	 * If not fanout_insert this was just an address verification
4707 	 */
4708 	if (fanout_insert) {
4709 		/*
4710 		 * The addresses have been verified. Time to insert in
4711 		 * the correct fanout list.
4712 		 */
4713 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4714 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4715 		connp->conn_lport = lport;
4716 		connp->conn_fport = 0;
4717 		/*
4718 		 * Do we need to add a check to reject Multicast packets
4719 		 */
4720 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4721 	}
4722 
4723 	if (error == 0) {
4724 		if (ire_requested) {
4725 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4726 				error = -1;
4727 				/* Falls through to bad_addr */
4728 			}
4729 		} else if (ipsec_policy_set) {
4730 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4731 				error = -1;
4732 				/* Falls through to bad_addr */
4733 			}
4734 		}
4735 	}
4736 bad_addr:
4737 	if (error != 0) {
4738 		if (connp->conn_anon_port) {
4739 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4740 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4741 			    B_FALSE);
4742 		}
4743 		connp->conn_mlp_type = mlptSingle;
4744 	}
4745 	if (src_ire != NULL)
4746 		IRE_REFRELE(src_ire);
4747 	return (error);
4748 }
4749 
4750 int
4751 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4752     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4753 {
4754 	int error;
4755 	mblk_t	*mp = NULL;
4756 	boolean_t ire_requested;
4757 
4758 	if (ire_mpp)
4759 		mp = *ire_mpp;
4760 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4761 
4762 	ASSERT(!connp->conn_af_isv6);
4763 	connp->conn_pkt_isv6 = B_FALSE;
4764 	connp->conn_ulp = protocol;
4765 
4766 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4767 	    fanout_insert);
4768 	if (error == 0) {
4769 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4770 		    ire_requested);
4771 	} else if (error < 0) {
4772 		error = -TBADADDR;
4773 	}
4774 	return (error);
4775 }
4776 
4777 /*
4778  * Verify that both the source and destination addresses
4779  * are valid.  If verify_dst is false, then the destination address may be
4780  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4781  * destination reachability, while tunnels do not.
4782  * Note that we allow connect to broadcast and multicast
4783  * addresses when ire_requested is set. Thus the ULP
4784  * has to check for IRE_BROADCAST and multicast.
4785  *
4786  * Returns zero if ok.
4787  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4788  * (for use with TSYSERR reply).
4789  *
4790  * Note: lport and fport are in network byte order.
4791  */
4792 int
4793 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4794     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4795     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4796 {
4797 
4798 	ire_t		*src_ire;
4799 	ire_t		*dst_ire;
4800 	int		error = 0;
4801 	ire_t		*sire = NULL;
4802 	ire_t		*md_dst_ire = NULL;
4803 	ire_t		*lso_dst_ire = NULL;
4804 	ill_t		*ill = NULL;
4805 	zoneid_t	zoneid;
4806 	ipaddr_t	src_addr = *src_addrp;
4807 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4808 	mblk_t		*mp = NULL;
4809 	boolean_t	ire_requested = B_FALSE;
4810 	boolean_t	ipsec_policy_set = B_FALSE;
4811 	ts_label_t	*tsl = NULL;
4812 
4813 	if (mpp)
4814 		mp = *mpp;
4815 
4816 	if (mp != NULL) {
4817 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4818 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4819 	}
4820 	if (cr != NULL)
4821 		tsl = crgetlabel(cr);
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 	if (CLASSD(dst_addr)) {
4833 		/* Pick up an IRE_BROADCAST */
4834 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4835 		    NULL, zoneid, tsl,
4836 		    (MATCH_IRE_RECURSIVE |
4837 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4838 		    MATCH_IRE_SECATTR), ipst);
4839 	} else {
4840 		/*
4841 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4842 		 * and onlink ipif is not found set ENETUNREACH error.
4843 		 */
4844 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4845 			ipif_t *ipif;
4846 
4847 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4848 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4849 			if (ipif == NULL) {
4850 				error = ENETUNREACH;
4851 				goto bad_addr;
4852 			}
4853 			ipif_refrele(ipif);
4854 		}
4855 
4856 		if (connp->conn_nexthop_set) {
4857 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4858 			    0, 0, NULL, NULL, zoneid, tsl,
4859 			    MATCH_IRE_SECATTR, ipst);
4860 		} else {
4861 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4862 			    &sire, zoneid, tsl,
4863 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4864 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4865 			    MATCH_IRE_SECATTR), ipst);
4866 		}
4867 	}
4868 	/*
4869 	 * dst_ire can't be a broadcast when not ire_requested.
4870 	 * We also prevent ire's with src address INADDR_ANY to
4871 	 * be used, which are created temporarily for
4872 	 * sending out packets from endpoints that have
4873 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4874 	 * reachable.  If verify_dst is false, the destination needn't be
4875 	 * reachable.
4876 	 *
4877 	 * If we match on a reject or black hole, then we've got a
4878 	 * local failure.  May as well fail out the connect() attempt,
4879 	 * since it's never going to succeed.
4880 	 */
4881 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4882 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4883 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4884 		/*
4885 		 * If we're verifying destination reachability, we always want
4886 		 * to complain here.
4887 		 *
4888 		 * If we're not verifying destination reachability but the
4889 		 * destination has a route, we still want to fail on the
4890 		 * temporary address and broadcast address tests.
4891 		 */
4892 		if (verify_dst || (dst_ire != NULL)) {
4893 			if (ip_debug > 2) {
4894 				pr_addr_dbg("ip_bind_connected_v4:"
4895 				    "bad connected dst %s\n",
4896 				    AF_INET, &dst_addr);
4897 			}
4898 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4899 				error = ENETUNREACH;
4900 			else
4901 				error = EHOSTUNREACH;
4902 			goto bad_addr;
4903 		}
4904 	}
4905 
4906 	/*
4907 	 * We now know that routing will allow us to reach the destination.
4908 	 * Check whether Trusted Solaris policy allows communication with this
4909 	 * host, and pretend that the destination is unreachable if not.
4910 	 *
4911 	 * This is never a problem for TCP, since that transport is known to
4912 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4913 	 * handling.  If the remote is unreachable, it will be detected at that
4914 	 * point, so there's no reason to check it here.
4915 	 *
4916 	 * Note that for sendto (and other datagram-oriented friends), this
4917 	 * check is done as part of the data path label computation instead.
4918 	 * The check here is just to make non-TCP connect() report the right
4919 	 * error.
4920 	 */
4921 	if (dst_ire != NULL && is_system_labeled() &&
4922 	    !IPCL_IS_TCP(connp) &&
4923 	    tsol_compute_label(cr, dst_addr, NULL,
4924 	    connp->conn_mac_exempt, ipst) != 0) {
4925 		error = EHOSTUNREACH;
4926 		if (ip_debug > 2) {
4927 			pr_addr_dbg("ip_bind_connected_v4:"
4928 			    " no label for dst %s\n",
4929 			    AF_INET, &dst_addr);
4930 		}
4931 		goto bad_addr;
4932 	}
4933 
4934 	/*
4935 	 * If the app does a connect(), it means that it will most likely
4936 	 * send more than 1 packet to the destination.  It makes sense
4937 	 * to clear the temporary flag.
4938 	 */
4939 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4940 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4941 		irb_t *irb = dst_ire->ire_bucket;
4942 
4943 		rw_enter(&irb->irb_lock, RW_WRITER);
4944 		/*
4945 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4946 		 * the lock to guarantee irb_tmp_ire_cnt.
4947 		 */
4948 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4949 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4950 			irb->irb_tmp_ire_cnt--;
4951 		}
4952 		rw_exit(&irb->irb_lock);
4953 	}
4954 
4955 	/*
4956 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4957 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4958 	 * eligibility tests for passive connects are handled separately
4959 	 * through tcp_adapt_ire().  We do this before the source address
4960 	 * selection, because dst_ire may change after a call to
4961 	 * ipif_select_source().  This is a best-effort check, as the
4962 	 * packet for this connection may not actually go through
4963 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4964 	 * calling ip_newroute().  This is why we further check on the
4965 	 * IRE during LSO/Multidata packet transmission in
4966 	 * tcp_lsosend()/tcp_multisend().
4967 	 */
4968 	if (!ipsec_policy_set && dst_ire != NULL &&
4969 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4970 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4971 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4972 			lso_dst_ire = dst_ire;
4973 			IRE_REFHOLD(lso_dst_ire);
4974 		} else if (ipst->ips_ip_multidata_outbound &&
4975 		    ILL_MDT_CAPABLE(ill)) {
4976 			md_dst_ire = dst_ire;
4977 			IRE_REFHOLD(md_dst_ire);
4978 		}
4979 	}
4980 
4981 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4982 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4983 		/*
4984 		 * If the IRE belongs to a different zone, look for a matching
4985 		 * route in the forwarding table and use the source address from
4986 		 * that route.
4987 		 */
4988 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4989 		    zoneid, 0, NULL,
4990 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4991 		    MATCH_IRE_RJ_BHOLE, ipst);
4992 		if (src_ire == NULL) {
4993 			error = EHOSTUNREACH;
4994 			goto bad_addr;
4995 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4996 			if (!(src_ire->ire_type & IRE_HOST))
4997 				error = ENETUNREACH;
4998 			else
4999 				error = EHOSTUNREACH;
5000 			goto bad_addr;
5001 		}
5002 		if (src_addr == INADDR_ANY)
5003 			src_addr = src_ire->ire_src_addr;
5004 		ire_refrele(src_ire);
5005 		src_ire = NULL;
5006 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5007 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5008 			src_addr = sire->ire_src_addr;
5009 			ire_refrele(dst_ire);
5010 			dst_ire = sire;
5011 			sire = NULL;
5012 		} else {
5013 			/*
5014 			 * Pick a source address so that a proper inbound
5015 			 * load spreading would happen.
5016 			 */
5017 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5018 			ipif_t *src_ipif = NULL;
5019 			ire_t *ipif_ire;
5020 
5021 			/*
5022 			 * Supply a local source address such that inbound
5023 			 * load spreading happens.
5024 			 *
5025 			 * Determine the best source address on this ill for
5026 			 * the destination.
5027 			 *
5028 			 * 1) For broadcast, we should return a broadcast ire
5029 			 *    found above so that upper layers know that the
5030 			 *    destination address is a broadcast address.
5031 			 *
5032 			 * 2) If the ipif is DEPRECATED, select a better
5033 			 *    source address.  Similarly, if the ipif is on
5034 			 *    the IPMP meta-interface, pick a source address
5035 			 *    at random to improve inbound load spreading.
5036 			 *
5037 			 * 3) If the outgoing interface is part of a usesrc
5038 			 *    group, then try selecting a source address from
5039 			 *    the usesrc ILL.
5040 			 */
5041 			if ((dst_ire->ire_zoneid != zoneid &&
5042 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5043 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5044 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5045 			    (IS_IPMP(ire_ill) ||
5046 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5047 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5048 				/*
5049 				 * If the destination is reachable via a
5050 				 * given gateway, the selected source address
5051 				 * should be in the same subnet as the gateway.
5052 				 * Otherwise, the destination is not reachable.
5053 				 *
5054 				 * If there are no interfaces on the same subnet
5055 				 * as the destination, ipif_select_source gives
5056 				 * first non-deprecated interface which might be
5057 				 * on a different subnet than the gateway.
5058 				 * This is not desirable. Hence pass the dst_ire
5059 				 * source address to ipif_select_source.
5060 				 * It is sure that the destination is reachable
5061 				 * with the dst_ire source address subnet.
5062 				 * So passing dst_ire source address to
5063 				 * ipif_select_source will make sure that the
5064 				 * selected source will be on the same subnet
5065 				 * as dst_ire source address.
5066 				 */
5067 				ipaddr_t saddr =
5068 				    dst_ire->ire_ipif->ipif_src_addr;
5069 				src_ipif = ipif_select_source(ire_ill,
5070 				    saddr, zoneid);
5071 				if (src_ipif != NULL) {
5072 					if (IS_VNI(src_ipif->ipif_ill)) {
5073 						/*
5074 						 * For VNI there is no
5075 						 * interface route
5076 						 */
5077 						src_addr =
5078 						    src_ipif->ipif_src_addr;
5079 					} else {
5080 						ipif_ire =
5081 						    ipif_to_ire(src_ipif);
5082 						if (ipif_ire != NULL) {
5083 							IRE_REFRELE(dst_ire);
5084 							dst_ire = ipif_ire;
5085 						}
5086 						src_addr =
5087 						    dst_ire->ire_src_addr;
5088 					}
5089 					ipif_refrele(src_ipif);
5090 				} else {
5091 					src_addr = dst_ire->ire_src_addr;
5092 				}
5093 			} else {
5094 				src_addr = dst_ire->ire_src_addr;
5095 			}
5096 		}
5097 	}
5098 
5099 	/*
5100 	 * We do ire_route_lookup() here (and not
5101 	 * interface lookup as we assert that
5102 	 * src_addr should only come from an
5103 	 * UP interface for hard binding.
5104 	 */
5105 	ASSERT(src_ire == NULL);
5106 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5107 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5108 	/* src_ire must be a local|loopback */
5109 	if (!IRE_IS_LOCAL(src_ire)) {
5110 		if (ip_debug > 2) {
5111 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5112 			    "src %s\n", AF_INET, &src_addr);
5113 		}
5114 		error = EADDRNOTAVAIL;
5115 		goto bad_addr;
5116 	}
5117 
5118 	/*
5119 	 * If the source address is a loopback address, the
5120 	 * destination had best be local or multicast.
5121 	 * The transports that can't handle multicast will reject
5122 	 * those addresses.
5123 	 */
5124 	if (src_ire->ire_type == IRE_LOOPBACK &&
5125 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5126 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5127 		error = -1;
5128 		goto bad_addr;
5129 	}
5130 
5131 	/*
5132 	 * Allow setting new policies. For example, disconnects come
5133 	 * down as ipa_t bind. As we would have set conn_policy_cached
5134 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5135 	 * can change after the disconnect.
5136 	 */
5137 	connp->conn_policy_cached = B_FALSE;
5138 
5139 	/*
5140 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5141 	 * can handle their passed-in conn's.
5142 	 */
5143 
5144 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5145 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5146 	connp->conn_lport = lport;
5147 	connp->conn_fport = fport;
5148 	*src_addrp = src_addr;
5149 
5150 	ASSERT(!(ipsec_policy_set && ire_requested));
5151 	if (ire_requested) {
5152 		iulp_t *ulp_info = NULL;
5153 
5154 		/*
5155 		 * Note that sire will not be NULL if this is an off-link
5156 		 * connection and there is not cache for that dest yet.
5157 		 *
5158 		 * XXX Because of an existing bug, if there are multiple
5159 		 * default routes, the IRE returned now may not be the actual
5160 		 * default route used (default routes are chosen in a
5161 		 * round robin fashion).  So if the metrics for different
5162 		 * default routes are different, we may return the wrong
5163 		 * metrics.  This will not be a problem if the existing
5164 		 * bug is fixed.
5165 		 */
5166 		if (sire != NULL) {
5167 			ulp_info = &(sire->ire_uinfo);
5168 		}
5169 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5170 			error = -1;
5171 			goto bad_addr;
5172 		}
5173 		mp = *mpp;
5174 	} else if (ipsec_policy_set) {
5175 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5176 			error = -1;
5177 			goto bad_addr;
5178 		}
5179 	}
5180 
5181 	/*
5182 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5183 	 * we'll cache that.  If we don't, we'll inherit global policy.
5184 	 *
5185 	 * We can't insert until the conn reflects the policy. Note that
5186 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5187 	 * connections where we don't have a policy. This is to prevent
5188 	 * global policy lookups in the inbound path.
5189 	 *
5190 	 * If we insert before we set conn_policy_cached,
5191 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5192 	 * because global policy cound be non-empty. We normally call
5193 	 * ipsec_check_policy() for conn_policy_cached connections only if
5194 	 * ipc_in_enforce_policy is set. But in this case,
5195 	 * conn_policy_cached can get set anytime since we made the
5196 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5197 	 * called, which will make the above assumption false.  Thus, we
5198 	 * need to insert after we set conn_policy_cached.
5199 	 */
5200 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5201 		goto bad_addr;
5202 
5203 	if (fanout_insert) {
5204 		/*
5205 		 * The addresses have been verified. Time to insert in
5206 		 * the correct fanout list.
5207 		 */
5208 		error = ipcl_conn_insert(connp, protocol, src_addr,
5209 		    dst_addr, connp->conn_ports);
5210 	}
5211 
5212 	if (error == 0) {
5213 		connp->conn_fully_bound = B_TRUE;
5214 		/*
5215 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5216 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5217 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5218 		 * ip_xxinfo_return(), which performs further checks
5219 		 * against them and upon success, returns the LSO/MDT info
5220 		 * mblk which we will attach to the bind acknowledgment.
5221 		 */
5222 		if (lso_dst_ire != NULL) {
5223 			mblk_t *lsoinfo_mp;
5224 
5225 			ASSERT(ill->ill_lso_capab != NULL);
5226 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5227 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5228 				if (mp == NULL) {
5229 					*mpp = lsoinfo_mp;
5230 				} else {
5231 					linkb(mp, lsoinfo_mp);
5232 				}
5233 			}
5234 		} else if (md_dst_ire != NULL) {
5235 			mblk_t *mdinfo_mp;
5236 
5237 			ASSERT(ill->ill_mdt_capab != NULL);
5238 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5239 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5240 				if (mp == NULL) {
5241 					*mpp = mdinfo_mp;
5242 				} else {
5243 					linkb(mp, mdinfo_mp);
5244 				}
5245 			}
5246 		}
5247 	}
5248 bad_addr:
5249 	if (ipsec_policy_set) {
5250 		ASSERT(mp != NULL);
5251 		freeb(mp);
5252 		/*
5253 		 * As of now assume that nothing else accompanies
5254 		 * IPSEC_POLICY_SET.
5255 		 */
5256 		*mpp = NULL;
5257 	}
5258 	if (src_ire != NULL)
5259 		IRE_REFRELE(src_ire);
5260 	if (dst_ire != NULL)
5261 		IRE_REFRELE(dst_ire);
5262 	if (sire != NULL)
5263 		IRE_REFRELE(sire);
5264 	if (md_dst_ire != NULL)
5265 		IRE_REFRELE(md_dst_ire);
5266 	if (lso_dst_ire != NULL)
5267 		IRE_REFRELE(lso_dst_ire);
5268 	return (error);
5269 }
5270 
5271 int
5272 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5273     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5274     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5275 {
5276 	int error;
5277 	mblk_t	*mp = NULL;
5278 	boolean_t ire_requested;
5279 
5280 	if (ire_mpp)
5281 		mp = *ire_mpp;
5282 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5283 
5284 	ASSERT(!connp->conn_af_isv6);
5285 	connp->conn_pkt_isv6 = B_FALSE;
5286 	connp->conn_ulp = protocol;
5287 
5288 	/* For raw socket, the local port is not set. */
5289 	if (lport == 0)
5290 		lport = connp->conn_lport;
5291 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5292 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5293 	if (error == 0) {
5294 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5295 		    ire_requested);
5296 	} else if (error < 0) {
5297 		error = -TBADADDR;
5298 	}
5299 	return (error);
5300 }
5301 
5302 /*
5303  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5304  * Prefers dst_ire over src_ire.
5305  */
5306 static boolean_t
5307 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5308 {
5309 	mblk_t	*mp = *mpp;
5310 	ire_t	*ret_ire;
5311 
5312 	ASSERT(mp != NULL);
5313 
5314 	if (ire != NULL) {
5315 		/*
5316 		 * mp initialized above to IRE_DB_REQ_TYPE
5317 		 * appended mblk. Its <upper protocol>'s
5318 		 * job to make sure there is room.
5319 		 */
5320 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5321 			return (B_FALSE);
5322 
5323 		mp->b_datap->db_type = IRE_DB_TYPE;
5324 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5325 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5326 		ret_ire = (ire_t *)mp->b_rptr;
5327 		/*
5328 		 * Pass the latest setting of the ip_path_mtu_discovery and
5329 		 * copy the ulp info if any.
5330 		 */
5331 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5332 		    IPH_DF : 0;
5333 		if (ulp_info != NULL) {
5334 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5335 			    sizeof (iulp_t));
5336 		}
5337 		ret_ire->ire_mp = mp;
5338 	} else {
5339 		/*
5340 		 * No IRE was found. Remove IRE mblk.
5341 		 */
5342 		*mpp = mp->b_cont;
5343 		freeb(mp);
5344 	}
5345 	return (B_TRUE);
5346 }
5347 
5348 /*
5349  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5350  * the final piece where we don't.  Return a pointer to the first mblk in the
5351  * result, and update the pointer to the next mblk to chew on.  If anything
5352  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5353  * NULL pointer.
5354  */
5355 mblk_t *
5356 ip_carve_mp(mblk_t **mpp, ssize_t len)
5357 {
5358 	mblk_t	*mp0;
5359 	mblk_t	*mp1;
5360 	mblk_t	*mp2;
5361 
5362 	if (!len || !mpp || !(mp0 = *mpp))
5363 		return (NULL);
5364 	/* If we aren't going to consume the first mblk, we need a dup. */
5365 	if (mp0->b_wptr - mp0->b_rptr > len) {
5366 		mp1 = dupb(mp0);
5367 		if (mp1) {
5368 			/* Partition the data between the two mblks. */
5369 			mp1->b_wptr = mp1->b_rptr + len;
5370 			mp0->b_rptr = mp1->b_wptr;
5371 			/*
5372 			 * after adjustments if mblk not consumed is now
5373 			 * unaligned, try to align it. If this fails free
5374 			 * all messages and let upper layer recover.
5375 			 */
5376 			if (!OK_32PTR(mp0->b_rptr)) {
5377 				if (!pullupmsg(mp0, -1)) {
5378 					freemsg(mp0);
5379 					freemsg(mp1);
5380 					*mpp = NULL;
5381 					return (NULL);
5382 				}
5383 			}
5384 		}
5385 		return (mp1);
5386 	}
5387 	/* Eat through as many mblks as we need to get len bytes. */
5388 	len -= mp0->b_wptr - mp0->b_rptr;
5389 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5390 		if (mp2->b_wptr - mp2->b_rptr > len) {
5391 			/*
5392 			 * We won't consume the entire last mblk.  Like
5393 			 * above, dup and partition it.
5394 			 */
5395 			mp1->b_cont = dupb(mp2);
5396 			mp1 = mp1->b_cont;
5397 			if (!mp1) {
5398 				/*
5399 				 * Trouble.  Rather than go to a lot of
5400 				 * trouble to clean up, we free the messages.
5401 				 * This won't be any worse than losing it on
5402 				 * the wire.
5403 				 */
5404 				freemsg(mp0);
5405 				freemsg(mp2);
5406 				*mpp = NULL;
5407 				return (NULL);
5408 			}
5409 			mp1->b_wptr = mp1->b_rptr + len;
5410 			mp2->b_rptr = mp1->b_wptr;
5411 			/*
5412 			 * after adjustments if mblk not consumed is now
5413 			 * unaligned, try to align it. If this fails free
5414 			 * all messages and let upper layer recover.
5415 			 */
5416 			if (!OK_32PTR(mp2->b_rptr)) {
5417 				if (!pullupmsg(mp2, -1)) {
5418 					freemsg(mp0);
5419 					freemsg(mp2);
5420 					*mpp = NULL;
5421 					return (NULL);
5422 				}
5423 			}
5424 			*mpp = mp2;
5425 			return (mp0);
5426 		}
5427 		/* Decrement len by the amount we just got. */
5428 		len -= mp2->b_wptr - mp2->b_rptr;
5429 	}
5430 	/*
5431 	 * len should be reduced to zero now.  If not our caller has
5432 	 * screwed up.
5433 	 */
5434 	if (len) {
5435 		/* Shouldn't happen! */
5436 		freemsg(mp0);
5437 		*mpp = NULL;
5438 		return (NULL);
5439 	}
5440 	/*
5441 	 * We consumed up to exactly the end of an mblk.  Detach the part
5442 	 * we are returning from the rest of the chain.
5443 	 */
5444 	mp1->b_cont = NULL;
5445 	*mpp = mp2;
5446 	return (mp0);
5447 }
5448 
5449 /* The ill stream is being unplumbed. Called from ip_close */
5450 int
5451 ip_modclose(ill_t *ill)
5452 {
5453 	boolean_t success;
5454 	ipsq_t	*ipsq;
5455 	ipif_t	*ipif;
5456 	queue_t	*q = ill->ill_rq;
5457 	ip_stack_t	*ipst = ill->ill_ipst;
5458 	int	i;
5459 
5460 	/*
5461 	 * The punlink prior to this may have initiated a capability
5462 	 * negotiation. But ipsq_enter will block until that finishes or
5463 	 * times out.
5464 	 */
5465 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5466 
5467 	/*
5468 	 * Open/close/push/pop is guaranteed to be single threaded
5469 	 * per stream by STREAMS. FS guarantees that all references
5470 	 * from top are gone before close is called. So there can't
5471 	 * be another close thread that has set CONDEMNED on this ill.
5472 	 * and cause ipsq_enter to return failure.
5473 	 */
5474 	ASSERT(success);
5475 	ipsq = ill->ill_phyint->phyint_ipsq;
5476 
5477 	/*
5478 	 * Mark it condemned. No new reference will be made to this ill.
5479 	 * Lookup functions will return an error. Threads that try to
5480 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5481 	 * that the refcnt will drop down to zero.
5482 	 */
5483 	mutex_enter(&ill->ill_lock);
5484 	ill->ill_state_flags |= ILL_CONDEMNED;
5485 	for (ipif = ill->ill_ipif; ipif != NULL;
5486 	    ipif = ipif->ipif_next) {
5487 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5488 	}
5489 	/*
5490 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5491 	 * returns  error if ILL_CONDEMNED is set
5492 	 */
5493 	cv_broadcast(&ill->ill_cv);
5494 	mutex_exit(&ill->ill_lock);
5495 
5496 	/*
5497 	 * Send all the deferred DLPI messages downstream which came in
5498 	 * during the small window right before ipsq_enter(). We do this
5499 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5500 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5501 	 */
5502 	ill_dlpi_send_deferred(ill);
5503 
5504 	/*
5505 	 * Shut down fragmentation reassembly.
5506 	 * ill_frag_timer won't start a timer again.
5507 	 * Now cancel any existing timer
5508 	 */
5509 	(void) untimeout(ill->ill_frag_timer_id);
5510 	(void) ill_frag_timeout(ill, 0);
5511 
5512 	/*
5513 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5514 	 * this ill. Then wait for the refcnts to drop to zero.
5515 	 * ill_is_freeable checks whether the ill is really quiescent.
5516 	 * Then make sure that threads that are waiting to enter the
5517 	 * ipsq have seen the error returned by ipsq_enter and have
5518 	 * gone away. Then we call ill_delete_tail which does the
5519 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5520 	 */
5521 	ill_delete(ill);
5522 	mutex_enter(&ill->ill_lock);
5523 	while (!ill_is_freeable(ill))
5524 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5525 	while (ill->ill_waiters)
5526 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5527 
5528 	mutex_exit(&ill->ill_lock);
5529 
5530 	/*
5531 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5532 	 * it held until the end of the function since the cleanup
5533 	 * below needs to be able to use the ip_stack_t.
5534 	 */
5535 	netstack_hold(ipst->ips_netstack);
5536 
5537 	/* qprocsoff is done via ill_delete_tail */
5538 	ill_delete_tail(ill);
5539 	ASSERT(ill->ill_ipst == NULL);
5540 
5541 	/*
5542 	 * Walk through all upper (conn) streams and qenable
5543 	 * those that have queued data.
5544 	 * close synchronization needs this to
5545 	 * be done to ensure that all upper layers blocked
5546 	 * due to flow control to the closing device
5547 	 * get unblocked.
5548 	 */
5549 	ip1dbg(("ip_wsrv: walking\n"));
5550 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5551 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5552 	}
5553 
5554 	mutex_enter(&ipst->ips_ip_mi_lock);
5555 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5556 	mutex_exit(&ipst->ips_ip_mi_lock);
5557 
5558 	/*
5559 	 * credp could be null if the open didn't succeed and ip_modopen
5560 	 * itself calls ip_close.
5561 	 */
5562 	if (ill->ill_credp != NULL)
5563 		crfree(ill->ill_credp);
5564 
5565 	/*
5566 	 * Now we are done with the module close pieces that
5567 	 * need the netstack_t.
5568 	 */
5569 	netstack_rele(ipst->ips_netstack);
5570 
5571 	mi_close_free((IDP)ill);
5572 	q->q_ptr = WR(q)->q_ptr = NULL;
5573 
5574 	ipsq_exit(ipsq);
5575 
5576 	return (0);
5577 }
5578 
5579 /*
5580  * This is called as part of close() for IP, UDP, ICMP, and RTS
5581  * in order to quiesce the conn.
5582  */
5583 void
5584 ip_quiesce_conn(conn_t *connp)
5585 {
5586 	boolean_t	drain_cleanup_reqd = B_FALSE;
5587 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5588 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5589 	ip_stack_t	*ipst;
5590 
5591 	ASSERT(!IPCL_IS_TCP(connp));
5592 	ipst = connp->conn_netstack->netstack_ip;
5593 
5594 	/*
5595 	 * Mark the conn as closing, and this conn must not be
5596 	 * inserted in future into any list. Eg. conn_drain_insert(),
5597 	 * won't insert this conn into the conn_drain_list.
5598 	 * Similarly ill_pending_mp_add() will not add any mp to
5599 	 * the pending mp list, after this conn has started closing.
5600 	 *
5601 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5602 	 * cannot get set henceforth.
5603 	 */
5604 	mutex_enter(&connp->conn_lock);
5605 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5606 	connp->conn_state_flags |= CONN_CLOSING;
5607 	if (connp->conn_idl != NULL)
5608 		drain_cleanup_reqd = B_TRUE;
5609 	if (connp->conn_oper_pending_ill != NULL)
5610 		conn_ioctl_cleanup_reqd = B_TRUE;
5611 	if (connp->conn_dhcpinit_ill != NULL) {
5612 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5613 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5614 		connp->conn_dhcpinit_ill = NULL;
5615 	}
5616 	if (connp->conn_ilg_inuse != 0)
5617 		ilg_cleanup_reqd = B_TRUE;
5618 	mutex_exit(&connp->conn_lock);
5619 
5620 	if (conn_ioctl_cleanup_reqd)
5621 		conn_ioctl_cleanup(connp);
5622 
5623 	if (is_system_labeled() && connp->conn_anon_port) {
5624 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5625 		    connp->conn_mlp_type, connp->conn_ulp,
5626 		    ntohs(connp->conn_lport), B_FALSE);
5627 		connp->conn_anon_port = 0;
5628 	}
5629 	connp->conn_mlp_type = mlptSingle;
5630 
5631 	/*
5632 	 * Remove this conn from any fanout list it is on.
5633 	 * and then wait for any threads currently operating
5634 	 * on this endpoint to finish
5635 	 */
5636 	ipcl_hash_remove(connp);
5637 
5638 	/*
5639 	 * Remove this conn from the drain list, and do
5640 	 * any other cleanup that may be required.
5641 	 * (Only non-tcp streams may have a non-null conn_idl.
5642 	 * TCP streams are never flow controlled, and
5643 	 * conn_idl will be null)
5644 	 */
5645 	if (drain_cleanup_reqd)
5646 		conn_drain_tail(connp, B_TRUE);
5647 
5648 	if (connp == ipst->ips_ip_g_mrouter)
5649 		(void) ip_mrouter_done(NULL, ipst);
5650 
5651 	if (ilg_cleanup_reqd)
5652 		ilg_delete_all(connp);
5653 
5654 	conn_delete_ire(connp, NULL);
5655 
5656 	/*
5657 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5658 	 * callers from write side can't be there now because close
5659 	 * is in progress. The only other caller is ipcl_walk
5660 	 * which checks for the condemned flag.
5661 	 */
5662 	mutex_enter(&connp->conn_lock);
5663 	connp->conn_state_flags |= CONN_CONDEMNED;
5664 	while (connp->conn_ref != 1)
5665 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5666 	connp->conn_state_flags |= CONN_QUIESCED;
5667 	mutex_exit(&connp->conn_lock);
5668 }
5669 
5670 /* ARGSUSED */
5671 int
5672 ip_close(queue_t *q, int flags)
5673 {
5674 	conn_t		*connp;
5675 
5676 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5677 
5678 	/*
5679 	 * Call the appropriate delete routine depending on whether this is
5680 	 * a module or device.
5681 	 */
5682 	if (WR(q)->q_next != NULL) {
5683 		/* This is a module close */
5684 		return (ip_modclose((ill_t *)q->q_ptr));
5685 	}
5686 
5687 	connp = q->q_ptr;
5688 	ip_quiesce_conn(connp);
5689 
5690 	qprocsoff(q);
5691 
5692 	/*
5693 	 * Now we are truly single threaded on this stream, and can
5694 	 * delete the things hanging off the connp, and finally the connp.
5695 	 * We removed this connp from the fanout list, it cannot be
5696 	 * accessed thru the fanouts, and we already waited for the
5697 	 * conn_ref to drop to 0. We are already in close, so
5698 	 * there cannot be any other thread from the top. qprocsoff
5699 	 * has completed, and service has completed or won't run in
5700 	 * future.
5701 	 */
5702 	ASSERT(connp->conn_ref == 1);
5703 
5704 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5705 
5706 	connp->conn_ref--;
5707 	ipcl_conn_destroy(connp);
5708 
5709 	q->q_ptr = WR(q)->q_ptr = NULL;
5710 	return (0);
5711 }
5712 
5713 /*
5714  * Wapper around putnext() so that ip_rts_request can merely use
5715  * conn_recv.
5716  */
5717 /*ARGSUSED2*/
5718 static void
5719 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5720 {
5721 	conn_t *connp = (conn_t *)arg1;
5722 
5723 	putnext(connp->conn_rq, mp);
5724 }
5725 
5726 /*
5727  * Called when the module is about to be unloaded
5728  */
5729 void
5730 ip_ddi_destroy(void)
5731 {
5732 	tnet_fini();
5733 
5734 	icmp_ddi_g_destroy();
5735 	rts_ddi_g_destroy();
5736 	udp_ddi_g_destroy();
5737 	sctp_ddi_g_destroy();
5738 	tcp_ddi_g_destroy();
5739 	ipsec_policy_g_destroy();
5740 	ipcl_g_destroy();
5741 	ip_net_g_destroy();
5742 	ip_ire_g_fini();
5743 	inet_minor_destroy(ip_minor_arena_sa);
5744 #if defined(_LP64)
5745 	inet_minor_destroy(ip_minor_arena_la);
5746 #endif
5747 
5748 #ifdef DEBUG
5749 	list_destroy(&ip_thread_list);
5750 	rw_destroy(&ip_thread_rwlock);
5751 	tsd_destroy(&ip_thread_data);
5752 #endif
5753 
5754 	netstack_unregister(NS_IP);
5755 }
5756 
5757 /*
5758  * First step in cleanup.
5759  */
5760 /* ARGSUSED */
5761 static void
5762 ip_stack_shutdown(netstackid_t stackid, void *arg)
5763 {
5764 	ip_stack_t *ipst = (ip_stack_t *)arg;
5765 
5766 #ifdef NS_DEBUG
5767 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5768 #endif
5769 
5770 	/* Get rid of loopback interfaces and their IREs */
5771 	ip_loopback_cleanup(ipst);
5772 
5773 	/*
5774 	 * The *_hook_shutdown()s start the process of notifying any
5775 	 * consumers that things are going away.... nothing is destroyed.
5776 	 */
5777 	ipv4_hook_shutdown(ipst);
5778 	ipv6_hook_shutdown(ipst);
5779 
5780 	mutex_enter(&ipst->ips_capab_taskq_lock);
5781 	ipst->ips_capab_taskq_quit = B_TRUE;
5782 	cv_signal(&ipst->ips_capab_taskq_cv);
5783 	mutex_exit(&ipst->ips_capab_taskq_lock);
5784 
5785 	mutex_enter(&ipst->ips_mrt_lock);
5786 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5787 	cv_signal(&ipst->ips_mrt_cv);
5788 	mutex_exit(&ipst->ips_mrt_lock);
5789 }
5790 
5791 /*
5792  * Free the IP stack instance.
5793  */
5794 static void
5795 ip_stack_fini(netstackid_t stackid, void *arg)
5796 {
5797 	ip_stack_t *ipst = (ip_stack_t *)arg;
5798 	int ret;
5799 
5800 #ifdef NS_DEBUG
5801 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5802 #endif
5803 	/*
5804 	 * At this point, all of the notifications that the events and
5805 	 * protocols are going away have been run, meaning that we can
5806 	 * now set about starting to clean things up.
5807 	 */
5808 	ipv4_hook_destroy(ipst);
5809 	ipv6_hook_destroy(ipst);
5810 	ip_net_destroy(ipst);
5811 
5812 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5813 	cv_destroy(&ipst->ips_capab_taskq_cv);
5814 	list_destroy(&ipst->ips_capab_taskq_list);
5815 
5816 	mutex_enter(&ipst->ips_mrt_lock);
5817 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5818 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5819 	mutex_destroy(&ipst->ips_mrt_lock);
5820 	cv_destroy(&ipst->ips_mrt_cv);
5821 	cv_destroy(&ipst->ips_mrt_done_cv);
5822 
5823 	ipmp_destroy(ipst);
5824 	rw_destroy(&ipst->ips_srcid_lock);
5825 
5826 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5827 	ipst->ips_ip_mibkp = NULL;
5828 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5829 	ipst->ips_icmp_mibkp = NULL;
5830 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5831 	ipst->ips_ip_kstat = NULL;
5832 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5833 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5834 	ipst->ips_ip6_kstat = NULL;
5835 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5836 
5837 	nd_free(&ipst->ips_ip_g_nd);
5838 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5839 	ipst->ips_param_arr = NULL;
5840 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5841 	ipst->ips_ndp_arr = NULL;
5842 
5843 	ip_mrouter_stack_destroy(ipst);
5844 
5845 	mutex_destroy(&ipst->ips_ip_mi_lock);
5846 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5847 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5848 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5849 
5850 	ret = untimeout(ipst->ips_igmp_timeout_id);
5851 	if (ret == -1) {
5852 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5853 	} else {
5854 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5855 		ipst->ips_igmp_timeout_id = 0;
5856 	}
5857 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5858 	if (ret == -1) {
5859 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5860 	} else {
5861 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5862 		ipst->ips_igmp_slowtimeout_id = 0;
5863 	}
5864 	ret = untimeout(ipst->ips_mld_timeout_id);
5865 	if (ret == -1) {
5866 		ASSERT(ipst->ips_mld_timeout_id == 0);
5867 	} else {
5868 		ASSERT(ipst->ips_mld_timeout_id != 0);
5869 		ipst->ips_mld_timeout_id = 0;
5870 	}
5871 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5872 	if (ret == -1) {
5873 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5874 	} else {
5875 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5876 		ipst->ips_mld_slowtimeout_id = 0;
5877 	}
5878 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5879 	if (ret == -1) {
5880 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5881 	} else {
5882 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5883 		ipst->ips_ip_ire_expire_id = 0;
5884 	}
5885 
5886 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5887 	mutex_destroy(&ipst->ips_mld_timer_lock);
5888 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5889 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5890 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5891 	rw_destroy(&ipst->ips_ill_g_lock);
5892 
5893 	ipobs_fini(ipst);
5894 	ip_ire_fini(ipst);
5895 	ip6_asp_free(ipst);
5896 	conn_drain_fini(ipst);
5897 	ipcl_destroy(ipst);
5898 
5899 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5900 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5901 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5902 	ipst->ips_ndp4 = NULL;
5903 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5904 	ipst->ips_ndp6 = NULL;
5905 
5906 	if (ipst->ips_loopback_ksp != NULL) {
5907 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5908 		ipst->ips_loopback_ksp = NULL;
5909 	}
5910 
5911 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5912 	ipst->ips_phyint_g_list = NULL;
5913 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5914 	ipst->ips_ill_g_heads = NULL;
5915 
5916 	ldi_ident_release(ipst->ips_ldi_ident);
5917 	kmem_free(ipst, sizeof (*ipst));
5918 }
5919 
5920 /*
5921  * This function is called from the TSD destructor, and is used to debug
5922  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5923  * details.
5924  */
5925 static void
5926 ip_thread_exit(void *phash)
5927 {
5928 	th_hash_t *thh = phash;
5929 
5930 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5931 	list_remove(&ip_thread_list, thh);
5932 	rw_exit(&ip_thread_rwlock);
5933 	mod_hash_destroy_hash(thh->thh_hash);
5934 	kmem_free(thh, sizeof (*thh));
5935 }
5936 
5937 /*
5938  * Called when the IP kernel module is loaded into the kernel
5939  */
5940 void
5941 ip_ddi_init(void)
5942 {
5943 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5944 
5945 	/*
5946 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5947 	 * initial devices: ip, ip6, tcp, tcp6.
5948 	 */
5949 	/*
5950 	 * If this is a 64-bit kernel, then create two separate arenas -
5951 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5952 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5953 	 */
5954 	ip_minor_arena_la = NULL;
5955 	ip_minor_arena_sa = NULL;
5956 #if defined(_LP64)
5957 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5958 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5959 		cmn_err(CE_PANIC,
5960 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5961 	}
5962 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5963 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5964 		cmn_err(CE_PANIC,
5965 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5966 	}
5967 #else
5968 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5969 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5970 		cmn_err(CE_PANIC,
5971 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5972 	}
5973 #endif
5974 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5975 
5976 	ipcl_g_init();
5977 	ip_ire_g_init();
5978 	ip_net_g_init();
5979 
5980 #ifdef DEBUG
5981 	tsd_create(&ip_thread_data, ip_thread_exit);
5982 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5983 	list_create(&ip_thread_list, sizeof (th_hash_t),
5984 	    offsetof(th_hash_t, thh_link));
5985 #endif
5986 
5987 	/*
5988 	 * We want to be informed each time a stack is created or
5989 	 * destroyed in the kernel, so we can maintain the
5990 	 * set of udp_stack_t's.
5991 	 */
5992 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5993 	    ip_stack_fini);
5994 
5995 	ipsec_policy_g_init();
5996 	tcp_ddi_g_init();
5997 	sctp_ddi_g_init();
5998 
5999 	tnet_init();
6000 
6001 	udp_ddi_g_init();
6002 	rts_ddi_g_init();
6003 	icmp_ddi_g_init();
6004 }
6005 
6006 /*
6007  * Initialize the IP stack instance.
6008  */
6009 static void *
6010 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6011 {
6012 	ip_stack_t	*ipst;
6013 	ipparam_t	*pa;
6014 	ipndp_t		*na;
6015 	major_t		major;
6016 
6017 #ifdef NS_DEBUG
6018 	printf("ip_stack_init(stack %d)\n", stackid);
6019 #endif
6020 
6021 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6022 	ipst->ips_netstack = ns;
6023 
6024 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6025 	    KM_SLEEP);
6026 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6027 	    KM_SLEEP);
6028 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6029 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6030 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6031 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6032 
6033 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6034 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6035 	ipst->ips_igmp_deferred_next = INFINITY;
6036 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6037 	ipst->ips_mld_deferred_next = INFINITY;
6038 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6039 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6040 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6041 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6042 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6043 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6044 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6045 
6046 	ipcl_init(ipst);
6047 	ip_ire_init(ipst);
6048 	ip6_asp_init(ipst);
6049 	ipif_init(ipst);
6050 	conn_drain_init(ipst);
6051 	ip_mrouter_stack_init(ipst);
6052 
6053 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6054 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6055 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
6056 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
6057 
6058 	ipst->ips_ip_multirt_log_interval = 1000;
6059 
6060 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6061 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6062 	ipst->ips_ill_index = 1;
6063 
6064 	ipst->ips_saved_ip_g_forward = -1;
6065 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6066 
6067 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6068 	ipst->ips_param_arr = pa;
6069 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6070 
6071 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6072 	ipst->ips_ndp_arr = na;
6073 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6074 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6075 	    (caddr_t)&ipst->ips_ip_g_forward;
6076 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6077 	    (caddr_t)&ipst->ips_ipv6_forward;
6078 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6079 	    "ip_cgtp_filter") == 0);
6080 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6081 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6082 
6083 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6084 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6085 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6086 
6087 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6088 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6089 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6090 	ipst->ips_ip6_kstat =
6091 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6092 
6093 	ipst->ips_ip_src_id = 1;
6094 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6095 
6096 	ipobs_init(ipst);
6097 	ip_net_init(ipst, ns);
6098 	ipv4_hook_init(ipst);
6099 	ipv6_hook_init(ipst);
6100 	ipmp_init(ipst);
6101 
6102 	/*
6103 	 * Create the taskq dispatcher thread and initialize related stuff.
6104 	 */
6105 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6106 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6107 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6108 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6109 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6110 	    offsetof(mblk_t, b_next));
6111 
6112 	/*
6113 	 * Create the mcast_restart_timers_thread() worker thread.
6114 	 */
6115 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6116 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6117 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6118 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6119 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6120 
6121 	major = mod_name_to_major(INET_NAME);
6122 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6123 	return (ipst);
6124 }
6125 
6126 /*
6127  * Allocate and initialize a DLPI template of the specified length.  (May be
6128  * called as writer.)
6129  */
6130 mblk_t *
6131 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6132 {
6133 	mblk_t	*mp;
6134 
6135 	mp = allocb(len, BPRI_MED);
6136 	if (!mp)
6137 		return (NULL);
6138 
6139 	/*
6140 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6141 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6142 	 * that other DLPI are M_PROTO.
6143 	 */
6144 	if (prim == DL_INFO_REQ) {
6145 		mp->b_datap->db_type = M_PCPROTO;
6146 	} else {
6147 		mp->b_datap->db_type = M_PROTO;
6148 	}
6149 
6150 	mp->b_wptr = mp->b_rptr + len;
6151 	bzero(mp->b_rptr, len);
6152 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6153 	return (mp);
6154 }
6155 
6156 /*
6157  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6158  */
6159 mblk_t *
6160 ip_dlnotify_alloc(uint_t notification, uint_t data)
6161 {
6162 	dl_notify_ind_t	*notifyp;
6163 	mblk_t		*mp;
6164 
6165 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6166 		return (NULL);
6167 
6168 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6169 	notifyp->dl_notification = notification;
6170 	notifyp->dl_data = data;
6171 	return (mp);
6172 }
6173 
6174 /*
6175  * Debug formatting routine.  Returns a character string representation of the
6176  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6177  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6178  *
6179  * Once the ndd table-printing interfaces are removed, this can be changed to
6180  * standard dotted-decimal form.
6181  */
6182 char *
6183 ip_dot_addr(ipaddr_t addr, char *buf)
6184 {
6185 	uint8_t *ap = (uint8_t *)&addr;
6186 
6187 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6188 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6189 	return (buf);
6190 }
6191 
6192 /*
6193  * Write the given MAC address as a printable string in the usual colon-
6194  * separated format.
6195  */
6196 const char *
6197 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6198 {
6199 	char *bp;
6200 
6201 	if (alen == 0 || buflen < 4)
6202 		return ("?");
6203 	bp = buf;
6204 	for (;;) {
6205 		/*
6206 		 * If there are more MAC address bytes available, but we won't
6207 		 * have any room to print them, then add "..." to the string
6208 		 * instead.  See below for the 'magic number' explanation.
6209 		 */
6210 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6211 			(void) strcpy(bp, "...");
6212 			break;
6213 		}
6214 		(void) sprintf(bp, "%02x", *addr++);
6215 		bp += 2;
6216 		if (--alen == 0)
6217 			break;
6218 		*bp++ = ':';
6219 		buflen -= 3;
6220 		/*
6221 		 * At this point, based on the first 'if' statement above,
6222 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6223 		 * buflen >= 4.  The first case leaves room for the final "xx"
6224 		 * number and trailing NUL byte.  The second leaves room for at
6225 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6226 		 * that statement.
6227 		 */
6228 	}
6229 	return (buf);
6230 }
6231 
6232 /*
6233  * Send an ICMP error after patching up the packet appropriately.  Returns
6234  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6235  */
6236 static boolean_t
6237 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6238     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6239     zoneid_t zoneid, ip_stack_t *ipst)
6240 {
6241 	ipha_t *ipha;
6242 	mblk_t *first_mp;
6243 	boolean_t secure;
6244 	unsigned char db_type;
6245 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6246 
6247 	first_mp = mp;
6248 	if (mctl_present) {
6249 		mp = mp->b_cont;
6250 		secure = ipsec_in_is_secure(first_mp);
6251 		ASSERT(mp != NULL);
6252 	} else {
6253 		/*
6254 		 * If this is an ICMP error being reported - which goes
6255 		 * up as M_CTLs, we need to convert them to M_DATA till
6256 		 * we finish checking with global policy because
6257 		 * ipsec_check_global_policy() assumes M_DATA as clear
6258 		 * and M_CTL as secure.
6259 		 */
6260 		db_type = DB_TYPE(mp);
6261 		DB_TYPE(mp) = M_DATA;
6262 		secure = B_FALSE;
6263 	}
6264 	/*
6265 	 * We are generating an icmp error for some inbound packet.
6266 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6267 	 * Before we generate an error, check with global policy
6268 	 * to see whether this is allowed to enter the system. As
6269 	 * there is no "conn", we are checking with global policy.
6270 	 */
6271 	ipha = (ipha_t *)mp->b_rptr;
6272 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6273 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6274 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6275 		if (first_mp == NULL)
6276 			return (B_FALSE);
6277 	}
6278 
6279 	if (!mctl_present)
6280 		DB_TYPE(mp) = db_type;
6281 
6282 	if (flags & IP_FF_SEND_ICMP) {
6283 		if (flags & IP_FF_HDR_COMPLETE) {
6284 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6285 				freemsg(first_mp);
6286 				return (B_TRUE);
6287 			}
6288 		}
6289 		if (flags & IP_FF_CKSUM) {
6290 			/*
6291 			 * Have to correct checksum since
6292 			 * the packet might have been
6293 			 * fragmented and the reassembly code in ip_rput
6294 			 * does not restore the IP checksum.
6295 			 */
6296 			ipha->ipha_hdr_checksum = 0;
6297 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6298 		}
6299 		switch (icmp_type) {
6300 		case ICMP_DEST_UNREACHABLE:
6301 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6302 			    ipst);
6303 			break;
6304 		default:
6305 			freemsg(first_mp);
6306 			break;
6307 		}
6308 	} else {
6309 		freemsg(first_mp);
6310 		return (B_FALSE);
6311 	}
6312 
6313 	return (B_TRUE);
6314 }
6315 
6316 /*
6317  * Used to send an ICMP error message when a packet is received for
6318  * a protocol that is not supported. The mblk passed as argument
6319  * is consumed by this function.
6320  */
6321 void
6322 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6323     ip_stack_t *ipst)
6324 {
6325 	mblk_t *mp;
6326 	ipha_t *ipha;
6327 	ill_t *ill;
6328 	ipsec_in_t *ii;
6329 
6330 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6331 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6332 
6333 	mp = ipsec_mp->b_cont;
6334 	ipsec_mp->b_cont = NULL;
6335 	ipha = (ipha_t *)mp->b_rptr;
6336 	/* Get ill from index in ipsec_in_t. */
6337 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6338 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6339 	    ipst);
6340 	if (ill != NULL) {
6341 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6342 			if (ip_fanout_send_icmp(q, mp, flags,
6343 			    ICMP_DEST_UNREACHABLE,
6344 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6345 				BUMP_MIB(ill->ill_ip_mib,
6346 				    ipIfStatsInUnknownProtos);
6347 			}
6348 		} else {
6349 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6350 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6351 			    0, B_FALSE, zoneid, ipst)) {
6352 				BUMP_MIB(ill->ill_ip_mib,
6353 				    ipIfStatsInUnknownProtos);
6354 			}
6355 		}
6356 		ill_refrele(ill);
6357 	} else { /* re-link for the freemsg() below. */
6358 		ipsec_mp->b_cont = mp;
6359 	}
6360 
6361 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6362 	freemsg(ipsec_mp);
6363 }
6364 
6365 /*
6366  * See if the inbound datagram has had IPsec processing applied to it.
6367  */
6368 boolean_t
6369 ipsec_in_is_secure(mblk_t *ipsec_mp)
6370 {
6371 	ipsec_in_t *ii;
6372 
6373 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6374 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6375 
6376 	if (ii->ipsec_in_loopback) {
6377 		return (ii->ipsec_in_secure);
6378 	} else {
6379 		return (ii->ipsec_in_ah_sa != NULL ||
6380 		    ii->ipsec_in_esp_sa != NULL ||
6381 		    ii->ipsec_in_decaps);
6382 	}
6383 }
6384 
6385 /*
6386  * Handle protocols with which IP is less intimate.  There
6387  * can be more than one stream bound to a particular
6388  * protocol.  When this is the case, normally each one gets a copy
6389  * of any incoming packets.
6390  *
6391  * IPsec NOTE :
6392  *
6393  * Don't allow a secure packet going up a non-secure connection.
6394  * We don't allow this because
6395  *
6396  * 1) Reply might go out in clear which will be dropped at
6397  *    the sending side.
6398  * 2) If the reply goes out in clear it will give the
6399  *    adversary enough information for getting the key in
6400  *    most of the cases.
6401  *
6402  * Moreover getting a secure packet when we expect clear
6403  * implies that SA's were added without checking for
6404  * policy on both ends. This should not happen once ISAKMP
6405  * is used to negotiate SAs as SAs will be added only after
6406  * verifying the policy.
6407  *
6408  * NOTE : If the packet was tunneled and not multicast we only send
6409  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6410  * back to delivering packets to AF_INET6 raw sockets.
6411  *
6412  * IPQoS Notes:
6413  * Once we have determined the client, invoke IPPF processing.
6414  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6415  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6416  * ip_policy will be false.
6417  *
6418  * Zones notes:
6419  * Currently only applications in the global zone can create raw sockets for
6420  * protocols other than ICMP. So unlike the broadcast / multicast case of
6421  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6422  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6423  */
6424 static void
6425 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6426     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6427     zoneid_t zoneid)
6428 {
6429 	queue_t	*rq;
6430 	mblk_t	*mp1, *first_mp1;
6431 	uint_t	protocol = ipha->ipha_protocol;
6432 	ipaddr_t dst;
6433 	boolean_t one_only;
6434 	mblk_t *first_mp = mp;
6435 	boolean_t secure;
6436 	uint32_t ill_index;
6437 	conn_t	*connp, *first_connp, *next_connp;
6438 	connf_t	*connfp;
6439 	boolean_t shared_addr;
6440 	mib2_ipIfStatsEntry_t *mibptr;
6441 	ip_stack_t *ipst = recv_ill->ill_ipst;
6442 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6443 
6444 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6445 	if (mctl_present) {
6446 		mp = first_mp->b_cont;
6447 		secure = ipsec_in_is_secure(first_mp);
6448 		ASSERT(mp != NULL);
6449 	} else {
6450 		secure = B_FALSE;
6451 	}
6452 	dst = ipha->ipha_dst;
6453 	/*
6454 	 * If the packet was tunneled and not multicast we only send to it
6455 	 * the first match.
6456 	 */
6457 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6458 	    !CLASSD(dst));
6459 
6460 	shared_addr = (zoneid == ALL_ZONES);
6461 	if (shared_addr) {
6462 		/*
6463 		 * We don't allow multilevel ports for raw IP, so no need to
6464 		 * check for that here.
6465 		 */
6466 		zoneid = tsol_packet_to_zoneid(mp);
6467 	}
6468 
6469 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6470 	mutex_enter(&connfp->connf_lock);
6471 	connp = connfp->connf_head;
6472 	for (connp = connfp->connf_head; connp != NULL;
6473 	    connp = connp->conn_next) {
6474 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6475 		    zoneid) &&
6476 		    (!is_system_labeled() ||
6477 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6478 		    connp))) {
6479 			break;
6480 		}
6481 	}
6482 
6483 	if (connp == NULL) {
6484 		/*
6485 		 * No one bound to these addresses.  Is
6486 		 * there a client that wants all
6487 		 * unclaimed datagrams?
6488 		 */
6489 		mutex_exit(&connfp->connf_lock);
6490 		/*
6491 		 * Check for IPPROTO_ENCAP...
6492 		 */
6493 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6494 			/*
6495 			 * If an IPsec mblk is here on a multicast
6496 			 * tunnel (using ip_mroute stuff), check policy here,
6497 			 * THEN ship off to ip_mroute_decap().
6498 			 *
6499 			 * BTW,  If I match a configured IP-in-IP
6500 			 * tunnel, this path will not be reached, and
6501 			 * ip_mroute_decap will never be called.
6502 			 */
6503 			first_mp = ipsec_check_global_policy(first_mp, connp,
6504 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6505 			if (first_mp != NULL) {
6506 				if (mctl_present)
6507 					freeb(first_mp);
6508 				ip_mroute_decap(q, mp, ill);
6509 			} /* Else we already freed everything! */
6510 		} else {
6511 			/*
6512 			 * Otherwise send an ICMP protocol unreachable.
6513 			 */
6514 			if (ip_fanout_send_icmp(q, first_mp, flags,
6515 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6516 			    mctl_present, zoneid, ipst)) {
6517 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6518 			}
6519 		}
6520 		return;
6521 	}
6522 
6523 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6524 
6525 	CONN_INC_REF(connp);
6526 	first_connp = connp;
6527 
6528 	/*
6529 	 * Only send message to one tunnel driver by immediately
6530 	 * terminating the loop.
6531 	 */
6532 	connp = one_only ? NULL : connp->conn_next;
6533 
6534 	for (;;) {
6535 		while (connp != NULL) {
6536 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6537 			    flags, zoneid) &&
6538 			    (!is_system_labeled() ||
6539 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6540 			    shared_addr, connp)))
6541 				break;
6542 			connp = connp->conn_next;
6543 		}
6544 
6545 		/*
6546 		 * Copy the packet.
6547 		 */
6548 		if (connp == NULL ||
6549 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6550 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6551 			/*
6552 			 * No more interested clients or memory
6553 			 * allocation failed
6554 			 */
6555 			connp = first_connp;
6556 			break;
6557 		}
6558 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6559 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6560 		CONN_INC_REF(connp);
6561 		mutex_exit(&connfp->connf_lock);
6562 		rq = connp->conn_rq;
6563 
6564 		/*
6565 		 * Check flow control
6566 		 */
6567 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6568 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6569 			if (flags & IP_FF_RAWIP) {
6570 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6571 			} else {
6572 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6573 			}
6574 
6575 			freemsg(first_mp1);
6576 		} else {
6577 			/*
6578 			 * Don't enforce here if we're an actual tunnel -
6579 			 * let "tun" do it instead.
6580 			 */
6581 			if (!IPCL_IS_IPTUN(connp) &&
6582 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6583 			    secure)) {
6584 				first_mp1 = ipsec_check_inbound_policy
6585 				    (first_mp1, connp, ipha, NULL,
6586 				    mctl_present);
6587 			}
6588 			if (first_mp1 != NULL) {
6589 				int in_flags = 0;
6590 				/*
6591 				 * ip_fanout_proto also gets called from
6592 				 * icmp_inbound_error_fanout, in which case
6593 				 * the msg type is M_CTL.  Don't add info
6594 				 * in this case for the time being. In future
6595 				 * when there is a need for knowing the
6596 				 * inbound iface index for ICMP error msgs,
6597 				 * then this can be changed.
6598 				 */
6599 				if (connp->conn_recvif)
6600 					in_flags = IPF_RECVIF;
6601 				/*
6602 				 * The ULP may support IP_RECVPKTINFO for both
6603 				 * IP v4 and v6 so pass the appropriate argument
6604 				 * based on conn IP version.
6605 				 */
6606 				if (connp->conn_ip_recvpktinfo) {
6607 					if (connp->conn_af_isv6) {
6608 						/*
6609 						 * V6 only needs index
6610 						 */
6611 						in_flags |= IPF_RECVIF;
6612 					} else {
6613 						/*
6614 						 * V4 needs index +
6615 						 * matching address.
6616 						 */
6617 						in_flags |= IPF_RECVADDR;
6618 					}
6619 				}
6620 				if ((in_flags != 0) &&
6621 				    (mp->b_datap->db_type != M_CTL)) {
6622 					/*
6623 					 * the actual data will be
6624 					 * contained in b_cont upon
6625 					 * successful return of the
6626 					 * following call else
6627 					 * original mblk is returned
6628 					 */
6629 					ASSERT(recv_ill != NULL);
6630 					mp1 = ip_add_info(mp1, recv_ill,
6631 					    in_flags, IPCL_ZONEID(connp), ipst);
6632 				}
6633 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6634 				if (mctl_present)
6635 					freeb(first_mp1);
6636 				(connp->conn_recv)(connp, mp1, NULL);
6637 			}
6638 		}
6639 		mutex_enter(&connfp->connf_lock);
6640 		/* Follow the next pointer before releasing the conn. */
6641 		next_connp = connp->conn_next;
6642 		CONN_DEC_REF(connp);
6643 		connp = next_connp;
6644 	}
6645 
6646 	/* Last one.  Send it upstream. */
6647 	mutex_exit(&connfp->connf_lock);
6648 
6649 	/*
6650 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6651 	 * will be set to false.
6652 	 */
6653 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6654 		ill_index = ill->ill_phyint->phyint_ifindex;
6655 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6656 		if (mp == NULL) {
6657 			CONN_DEC_REF(connp);
6658 			if (mctl_present) {
6659 				freeb(first_mp);
6660 			}
6661 			return;
6662 		}
6663 	}
6664 
6665 	rq = connp->conn_rq;
6666 	/*
6667 	 * Check flow control
6668 	 */
6669 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6670 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6671 		if (flags & IP_FF_RAWIP) {
6672 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6673 		} else {
6674 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6675 		}
6676 
6677 		freemsg(first_mp);
6678 	} else {
6679 		if (IPCL_IS_IPTUN(connp)) {
6680 			/*
6681 			 * Tunneled packet.  We enforce policy in the tunnel
6682 			 * module itself.
6683 			 *
6684 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6685 			 * a policy check.
6686 			 * FIXME to use conn_recv for tun later.
6687 			 */
6688 			putnext(rq, first_mp);
6689 			CONN_DEC_REF(connp);
6690 			return;
6691 		}
6692 
6693 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6694 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6695 			    ipha, NULL, mctl_present);
6696 		}
6697 
6698 		if (first_mp != NULL) {
6699 			int in_flags = 0;
6700 
6701 			/*
6702 			 * ip_fanout_proto also gets called
6703 			 * from icmp_inbound_error_fanout, in
6704 			 * which case the msg type is M_CTL.
6705 			 * Don't add info in this case for time
6706 			 * being. In future when there is a
6707 			 * need for knowing the inbound iface
6708 			 * index for ICMP error msgs, then this
6709 			 * can be changed
6710 			 */
6711 			if (connp->conn_recvif)
6712 				in_flags = IPF_RECVIF;
6713 			if (connp->conn_ip_recvpktinfo) {
6714 				if (connp->conn_af_isv6) {
6715 					/*
6716 					 * V6 only needs index
6717 					 */
6718 					in_flags |= IPF_RECVIF;
6719 				} else {
6720 					/*
6721 					 * V4 needs index +
6722 					 * matching address.
6723 					 */
6724 					in_flags |= IPF_RECVADDR;
6725 				}
6726 			}
6727 			if ((in_flags != 0) &&
6728 			    (mp->b_datap->db_type != M_CTL)) {
6729 
6730 				/*
6731 				 * the actual data will be contained in
6732 				 * b_cont upon successful return
6733 				 * of the following call else original
6734 				 * mblk is returned
6735 				 */
6736 				ASSERT(recv_ill != NULL);
6737 				mp = ip_add_info(mp, recv_ill,
6738 				    in_flags, IPCL_ZONEID(connp), ipst);
6739 			}
6740 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6741 			(connp->conn_recv)(connp, mp, NULL);
6742 			if (mctl_present)
6743 				freeb(first_mp);
6744 		}
6745 	}
6746 	CONN_DEC_REF(connp);
6747 }
6748 
6749 /*
6750  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6751  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6752  * the correct squeue, in this case the same squeue as a valid listener with
6753  * no current connection state for the packet we are processing. The function
6754  * is called for synchronizing both IPv4 and IPv6.
6755  */
6756 void
6757 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6758     tcp_stack_t *tcps, conn_t *connp)
6759 {
6760 	mblk_t *rst_mp;
6761 	tcp_xmit_reset_event_t *eventp;
6762 
6763 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6764 
6765 	if (rst_mp == NULL) {
6766 		freemsg(mp);
6767 		return;
6768 	}
6769 
6770 	rst_mp->b_datap->db_type = M_PROTO;
6771 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6772 
6773 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6774 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6775 	eventp->tcp_xre_iphdrlen = hdrlen;
6776 	eventp->tcp_xre_zoneid = zoneid;
6777 	eventp->tcp_xre_tcps = tcps;
6778 
6779 	rst_mp->b_cont = mp;
6780 	mp = rst_mp;
6781 
6782 	/*
6783 	 * Increment the connref, this ref will be released by the squeue
6784 	 * framework.
6785 	 */
6786 	CONN_INC_REF(connp);
6787 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6788 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6789 }
6790 
6791 /*
6792  * Fanout for TCP packets
6793  * The caller puts <fport, lport> in the ports parameter.
6794  *
6795  * IPQoS Notes
6796  * Before sending it to the client, invoke IPPF processing.
6797  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6798  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6799  * ip_policy is false.
6800  */
6801 static void
6802 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6803     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6804 {
6805 	mblk_t  *first_mp;
6806 	boolean_t secure;
6807 	uint32_t ill_index;
6808 	int	ip_hdr_len;
6809 	tcph_t	*tcph;
6810 	boolean_t syn_present = B_FALSE;
6811 	conn_t	*connp;
6812 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6813 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6814 
6815 	ASSERT(recv_ill != NULL);
6816 
6817 	first_mp = mp;
6818 	if (mctl_present) {
6819 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6820 		mp = first_mp->b_cont;
6821 		secure = ipsec_in_is_secure(first_mp);
6822 		ASSERT(mp != NULL);
6823 	} else {
6824 		secure = B_FALSE;
6825 	}
6826 
6827 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6828 
6829 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6830 	    zoneid, ipst)) == NULL) {
6831 		/*
6832 		 * No connected connection or listener. Send a
6833 		 * TH_RST via tcp_xmit_listeners_reset.
6834 		 */
6835 
6836 		/* Initiate IPPf processing, if needed. */
6837 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6838 			uint32_t ill_index;
6839 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6840 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6841 			if (first_mp == NULL)
6842 				return;
6843 		}
6844 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6845 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6846 		    zoneid));
6847 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6848 		    ipst->ips_netstack->netstack_tcp, NULL);
6849 		return;
6850 	}
6851 
6852 	/*
6853 	 * Allocate the SYN for the TCP connection here itself
6854 	 */
6855 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6856 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6857 		if (IPCL_IS_TCP(connp)) {
6858 			squeue_t *sqp;
6859 
6860 			/*
6861 			 * If the queue belongs to a conn, and fused tcp
6862 			 * loopback is enabled, assign the eager's squeue
6863 			 * to be that of the active connect's. Note that
6864 			 * we don't check for IP_FF_LOOPBACK here since this
6865 			 * routine gets called only for loopback (unlike the
6866 			 * IPv6 counterpart).
6867 			 */
6868 			if (do_tcp_fusion &&
6869 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6870 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6871 			    !secure &&
6872 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6873 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6874 				sqp = Q_TO_CONN(q)->conn_sqp;
6875 			} else {
6876 				sqp = IP_SQUEUE_GET(lbolt);
6877 			}
6878 
6879 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6880 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6881 			syn_present = B_TRUE;
6882 		}
6883 	}
6884 
6885 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6886 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6887 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6888 		if ((flags & TH_RST) || (flags & TH_URG)) {
6889 			CONN_DEC_REF(connp);
6890 			freemsg(first_mp);
6891 			return;
6892 		}
6893 		if (flags & TH_ACK) {
6894 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6895 			    ipst->ips_netstack->netstack_tcp, connp);
6896 			CONN_DEC_REF(connp);
6897 			return;
6898 		}
6899 
6900 		CONN_DEC_REF(connp);
6901 		freemsg(first_mp);
6902 		return;
6903 	}
6904 
6905 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6906 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6907 		    NULL, mctl_present);
6908 		if (first_mp == NULL) {
6909 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6910 			CONN_DEC_REF(connp);
6911 			return;
6912 		}
6913 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6914 			ASSERT(syn_present);
6915 			if (mctl_present) {
6916 				ASSERT(first_mp != mp);
6917 				first_mp->b_datap->db_struioflag |=
6918 				    STRUIO_POLICY;
6919 			} else {
6920 				ASSERT(first_mp == mp);
6921 				mp->b_datap->db_struioflag &=
6922 				    ~STRUIO_EAGER;
6923 				mp->b_datap->db_struioflag |=
6924 				    STRUIO_POLICY;
6925 			}
6926 		} else {
6927 			/*
6928 			 * Discard first_mp early since we're dealing with a
6929 			 * fully-connected conn_t and tcp doesn't do policy in
6930 			 * this case.
6931 			 */
6932 			if (mctl_present) {
6933 				freeb(first_mp);
6934 				mctl_present = B_FALSE;
6935 			}
6936 			first_mp = mp;
6937 		}
6938 	}
6939 
6940 	/*
6941 	 * Initiate policy processing here if needed. If we get here from
6942 	 * icmp_inbound_error_fanout, ip_policy is false.
6943 	 */
6944 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6945 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6946 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6947 		if (mp == NULL) {
6948 			CONN_DEC_REF(connp);
6949 			if (mctl_present)
6950 				freeb(first_mp);
6951 			return;
6952 		} else if (mctl_present) {
6953 			ASSERT(first_mp != mp);
6954 			first_mp->b_cont = mp;
6955 		} else {
6956 			first_mp = mp;
6957 		}
6958 	}
6959 
6960 	/* Handle socket options. */
6961 	if (!syn_present &&
6962 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6963 		/* Add header */
6964 		ASSERT(recv_ill != NULL);
6965 		/*
6966 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6967 		 * IPF_RECVIF.
6968 		 */
6969 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6970 		    ipst);
6971 		if (mp == NULL) {
6972 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6973 			CONN_DEC_REF(connp);
6974 			if (mctl_present)
6975 				freeb(first_mp);
6976 			return;
6977 		} else if (mctl_present) {
6978 			/*
6979 			 * ip_add_info might return a new mp.
6980 			 */
6981 			ASSERT(first_mp != mp);
6982 			first_mp->b_cont = mp;
6983 		} else {
6984 			first_mp = mp;
6985 		}
6986 	}
6987 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6988 	if (IPCL_IS_TCP(connp)) {
6989 		/* do not drain, certain use cases can blow the stack */
6990 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6991 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6992 	} else {
6993 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6994 		(connp->conn_recv)(connp, first_mp, NULL);
6995 		CONN_DEC_REF(connp);
6996 	}
6997 }
6998 
6999 /*
7000  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
7001  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
7002  * is not consumed.
7003  *
7004  * One of four things can happen, all of which affect the passed-in mblk:
7005  *
7006  * 1.) ICMP messages that go through here just get returned TRUE.
7007  *
7008  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
7009  *
7010  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7011  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7012  *
7013  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7014  */
7015 static boolean_t
7016 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7017     ipsec_stack_t *ipss)
7018 {
7019 	int shift, plen, iph_len;
7020 	ipha_t *ipha;
7021 	udpha_t *udpha;
7022 	uint32_t *spi;
7023 	uint32_t esp_ports;
7024 	uint8_t *orptr;
7025 	boolean_t free_ire;
7026 
7027 	if (DB_TYPE(mp) == M_CTL) {
7028 		/*
7029 		 * ICMP message with UDP inside.  Don't bother stripping, just
7030 		 * send it up.
7031 		 *
7032 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7033 		 * to ignore errors set by ICMP anyway ('cause they might be
7034 		 * forged), but that's the app's decision, not ours.
7035 		 */
7036 
7037 		/* Bunch of reality checks for DEBUG kernels... */
7038 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7039 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7040 
7041 		return (B_TRUE);
7042 	}
7043 
7044 	ipha = (ipha_t *)mp->b_rptr;
7045 	iph_len = IPH_HDR_LENGTH(ipha);
7046 	plen = ntohs(ipha->ipha_length);
7047 
7048 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7049 		/*
7050 		 * Most likely a keepalive for the benefit of an intervening
7051 		 * NAT.  These aren't for us, per se, so drop it.
7052 		 *
7053 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7054 		 * byte packets (keepalives are 1-byte), but we'll drop them
7055 		 * also.
7056 		 */
7057 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7058 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7059 		return (B_FALSE);
7060 	}
7061 
7062 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7063 		/* might as well pull it all up - it might be ESP. */
7064 		if (!pullupmsg(mp, -1)) {
7065 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7066 			    DROPPER(ipss, ipds_esp_nomem),
7067 			    &ipss->ipsec_dropper);
7068 			return (B_FALSE);
7069 		}
7070 
7071 		ipha = (ipha_t *)mp->b_rptr;
7072 	}
7073 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7074 	if (*spi == 0) {
7075 		/* UDP packet - remove 0-spi. */
7076 		shift = sizeof (uint32_t);
7077 	} else {
7078 		/* ESP-in-UDP packet - reduce to ESP. */
7079 		ipha->ipha_protocol = IPPROTO_ESP;
7080 		shift = sizeof (udpha_t);
7081 	}
7082 
7083 	/* Fix IP header */
7084 	ipha->ipha_length = htons(plen - shift);
7085 	ipha->ipha_hdr_checksum = 0;
7086 
7087 	orptr = mp->b_rptr;
7088 	mp->b_rptr += shift;
7089 
7090 	udpha = (udpha_t *)(orptr + iph_len);
7091 	if (*spi == 0) {
7092 		ASSERT((uint8_t *)ipha == orptr);
7093 		udpha->uha_length = htons(plen - shift - iph_len);
7094 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7095 		esp_ports = 0;
7096 	} else {
7097 		esp_ports = *((uint32_t *)udpha);
7098 		ASSERT(esp_ports != 0);
7099 	}
7100 	ovbcopy(orptr, orptr + shift, iph_len);
7101 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7102 		ipha = (ipha_t *)(orptr + shift);
7103 
7104 		free_ire = (ire == NULL);
7105 		if (free_ire) {
7106 			/* Re-acquire ire. */
7107 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7108 			    ipss->ipsec_netstack->netstack_ip);
7109 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7110 				if (ire != NULL)
7111 					ire_refrele(ire);
7112 				/*
7113 				 * Do a regular freemsg(), as this is an IP
7114 				 * error (no local route) not an IPsec one.
7115 				 */
7116 				freemsg(mp);
7117 			}
7118 		}
7119 
7120 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7121 		if (free_ire)
7122 			ire_refrele(ire);
7123 	}
7124 
7125 	return (esp_ports == 0);
7126 }
7127 
7128 /*
7129  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7130  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7131  * Caller is responsible for dropping references to the conn, and freeing
7132  * first_mp.
7133  *
7134  * IPQoS Notes
7135  * Before sending it to the client, invoke IPPF processing. Policy processing
7136  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7137  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7138  * ip_wput_local, ip_policy is false.
7139  */
7140 static void
7141 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7142     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7143     boolean_t ip_policy)
7144 {
7145 	boolean_t	mctl_present = (first_mp != NULL);
7146 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7147 	uint32_t	ill_index;
7148 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7149 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7150 
7151 	ASSERT(ill != NULL);
7152 
7153 	if (mctl_present)
7154 		first_mp->b_cont = mp;
7155 	else
7156 		first_mp = mp;
7157 
7158 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7159 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7160 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7161 		freemsg(first_mp);
7162 		return;
7163 	}
7164 
7165 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7166 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7167 		    NULL, mctl_present);
7168 		/* Freed by ipsec_check_inbound_policy(). */
7169 		if (first_mp == NULL) {
7170 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7171 			return;
7172 		}
7173 	}
7174 	if (mctl_present)
7175 		freeb(first_mp);
7176 
7177 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7178 	if (connp->conn_udp->udp_nat_t_endpoint) {
7179 		if (mctl_present) {
7180 			/* mctl_present *shouldn't* happen. */
7181 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7182 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7183 			    &ipss->ipsec_dropper);
7184 			return;
7185 		}
7186 
7187 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7188 			return;
7189 	}
7190 
7191 	/* Handle options. */
7192 	if (connp->conn_recvif)
7193 		in_flags = IPF_RECVIF;
7194 	/*
7195 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7196 	 * passed to ip_add_info is based on IP version of connp.
7197 	 */
7198 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7199 		if (connp->conn_af_isv6) {
7200 			/*
7201 			 * V6 only needs index
7202 			 */
7203 			in_flags |= IPF_RECVIF;
7204 		} else {
7205 			/*
7206 			 * V4 needs index + matching address.
7207 			 */
7208 			in_flags |= IPF_RECVADDR;
7209 		}
7210 	}
7211 
7212 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7213 		in_flags |= IPF_RECVSLLA;
7214 
7215 	/*
7216 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7217 	 * freed if the packet is dropped. The caller will do so.
7218 	 */
7219 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7220 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7221 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7222 		if (mp == NULL) {
7223 			return;
7224 		}
7225 	}
7226 	if ((in_flags != 0) &&
7227 	    (mp->b_datap->db_type != M_CTL)) {
7228 		/*
7229 		 * The actual data will be contained in b_cont
7230 		 * upon successful return of the following call
7231 		 * else original mblk is returned
7232 		 */
7233 		ASSERT(recv_ill != NULL);
7234 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7235 		    ipst);
7236 	}
7237 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7238 	/* Send it upstream */
7239 	(connp->conn_recv)(connp, mp, NULL);
7240 }
7241 
7242 /*
7243  * Fanout for UDP packets.
7244  * The caller puts <fport, lport> in the ports parameter.
7245  *
7246  * If SO_REUSEADDR is set all multicast and broadcast packets
7247  * will be delivered to all streams bound to the same port.
7248  *
7249  * Zones notes:
7250  * Multicast and broadcast packets will be distributed to streams in all zones.
7251  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7252  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7253  * packets. To maintain this behavior with multiple zones, the conns are grouped
7254  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7255  * each zone. If unset, all the following conns in the same zone are skipped.
7256  */
7257 static void
7258 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7259     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7260     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7261 {
7262 	uint32_t	dstport, srcport;
7263 	ipaddr_t	dst;
7264 	mblk_t		*first_mp;
7265 	boolean_t	secure;
7266 	in6_addr_t	v6src;
7267 	conn_t		*connp;
7268 	connf_t		*connfp;
7269 	conn_t		*first_connp;
7270 	conn_t		*next_connp;
7271 	mblk_t		*mp1, *first_mp1;
7272 	ipaddr_t	src;
7273 	zoneid_t	last_zoneid;
7274 	boolean_t	reuseaddr;
7275 	boolean_t	shared_addr;
7276 	boolean_t	unlabeled;
7277 	ip_stack_t	*ipst;
7278 
7279 	ASSERT(recv_ill != NULL);
7280 	ipst = recv_ill->ill_ipst;
7281 
7282 	first_mp = mp;
7283 	if (mctl_present) {
7284 		mp = first_mp->b_cont;
7285 		first_mp->b_cont = NULL;
7286 		secure = ipsec_in_is_secure(first_mp);
7287 		ASSERT(mp != NULL);
7288 	} else {
7289 		first_mp = NULL;
7290 		secure = B_FALSE;
7291 	}
7292 
7293 	/* Extract ports in net byte order */
7294 	dstport = htons(ntohl(ports) & 0xFFFF);
7295 	srcport = htons(ntohl(ports) >> 16);
7296 	dst = ipha->ipha_dst;
7297 	src = ipha->ipha_src;
7298 
7299 	unlabeled = B_FALSE;
7300 	if (is_system_labeled())
7301 		/* Cred cannot be null on IPv4 */
7302 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7303 		    TSLF_UNLABELED) != 0;
7304 	shared_addr = (zoneid == ALL_ZONES);
7305 	if (shared_addr) {
7306 		/*
7307 		 * No need to handle exclusive-stack zones since ALL_ZONES
7308 		 * only applies to the shared stack.
7309 		 */
7310 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7311 		/*
7312 		 * If no shared MLP is found, tsol_mlp_findzone returns
7313 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7314 		 * search for the zone based on the packet label.
7315 		 *
7316 		 * If there is such a zone, we prefer to find a
7317 		 * connection in it.  Otherwise, we look for a
7318 		 * MAC-exempt connection in any zone whose label
7319 		 * dominates the default label on the packet.
7320 		 */
7321 		if (zoneid == ALL_ZONES)
7322 			zoneid = tsol_packet_to_zoneid(mp);
7323 		else
7324 			unlabeled = B_FALSE;
7325 	}
7326 
7327 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7328 	mutex_enter(&connfp->connf_lock);
7329 	connp = connfp->connf_head;
7330 	if (!broadcast && !CLASSD(dst)) {
7331 		/*
7332 		 * Not broadcast or multicast. Send to the one (first)
7333 		 * client we find. No need to check conn_wantpacket()
7334 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7335 		 * IPv4 unicast packets.
7336 		 */
7337 		while ((connp != NULL) &&
7338 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7339 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7340 		    !(unlabeled && connp->conn_mac_exempt)))) {
7341 			/*
7342 			 * We keep searching since the conn did not match,
7343 			 * or its zone did not match and it is not either
7344 			 * an allzones conn or a mac exempt conn (if the
7345 			 * sender is unlabeled.)
7346 			 */
7347 			connp = connp->conn_next;
7348 		}
7349 
7350 		if (connp == NULL ||
7351 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7352 			goto notfound;
7353 
7354 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7355 
7356 		if (is_system_labeled() &&
7357 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7358 		    connp))
7359 			goto notfound;
7360 
7361 		CONN_INC_REF(connp);
7362 		mutex_exit(&connfp->connf_lock);
7363 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7364 		    flags, recv_ill, ip_policy);
7365 		IP_STAT(ipst, ip_udp_fannorm);
7366 		CONN_DEC_REF(connp);
7367 		return;
7368 	}
7369 
7370 	/*
7371 	 * Broadcast and multicast case
7372 	 *
7373 	 * Need to check conn_wantpacket().
7374 	 * If SO_REUSEADDR has been set on the first we send the
7375 	 * packet to all clients that have joined the group and
7376 	 * match the port.
7377 	 */
7378 
7379 	while (connp != NULL) {
7380 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7381 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7382 		    (!is_system_labeled() ||
7383 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7384 		    connp)))
7385 			break;
7386 		connp = connp->conn_next;
7387 	}
7388 
7389 	if (connp == NULL ||
7390 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7391 		goto notfound;
7392 
7393 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7394 
7395 	first_connp = connp;
7396 	/*
7397 	 * When SO_REUSEADDR is not set, send the packet only to the first
7398 	 * matching connection in its zone by keeping track of the zoneid.
7399 	 */
7400 	reuseaddr = first_connp->conn_reuseaddr;
7401 	last_zoneid = first_connp->conn_zoneid;
7402 
7403 	CONN_INC_REF(connp);
7404 	connp = connp->conn_next;
7405 	for (;;) {
7406 		while (connp != NULL) {
7407 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7408 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7409 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7410 			    (!is_system_labeled() ||
7411 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7412 			    shared_addr, connp)))
7413 				break;
7414 			connp = connp->conn_next;
7415 		}
7416 		/*
7417 		 * Just copy the data part alone. The mctl part is
7418 		 * needed just for verifying policy and it is never
7419 		 * sent up.
7420 		 */
7421 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7422 		    ((mp1 = copymsg(mp)) == NULL))) {
7423 			/*
7424 			 * No more interested clients or memory
7425 			 * allocation failed
7426 			 */
7427 			connp = first_connp;
7428 			break;
7429 		}
7430 		if (connp->conn_zoneid != last_zoneid) {
7431 			/*
7432 			 * Update the zoneid so that the packet isn't sent to
7433 			 * any more conns in the same zone unless SO_REUSEADDR
7434 			 * is set.
7435 			 */
7436 			reuseaddr = connp->conn_reuseaddr;
7437 			last_zoneid = connp->conn_zoneid;
7438 		}
7439 		if (first_mp != NULL) {
7440 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7441 			    ipsec_info_type == IPSEC_IN);
7442 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7443 			    ipst->ips_netstack);
7444 			if (first_mp1 == NULL) {
7445 				freemsg(mp1);
7446 				connp = first_connp;
7447 				break;
7448 			}
7449 		} else {
7450 			first_mp1 = NULL;
7451 		}
7452 		CONN_INC_REF(connp);
7453 		mutex_exit(&connfp->connf_lock);
7454 		/*
7455 		 * IPQoS notes: We don't send the packet for policy
7456 		 * processing here, will do it for the last one (below).
7457 		 * i.e. we do it per-packet now, but if we do policy
7458 		 * processing per-conn, then we would need to do it
7459 		 * here too.
7460 		 */
7461 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7462 		    ipha, flags, recv_ill, B_FALSE);
7463 		mutex_enter(&connfp->connf_lock);
7464 		/* Follow the next pointer before releasing the conn. */
7465 		next_connp = connp->conn_next;
7466 		IP_STAT(ipst, ip_udp_fanmb);
7467 		CONN_DEC_REF(connp);
7468 		connp = next_connp;
7469 	}
7470 
7471 	/* Last one.  Send it upstream. */
7472 	mutex_exit(&connfp->connf_lock);
7473 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7474 	    recv_ill, ip_policy);
7475 	IP_STAT(ipst, ip_udp_fanmb);
7476 	CONN_DEC_REF(connp);
7477 	return;
7478 
7479 notfound:
7480 
7481 	mutex_exit(&connfp->connf_lock);
7482 	IP_STAT(ipst, ip_udp_fanothers);
7483 	/*
7484 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7485 	 * have already been matched above, since they live in the IPv4
7486 	 * fanout tables. This implies we only need to
7487 	 * check for IPv6 in6addr_any endpoints here.
7488 	 * Thus we compare using ipv6_all_zeros instead of the destination
7489 	 * address, except for the multicast group membership lookup which
7490 	 * uses the IPv4 destination.
7491 	 */
7492 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7493 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7494 	mutex_enter(&connfp->connf_lock);
7495 	connp = connfp->connf_head;
7496 	if (!broadcast && !CLASSD(dst)) {
7497 		while (connp != NULL) {
7498 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7499 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7500 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7501 			    !connp->conn_ipv6_v6only)
7502 				break;
7503 			connp = connp->conn_next;
7504 		}
7505 
7506 		if (connp != NULL && is_system_labeled() &&
7507 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7508 		    connp))
7509 			connp = NULL;
7510 
7511 		if (connp == NULL ||
7512 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7513 			/*
7514 			 * No one bound to this port.  Is
7515 			 * there a client that wants all
7516 			 * unclaimed datagrams?
7517 			 */
7518 			mutex_exit(&connfp->connf_lock);
7519 
7520 			if (mctl_present)
7521 				first_mp->b_cont = mp;
7522 			else
7523 				first_mp = mp;
7524 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7525 			    connf_head != NULL) {
7526 				ip_fanout_proto(q, first_mp, ill, ipha,
7527 				    flags | IP_FF_RAWIP, mctl_present,
7528 				    ip_policy, recv_ill, zoneid);
7529 			} else {
7530 				if (ip_fanout_send_icmp(q, first_mp, flags,
7531 				    ICMP_DEST_UNREACHABLE,
7532 				    ICMP_PORT_UNREACHABLE,
7533 				    mctl_present, zoneid, ipst)) {
7534 					BUMP_MIB(ill->ill_ip_mib,
7535 					    udpIfStatsNoPorts);
7536 				}
7537 			}
7538 			return;
7539 		}
7540 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7541 
7542 		CONN_INC_REF(connp);
7543 		mutex_exit(&connfp->connf_lock);
7544 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7545 		    flags, recv_ill, ip_policy);
7546 		CONN_DEC_REF(connp);
7547 		return;
7548 	}
7549 	/*
7550 	 * IPv4 multicast packet being delivered to an AF_INET6
7551 	 * in6addr_any endpoint.
7552 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7553 	 * and not conn_wantpacket_v6() since any multicast membership is
7554 	 * for an IPv4-mapped multicast address.
7555 	 * The packet is sent to all clients in all zones that have joined the
7556 	 * group and match the port.
7557 	 */
7558 	while (connp != NULL) {
7559 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7560 		    srcport, v6src) &&
7561 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7562 		    (!is_system_labeled() ||
7563 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7564 		    connp)))
7565 			break;
7566 		connp = connp->conn_next;
7567 	}
7568 
7569 	if (connp == NULL ||
7570 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7571 		/*
7572 		 * No one bound to this port.  Is
7573 		 * there a client that wants all
7574 		 * unclaimed datagrams?
7575 		 */
7576 		mutex_exit(&connfp->connf_lock);
7577 
7578 		if (mctl_present)
7579 			first_mp->b_cont = mp;
7580 		else
7581 			first_mp = mp;
7582 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7583 		    NULL) {
7584 			ip_fanout_proto(q, first_mp, ill, ipha,
7585 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7586 			    recv_ill, zoneid);
7587 		} else {
7588 			/*
7589 			 * We used to attempt to send an icmp error here, but
7590 			 * since this is known to be a multicast packet
7591 			 * and we don't send icmp errors in response to
7592 			 * multicast, just drop the packet and give up sooner.
7593 			 */
7594 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7595 			freemsg(first_mp);
7596 		}
7597 		return;
7598 	}
7599 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7600 
7601 	first_connp = connp;
7602 
7603 	CONN_INC_REF(connp);
7604 	connp = connp->conn_next;
7605 	for (;;) {
7606 		while (connp != NULL) {
7607 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7608 			    ipv6_all_zeros, srcport, v6src) &&
7609 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7610 			    (!is_system_labeled() ||
7611 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7612 			    shared_addr, connp)))
7613 				break;
7614 			connp = connp->conn_next;
7615 		}
7616 		/*
7617 		 * Just copy the data part alone. The mctl part is
7618 		 * needed just for verifying policy and it is never
7619 		 * sent up.
7620 		 */
7621 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7622 		    ((mp1 = copymsg(mp)) == NULL))) {
7623 			/*
7624 			 * No more intested clients or memory
7625 			 * allocation failed
7626 			 */
7627 			connp = first_connp;
7628 			break;
7629 		}
7630 		if (first_mp != NULL) {
7631 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7632 			    ipsec_info_type == IPSEC_IN);
7633 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7634 			    ipst->ips_netstack);
7635 			if (first_mp1 == NULL) {
7636 				freemsg(mp1);
7637 				connp = first_connp;
7638 				break;
7639 			}
7640 		} else {
7641 			first_mp1 = NULL;
7642 		}
7643 		CONN_INC_REF(connp);
7644 		mutex_exit(&connfp->connf_lock);
7645 		/*
7646 		 * IPQoS notes: We don't send the packet for policy
7647 		 * processing here, will do it for the last one (below).
7648 		 * i.e. we do it per-packet now, but if we do policy
7649 		 * processing per-conn, then we would need to do it
7650 		 * here too.
7651 		 */
7652 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7653 		    ipha, flags, recv_ill, B_FALSE);
7654 		mutex_enter(&connfp->connf_lock);
7655 		/* Follow the next pointer before releasing the conn. */
7656 		next_connp = connp->conn_next;
7657 		CONN_DEC_REF(connp);
7658 		connp = next_connp;
7659 	}
7660 
7661 	/* Last one.  Send it upstream. */
7662 	mutex_exit(&connfp->connf_lock);
7663 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7664 	    recv_ill, ip_policy);
7665 	CONN_DEC_REF(connp);
7666 }
7667 
7668 /*
7669  * Complete the ip_wput header so that it
7670  * is possible to generate ICMP
7671  * errors.
7672  */
7673 int
7674 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7675 {
7676 	ire_t *ire;
7677 
7678 	if (ipha->ipha_src == INADDR_ANY) {
7679 		ire = ire_lookup_local(zoneid, ipst);
7680 		if (ire == NULL) {
7681 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7682 			return (1);
7683 		}
7684 		ipha->ipha_src = ire->ire_addr;
7685 		ire_refrele(ire);
7686 	}
7687 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7688 	ipha->ipha_hdr_checksum = 0;
7689 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7690 	return (0);
7691 }
7692 
7693 /*
7694  * Nobody should be sending
7695  * packets up this stream
7696  */
7697 static void
7698 ip_lrput(queue_t *q, mblk_t *mp)
7699 {
7700 	mblk_t *mp1;
7701 
7702 	switch (mp->b_datap->db_type) {
7703 	case M_FLUSH:
7704 		/* Turn around */
7705 		if (*mp->b_rptr & FLUSHW) {
7706 			*mp->b_rptr &= ~FLUSHR;
7707 			qreply(q, mp);
7708 			return;
7709 		}
7710 		break;
7711 	}
7712 	/* Could receive messages that passed through ar_rput */
7713 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7714 		mp1->b_prev = mp1->b_next = NULL;
7715 	freemsg(mp);
7716 }
7717 
7718 /* Nobody should be sending packets down this stream */
7719 /* ARGSUSED */
7720 void
7721 ip_lwput(queue_t *q, mblk_t *mp)
7722 {
7723 	freemsg(mp);
7724 }
7725 
7726 /*
7727  * Move the first hop in any source route to ipha_dst and remove that part of
7728  * the source route.  Called by other protocols.  Errors in option formatting
7729  * are ignored - will be handled by ip_wput_options Return the final
7730  * destination (either ipha_dst or the last entry in a source route.)
7731  */
7732 ipaddr_t
7733 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7734 {
7735 	ipoptp_t	opts;
7736 	uchar_t		*opt;
7737 	uint8_t		optval;
7738 	uint8_t		optlen;
7739 	ipaddr_t	dst;
7740 	int		i;
7741 	ire_t		*ire;
7742 	ip_stack_t	*ipst = ns->netstack_ip;
7743 
7744 	ip2dbg(("ip_massage_options\n"));
7745 	dst = ipha->ipha_dst;
7746 	for (optval = ipoptp_first(&opts, ipha);
7747 	    optval != IPOPT_EOL;
7748 	    optval = ipoptp_next(&opts)) {
7749 		opt = opts.ipoptp_cur;
7750 		switch (optval) {
7751 			uint8_t off;
7752 		case IPOPT_SSRR:
7753 		case IPOPT_LSRR:
7754 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7755 				ip1dbg(("ip_massage_options: bad src route\n"));
7756 				break;
7757 			}
7758 			optlen = opts.ipoptp_len;
7759 			off = opt[IPOPT_OFFSET];
7760 			off--;
7761 		redo_srr:
7762 			if (optlen < IP_ADDR_LEN ||
7763 			    off > optlen - IP_ADDR_LEN) {
7764 				/* End of source route */
7765 				ip1dbg(("ip_massage_options: end of SR\n"));
7766 				break;
7767 			}
7768 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7769 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7770 			    ntohl(dst)));
7771 			/*
7772 			 * Check if our address is present more than
7773 			 * once as consecutive hops in source route.
7774 			 * XXX verify per-interface ip_forwarding
7775 			 * for source route?
7776 			 */
7777 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7778 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7779 			if (ire != NULL) {
7780 				ire_refrele(ire);
7781 				off += IP_ADDR_LEN;
7782 				goto redo_srr;
7783 			}
7784 			if (dst == htonl(INADDR_LOOPBACK)) {
7785 				ip1dbg(("ip_massage_options: loopback addr in "
7786 				    "source route!\n"));
7787 				break;
7788 			}
7789 			/*
7790 			 * Update ipha_dst to be the first hop and remove the
7791 			 * first hop from the source route (by overwriting
7792 			 * part of the option with NOP options).
7793 			 */
7794 			ipha->ipha_dst = dst;
7795 			/* Put the last entry in dst */
7796 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7797 			    3;
7798 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7799 
7800 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7801 			    ntohl(dst)));
7802 			/* Move down and overwrite */
7803 			opt[IP_ADDR_LEN] = opt[0];
7804 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7805 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7806 			for (i = 0; i < IP_ADDR_LEN; i++)
7807 				opt[i] = IPOPT_NOP;
7808 			break;
7809 		}
7810 	}
7811 	return (dst);
7812 }
7813 
7814 /*
7815  * Return the network mask
7816  * associated with the specified address.
7817  */
7818 ipaddr_t
7819 ip_net_mask(ipaddr_t addr)
7820 {
7821 	uchar_t	*up = (uchar_t *)&addr;
7822 	ipaddr_t mask = 0;
7823 	uchar_t	*maskp = (uchar_t *)&mask;
7824 
7825 #if defined(__i386) || defined(__amd64)
7826 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7827 #endif
7828 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7829 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7830 #endif
7831 	if (CLASSD(addr)) {
7832 		maskp[0] = 0xF0;
7833 		return (mask);
7834 	}
7835 
7836 	/* We assume Class E default netmask to be 32 */
7837 	if (CLASSE(addr))
7838 		return (0xffffffffU);
7839 
7840 	if (addr == 0)
7841 		return (0);
7842 	maskp[0] = 0xFF;
7843 	if ((up[0] & 0x80) == 0)
7844 		return (mask);
7845 
7846 	maskp[1] = 0xFF;
7847 	if ((up[0] & 0xC0) == 0x80)
7848 		return (mask);
7849 
7850 	maskp[2] = 0xFF;
7851 	if ((up[0] & 0xE0) == 0xC0)
7852 		return (mask);
7853 
7854 	/* Otherwise return no mask */
7855 	return ((ipaddr_t)0);
7856 }
7857 
7858 /*
7859  * Helper ill lookup function used by IPsec.
7860  */
7861 ill_t *
7862 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7863 {
7864 	ill_t *ret_ill;
7865 
7866 	ASSERT(ifindex != 0);
7867 
7868 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7869 	    ipst);
7870 	if (ret_ill == NULL) {
7871 		if (isv6) {
7872 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7873 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7874 			    ifindex));
7875 		} else {
7876 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7877 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7878 			    ifindex));
7879 		}
7880 		freemsg(first_mp);
7881 		return (NULL);
7882 	}
7883 	return (ret_ill);
7884 }
7885 
7886 /*
7887  * IPv4 -
7888  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7889  * out a packet to a destination address for which we do not have specific
7890  * (or sufficient) routing information.
7891  *
7892  * NOTE : These are the scopes of some of the variables that point at IRE,
7893  *	  which needs to be followed while making any future modifications
7894  *	  to avoid memory leaks.
7895  *
7896  *	- ire and sire are the entries looked up initially by
7897  *	  ire_ftable_lookup.
7898  *	- ipif_ire is used to hold the interface ire associated with
7899  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7900  *	  it before branching out to error paths.
7901  *	- save_ire is initialized before ire_create, so that ire returned
7902  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7903  *	  before breaking out of the switch.
7904  *
7905  *	Thus on failures, we have to REFRELE only ire and sire, if they
7906  *	are not NULL.
7907  */
7908 void
7909 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7910     zoneid_t zoneid, ip_stack_t *ipst)
7911 {
7912 	areq_t	*areq;
7913 	ipaddr_t gw = 0;
7914 	ire_t	*ire = NULL;
7915 	mblk_t	*res_mp;
7916 	ipaddr_t *addrp;
7917 	ipaddr_t nexthop_addr;
7918 	ipif_t  *src_ipif = NULL;
7919 	ill_t	*dst_ill = NULL;
7920 	ipha_t  *ipha;
7921 	ire_t	*sire = NULL;
7922 	mblk_t	*first_mp;
7923 	ire_t	*save_ire;
7924 	ushort_t ire_marks = 0;
7925 	boolean_t mctl_present;
7926 	ipsec_out_t *io;
7927 	mblk_t	*saved_mp;
7928 	ire_t	*first_sire = NULL;
7929 	mblk_t	*copy_mp = NULL;
7930 	mblk_t	*xmit_mp = NULL;
7931 	ipaddr_t save_dst;
7932 	uint32_t multirt_flags =
7933 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7934 	boolean_t multirt_is_resolvable;
7935 	boolean_t multirt_resolve_next;
7936 	boolean_t unspec_src;
7937 	boolean_t ip_nexthop = B_FALSE;
7938 	tsol_ire_gw_secattr_t *attrp = NULL;
7939 	tsol_gcgrp_t *gcgrp = NULL;
7940 	tsol_gcgrp_addr_t ga;
7941 
7942 	if (ip_debug > 2) {
7943 		/* ip1dbg */
7944 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7945 	}
7946 
7947 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7948 	if (mctl_present) {
7949 		io = (ipsec_out_t *)first_mp->b_rptr;
7950 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7951 		ASSERT(zoneid == io->ipsec_out_zoneid);
7952 		ASSERT(zoneid != ALL_ZONES);
7953 	}
7954 
7955 	ipha = (ipha_t *)mp->b_rptr;
7956 
7957 	/* All multicast lookups come through ip_newroute_ipif() */
7958 	if (CLASSD(dst)) {
7959 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7960 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7961 		freemsg(first_mp);
7962 		return;
7963 	}
7964 
7965 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7966 		ip_nexthop = B_TRUE;
7967 		nexthop_addr = io->ipsec_out_nexthop_addr;
7968 	}
7969 	/*
7970 	 * If this IRE is created for forwarding or it is not for
7971 	 * traffic for congestion controlled protocols, mark it as temporary.
7972 	 */
7973 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7974 		ire_marks |= IRE_MARK_TEMPORARY;
7975 
7976 	/*
7977 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7978 	 * chain until it gets the most specific information available.
7979 	 * For example, we know that there is no IRE_CACHE for this dest,
7980 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7981 	 * ire_ftable_lookup will look up the gateway, etc.
7982 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7983 	 * to the destination, of equal netmask length in the forward table,
7984 	 * will be recursively explored. If no information is available
7985 	 * for the final gateway of that route, we force the returned ire
7986 	 * to be equal to sire using MATCH_IRE_PARENT.
7987 	 * At least, in this case we have a starting point (in the buckets)
7988 	 * to look for other routes to the destination in the forward table.
7989 	 * This is actually used only for multirouting, where a list
7990 	 * of routes has to be processed in sequence.
7991 	 *
7992 	 * In the process of coming up with the most specific information,
7993 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7994 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7995 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7996 	 * Two caveats when handling incomplete ire's in ip_newroute:
7997 	 * - we should be careful when accessing its ire_nce (specifically
7998 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7999 	 * - not all legacy code path callers are prepared to handle
8000 	 *   incomplete ire's, so we should not create/add incomplete
8001 	 *   ire_cache entries here. (See discussion about temporary solution
8002 	 *   further below).
8003 	 *
8004 	 * In order to minimize packet dropping, and to preserve existing
8005 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8006 	 * gateway, and instead use the IF_RESOLVER ire to send out
8007 	 * another request to ARP (this is achieved by passing the
8008 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8009 	 * arp response comes back in ip_wput_nondata, we will create
8010 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8011 	 *
8012 	 * Note that this is a temporary solution; the correct solution is
8013 	 * to create an incomplete  per-dst ire_cache entry, and send the
8014 	 * packet out when the gw's nce is resolved. In order to achieve this,
8015 	 * all packet processing must have been completed prior to calling
8016 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8017 	 * to be modified to accomodate this solution.
8018 	 */
8019 	if (ip_nexthop) {
8020 		/*
8021 		 * The first time we come here, we look for an IRE_INTERFACE
8022 		 * entry for the specified nexthop, set the dst to be the
8023 		 * nexthop address and create an IRE_CACHE entry for the
8024 		 * nexthop. The next time around, we are able to find an
8025 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8026 		 * nexthop address and create an IRE_CACHE entry for the
8027 		 * destination address via the specified nexthop.
8028 		 */
8029 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8030 		    msg_getlabel(mp), ipst);
8031 		if (ire != NULL) {
8032 			gw = nexthop_addr;
8033 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8034 		} else {
8035 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8036 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8037 			    msg_getlabel(mp),
8038 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8039 			    ipst);
8040 			if (ire != NULL) {
8041 				dst = nexthop_addr;
8042 			}
8043 		}
8044 	} else {
8045 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8046 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8047 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8048 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8049 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8050 		    ipst);
8051 	}
8052 
8053 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8054 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8055 
8056 	/*
8057 	 * This loop is run only once in most cases.
8058 	 * We loop to resolve further routes only when the destination
8059 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8060 	 */
8061 	do {
8062 		/* Clear the previous iteration's values */
8063 		if (src_ipif != NULL) {
8064 			ipif_refrele(src_ipif);
8065 			src_ipif = NULL;
8066 		}
8067 		if (dst_ill != NULL) {
8068 			ill_refrele(dst_ill);
8069 			dst_ill = NULL;
8070 		}
8071 
8072 		multirt_resolve_next = B_FALSE;
8073 		/*
8074 		 * We check if packets have to be multirouted.
8075 		 * In this case, given the current <ire, sire> couple,
8076 		 * we look for the next suitable <ire, sire>.
8077 		 * This check is done in ire_multirt_lookup(),
8078 		 * which applies various criteria to find the next route
8079 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8080 		 * unchanged if it detects it has not been tried yet.
8081 		 */
8082 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8083 			ip3dbg(("ip_newroute: starting next_resolution "
8084 			    "with first_mp %p, tag %d\n",
8085 			    (void *)first_mp,
8086 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8087 
8088 			ASSERT(sire != NULL);
8089 			multirt_is_resolvable =
8090 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8091 			    msg_getlabel(mp), ipst);
8092 
8093 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8094 			    "ire %p, sire %p\n",
8095 			    multirt_is_resolvable,
8096 			    (void *)ire, (void *)sire));
8097 
8098 			if (!multirt_is_resolvable) {
8099 				/*
8100 				 * No more multirt route to resolve; give up
8101 				 * (all routes resolved or no more
8102 				 * resolvable routes).
8103 				 */
8104 				if (ire != NULL) {
8105 					ire_refrele(ire);
8106 					ire = NULL;
8107 				}
8108 			} else {
8109 				ASSERT(sire != NULL);
8110 				ASSERT(ire != NULL);
8111 				/*
8112 				 * We simply use first_sire as a flag that
8113 				 * indicates if a resolvable multirt route
8114 				 * has already been found.
8115 				 * If it is not the case, we may have to send
8116 				 * an ICMP error to report that the
8117 				 * destination is unreachable.
8118 				 * We do not IRE_REFHOLD first_sire.
8119 				 */
8120 				if (first_sire == NULL) {
8121 					first_sire = sire;
8122 				}
8123 			}
8124 		}
8125 		if (ire == NULL) {
8126 			if (ip_debug > 3) {
8127 				/* ip2dbg */
8128 				pr_addr_dbg("ip_newroute: "
8129 				    "can't resolve %s\n", AF_INET, &dst);
8130 			}
8131 			ip3dbg(("ip_newroute: "
8132 			    "ire %p, sire %p, first_sire %p\n",
8133 			    (void *)ire, (void *)sire, (void *)first_sire));
8134 
8135 			if (sire != NULL) {
8136 				ire_refrele(sire);
8137 				sire = NULL;
8138 			}
8139 
8140 			if (first_sire != NULL) {
8141 				/*
8142 				 * At least one multirt route has been found
8143 				 * in the same call to ip_newroute();
8144 				 * there is no need to report an ICMP error.
8145 				 * first_sire was not IRE_REFHOLDed.
8146 				 */
8147 				MULTIRT_DEBUG_UNTAG(first_mp);
8148 				freemsg(first_mp);
8149 				return;
8150 			}
8151 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8152 			    RTA_DST, ipst);
8153 			goto icmp_err_ret;
8154 		}
8155 
8156 		/*
8157 		 * Verify that the returned IRE does not have either
8158 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8159 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8160 		 */
8161 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8162 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8163 			goto icmp_err_ret;
8164 		}
8165 		/*
8166 		 * Increment the ire_ob_pkt_count field for ire if it is an
8167 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8168 		 * increment the same for the parent IRE, sire, if it is some
8169 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8170 		 */
8171 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8172 			UPDATE_OB_PKT_COUNT(ire);
8173 			ire->ire_last_used_time = lbolt;
8174 		}
8175 
8176 		if (sire != NULL) {
8177 			gw = sire->ire_gateway_addr;
8178 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8179 			    IRE_INTERFACE)) == 0);
8180 			UPDATE_OB_PKT_COUNT(sire);
8181 			sire->ire_last_used_time = lbolt;
8182 		}
8183 		/*
8184 		 * We have a route to reach the destination.  Find the
8185 		 * appropriate ill, then get a source address using
8186 		 * ipif_select_source().
8187 		 *
8188 		 * If we are here trying to create an IRE_CACHE for an offlink
8189 		 * destination and have an IRE_CACHE entry for VNI, then use
8190 		 * ire_stq instead since VNI's queue is a black hole.
8191 		 */
8192 		if ((ire->ire_type == IRE_CACHE) &&
8193 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8194 			dst_ill = ire->ire_stq->q_ptr;
8195 			ill_refhold(dst_ill);
8196 		} else {
8197 			ill_t *ill = ire->ire_ipif->ipif_ill;
8198 
8199 			if (IS_IPMP(ill)) {
8200 				dst_ill =
8201 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8202 			} else {
8203 				dst_ill = ill;
8204 				ill_refhold(dst_ill);
8205 			}
8206 		}
8207 
8208 		if (dst_ill == NULL) {
8209 			if (ip_debug > 2) {
8210 				pr_addr_dbg("ip_newroute: no dst "
8211 				    "ill for dst %s\n", AF_INET, &dst);
8212 			}
8213 			goto icmp_err_ret;
8214 		}
8215 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8216 
8217 		/*
8218 		 * Pick the best source address from dst_ill.
8219 		 *
8220 		 * 1) Try to pick the source address from the destination
8221 		 *    route. Clustering assumes that when we have multiple
8222 		 *    prefixes hosted on an interface, the prefix of the
8223 		 *    source address matches the prefix of the destination
8224 		 *    route. We do this only if the address is not
8225 		 *    DEPRECATED.
8226 		 *
8227 		 * 2) If the conn is in a different zone than the ire, we
8228 		 *    need to pick a source address from the right zone.
8229 		 */
8230 		ASSERT(src_ipif == NULL);
8231 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8232 			/*
8233 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8234 			 * Check that the ipif matching the requested source
8235 			 * address still exists.
8236 			 */
8237 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8238 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8239 		}
8240 
8241 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8242 
8243 		if (src_ipif == NULL &&
8244 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8245 			ire_marks |= IRE_MARK_USESRC_CHECK;
8246 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8247 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8248 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8249 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8250 			    ire->ire_zoneid != ALL_ZONES) ||
8251 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8252 				/*
8253 				 * If the destination is reachable via a
8254 				 * given gateway, the selected source address
8255 				 * should be in the same subnet as the gateway.
8256 				 * Otherwise, the destination is not reachable.
8257 				 *
8258 				 * If there are no interfaces on the same subnet
8259 				 * as the destination, ipif_select_source gives
8260 				 * first non-deprecated interface which might be
8261 				 * on a different subnet than the gateway.
8262 				 * This is not desirable. Hence pass the dst_ire
8263 				 * source address to ipif_select_source.
8264 				 * It is sure that the destination is reachable
8265 				 * with the dst_ire source address subnet.
8266 				 * So passing dst_ire source address to
8267 				 * ipif_select_source will make sure that the
8268 				 * selected source will be on the same subnet
8269 				 * as dst_ire source address.
8270 				 */
8271 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8272 
8273 				src_ipif = ipif_select_source(dst_ill, saddr,
8274 				    zoneid);
8275 				if (src_ipif == NULL) {
8276 					if (ip_debug > 2) {
8277 						pr_addr_dbg("ip_newroute: "
8278 						    "no src for dst %s ",
8279 						    AF_INET, &dst);
8280 						printf("on interface %s\n",
8281 						    dst_ill->ill_name);
8282 					}
8283 					goto icmp_err_ret;
8284 				}
8285 			} else {
8286 				src_ipif = ire->ire_ipif;
8287 				ASSERT(src_ipif != NULL);
8288 				/* hold src_ipif for uniformity */
8289 				ipif_refhold(src_ipif);
8290 			}
8291 		}
8292 
8293 		/*
8294 		 * Assign a source address while we have the conn.
8295 		 * We can't have ip_wput_ire pick a source address when the
8296 		 * packet returns from arp since we need to look at
8297 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8298 		 * going through arp.
8299 		 *
8300 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8301 		 *	  it uses ip6i to store this information.
8302 		 */
8303 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8304 			ipha->ipha_src = src_ipif->ipif_src_addr;
8305 
8306 		if (ip_debug > 3) {
8307 			/* ip2dbg */
8308 			pr_addr_dbg("ip_newroute: first hop %s\n",
8309 			    AF_INET, &gw);
8310 		}
8311 		ip2dbg(("\tire type %s (%d)\n",
8312 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8313 
8314 		/*
8315 		 * The TTL of multirouted packets is bounded by the
8316 		 * ip_multirt_ttl ndd variable.
8317 		 */
8318 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8319 			/* Force TTL of multirouted packets */
8320 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8321 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8322 				ip2dbg(("ip_newroute: forcing multirt TTL "
8323 				    "to %d (was %d), dst 0x%08x\n",
8324 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8325 				    ntohl(sire->ire_addr)));
8326 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8327 			}
8328 		}
8329 		/*
8330 		 * At this point in ip_newroute(), ire is either the
8331 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8332 		 * destination or an IRE_INTERFACE type that should be used
8333 		 * to resolve an on-subnet destination or an on-subnet
8334 		 * next-hop gateway.
8335 		 *
8336 		 * In the IRE_CACHE case, we have the following :
8337 		 *
8338 		 * 1) src_ipif - used for getting a source address.
8339 		 *
8340 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8341 		 *    means packets using this IRE_CACHE will go out on
8342 		 *    dst_ill.
8343 		 *
8344 		 * 3) The IRE sire will point to the prefix that is the
8345 		 *    longest  matching route for the destination. These
8346 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8347 		 *
8348 		 *    The newly created IRE_CACHE entry for the off-subnet
8349 		 *    destination is tied to both the prefix route and the
8350 		 *    interface route used to resolve the next-hop gateway
8351 		 *    via the ire_phandle and ire_ihandle fields,
8352 		 *    respectively.
8353 		 *
8354 		 * In the IRE_INTERFACE case, we have the following :
8355 		 *
8356 		 * 1) src_ipif - used for getting a source address.
8357 		 *
8358 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8359 		 *    means packets using the IRE_CACHE that we will build
8360 		 *    here will go out on dst_ill.
8361 		 *
8362 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8363 		 *    to be created will only be tied to the IRE_INTERFACE
8364 		 *    that was derived from the ire_ihandle field.
8365 		 *
8366 		 *    If sire is non-NULL, it means the destination is
8367 		 *    off-link and we will first create the IRE_CACHE for the
8368 		 *    gateway. Next time through ip_newroute, we will create
8369 		 *    the IRE_CACHE for the final destination as described
8370 		 *    above.
8371 		 *
8372 		 * In both cases, after the current resolution has been
8373 		 * completed (or possibly initialised, in the IRE_INTERFACE
8374 		 * case), the loop may be re-entered to attempt the resolution
8375 		 * of another RTF_MULTIRT route.
8376 		 *
8377 		 * When an IRE_CACHE entry for the off-subnet destination is
8378 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8379 		 * for further processing in emission loops.
8380 		 */
8381 		save_ire = ire;
8382 		switch (ire->ire_type) {
8383 		case IRE_CACHE: {
8384 			ire_t	*ipif_ire;
8385 
8386 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8387 			if (gw == 0)
8388 				gw = ire->ire_gateway_addr;
8389 			/*
8390 			 * We need 3 ire's to create a new cache ire for an
8391 			 * off-link destination from the cache ire of the
8392 			 * gateway.
8393 			 *
8394 			 *	1. The prefix ire 'sire' (Note that this does
8395 			 *	   not apply to the conn_nexthop_set case)
8396 			 *	2. The cache ire of the gateway 'ire'
8397 			 *	3. The interface ire 'ipif_ire'
8398 			 *
8399 			 * We have (1) and (2). We lookup (3) below.
8400 			 *
8401 			 * If there is no interface route to the gateway,
8402 			 * it is a race condition, where we found the cache
8403 			 * but the interface route has been deleted.
8404 			 */
8405 			if (ip_nexthop) {
8406 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8407 			} else {
8408 				ipif_ire =
8409 				    ire_ihandle_lookup_offlink(ire, sire);
8410 			}
8411 			if (ipif_ire == NULL) {
8412 				ip1dbg(("ip_newroute: "
8413 				    "ire_ihandle_lookup_offlink failed\n"));
8414 				goto icmp_err_ret;
8415 			}
8416 
8417 			/*
8418 			 * Check cached gateway IRE for any security
8419 			 * attributes; if found, associate the gateway
8420 			 * credentials group to the destination IRE.
8421 			 */
8422 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8423 				mutex_enter(&attrp->igsa_lock);
8424 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8425 					GCGRP_REFHOLD(gcgrp);
8426 				mutex_exit(&attrp->igsa_lock);
8427 			}
8428 
8429 			/*
8430 			 * XXX For the source of the resolver mp,
8431 			 * we are using the same DL_UNITDATA_REQ
8432 			 * (from save_ire->ire_nce->nce_res_mp)
8433 			 * though the save_ire is not pointing at the same ill.
8434 			 * This is incorrect. We need to send it up to the
8435 			 * resolver to get the right res_mp. For ethernets
8436 			 * this may be okay (ill_type == DL_ETHER).
8437 			 */
8438 
8439 			ire = ire_create(
8440 			    (uchar_t *)&dst,		/* dest address */
8441 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8442 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8443 			    (uchar_t *)&gw,		/* gateway address */
8444 			    &save_ire->ire_max_frag,
8445 			    save_ire->ire_nce,		/* src nce */
8446 			    dst_ill->ill_rq,		/* recv-from queue */
8447 			    dst_ill->ill_wq,		/* send-to queue */
8448 			    IRE_CACHE,			/* IRE type */
8449 			    src_ipif,
8450 			    (sire != NULL) ?
8451 			    sire->ire_mask : 0, 	/* Parent mask */
8452 			    (sire != NULL) ?
8453 			    sire->ire_phandle : 0,	/* Parent handle */
8454 			    ipif_ire->ire_ihandle,	/* Interface handle */
8455 			    (sire != NULL) ? (sire->ire_flags &
8456 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8457 			    (sire != NULL) ?
8458 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8459 			    NULL,
8460 			    gcgrp,
8461 			    ipst);
8462 
8463 			if (ire == NULL) {
8464 				if (gcgrp != NULL) {
8465 					GCGRP_REFRELE(gcgrp);
8466 					gcgrp = NULL;
8467 				}
8468 				ire_refrele(ipif_ire);
8469 				ire_refrele(save_ire);
8470 				break;
8471 			}
8472 
8473 			/* reference now held by IRE */
8474 			gcgrp = NULL;
8475 
8476 			ire->ire_marks |= ire_marks;
8477 
8478 			/*
8479 			 * Prevent sire and ipif_ire from getting deleted.
8480 			 * The newly created ire is tied to both of them via
8481 			 * the phandle and ihandle respectively.
8482 			 */
8483 			if (sire != NULL) {
8484 				IRB_REFHOLD(sire->ire_bucket);
8485 				/* Has it been removed already ? */
8486 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8487 					IRB_REFRELE(sire->ire_bucket);
8488 					ire_refrele(ipif_ire);
8489 					ire_refrele(save_ire);
8490 					break;
8491 				}
8492 			}
8493 
8494 			IRB_REFHOLD(ipif_ire->ire_bucket);
8495 			/* Has it been removed already ? */
8496 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8497 				IRB_REFRELE(ipif_ire->ire_bucket);
8498 				if (sire != NULL)
8499 					IRB_REFRELE(sire->ire_bucket);
8500 				ire_refrele(ipif_ire);
8501 				ire_refrele(save_ire);
8502 				break;
8503 			}
8504 
8505 			xmit_mp = first_mp;
8506 			/*
8507 			 * In the case of multirouting, a copy
8508 			 * of the packet is done before its sending.
8509 			 * The copy is used to attempt another
8510 			 * route resolution, in a next loop.
8511 			 */
8512 			if (ire->ire_flags & RTF_MULTIRT) {
8513 				copy_mp = copymsg(first_mp);
8514 				if (copy_mp != NULL) {
8515 					xmit_mp = copy_mp;
8516 					MULTIRT_DEBUG_TAG(first_mp);
8517 				}
8518 			}
8519 
8520 			ire_add_then_send(q, ire, xmit_mp);
8521 			ire_refrele(save_ire);
8522 
8523 			/* Assert that sire is not deleted yet. */
8524 			if (sire != NULL) {
8525 				ASSERT(sire->ire_ptpn != NULL);
8526 				IRB_REFRELE(sire->ire_bucket);
8527 			}
8528 
8529 			/* Assert that ipif_ire is not deleted yet. */
8530 			ASSERT(ipif_ire->ire_ptpn != NULL);
8531 			IRB_REFRELE(ipif_ire->ire_bucket);
8532 			ire_refrele(ipif_ire);
8533 
8534 			/*
8535 			 * If copy_mp is not NULL, multirouting was
8536 			 * requested. We loop to initiate a next
8537 			 * route resolution attempt, starting from sire.
8538 			 */
8539 			if (copy_mp != NULL) {
8540 				/*
8541 				 * Search for the next unresolved
8542 				 * multirt route.
8543 				 */
8544 				copy_mp = NULL;
8545 				ipif_ire = NULL;
8546 				ire = NULL;
8547 				multirt_resolve_next = B_TRUE;
8548 				continue;
8549 			}
8550 			if (sire != NULL)
8551 				ire_refrele(sire);
8552 			ipif_refrele(src_ipif);
8553 			ill_refrele(dst_ill);
8554 			return;
8555 		}
8556 		case IRE_IF_NORESOLVER: {
8557 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8558 			    dst_ill->ill_resolver_mp == NULL) {
8559 				ip1dbg(("ip_newroute: dst_ill %p "
8560 				    "for IRE_IF_NORESOLVER ire %p has "
8561 				    "no ill_resolver_mp\n",
8562 				    (void *)dst_ill, (void *)ire));
8563 				break;
8564 			}
8565 
8566 			/*
8567 			 * TSol note: We are creating the ire cache for the
8568 			 * destination 'dst'. If 'dst' is offlink, going
8569 			 * through the first hop 'gw', the security attributes
8570 			 * of 'dst' must be set to point to the gateway
8571 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8572 			 * is possible that 'dst' is a potential gateway that is
8573 			 * referenced by some route that has some security
8574 			 * attributes. Thus in the former case, we need to do a
8575 			 * gcgrp_lookup of 'gw' while in the latter case we
8576 			 * need to do gcgrp_lookup of 'dst' itself.
8577 			 */
8578 			ga.ga_af = AF_INET;
8579 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8580 			    &ga.ga_addr);
8581 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8582 
8583 			ire = ire_create(
8584 			    (uchar_t *)&dst,		/* dest address */
8585 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8586 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8587 			    (uchar_t *)&gw,		/* gateway address */
8588 			    &save_ire->ire_max_frag,
8589 			    NULL,			/* no src nce */
8590 			    dst_ill->ill_rq,		/* recv-from queue */
8591 			    dst_ill->ill_wq,		/* send-to queue */
8592 			    IRE_CACHE,
8593 			    src_ipif,
8594 			    save_ire->ire_mask,		/* Parent mask */
8595 			    (sire != NULL) ?		/* Parent handle */
8596 			    sire->ire_phandle : 0,
8597 			    save_ire->ire_ihandle,	/* Interface handle */
8598 			    (sire != NULL) ? sire->ire_flags &
8599 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8600 			    &(save_ire->ire_uinfo),
8601 			    NULL,
8602 			    gcgrp,
8603 			    ipst);
8604 
8605 			if (ire == NULL) {
8606 				if (gcgrp != NULL) {
8607 					GCGRP_REFRELE(gcgrp);
8608 					gcgrp = NULL;
8609 				}
8610 				ire_refrele(save_ire);
8611 				break;
8612 			}
8613 
8614 			/* reference now held by IRE */
8615 			gcgrp = NULL;
8616 
8617 			ire->ire_marks |= ire_marks;
8618 
8619 			/* Prevent save_ire from getting deleted */
8620 			IRB_REFHOLD(save_ire->ire_bucket);
8621 			/* Has it been removed already ? */
8622 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8623 				IRB_REFRELE(save_ire->ire_bucket);
8624 				ire_refrele(save_ire);
8625 				break;
8626 			}
8627 
8628 			/*
8629 			 * In the case of multirouting, a copy
8630 			 * of the packet is made before it is sent.
8631 			 * The copy is used in the next
8632 			 * loop to attempt another resolution.
8633 			 */
8634 			xmit_mp = first_mp;
8635 			if ((sire != NULL) &&
8636 			    (sire->ire_flags & RTF_MULTIRT)) {
8637 				copy_mp = copymsg(first_mp);
8638 				if (copy_mp != NULL) {
8639 					xmit_mp = copy_mp;
8640 					MULTIRT_DEBUG_TAG(first_mp);
8641 				}
8642 			}
8643 			ire_add_then_send(q, ire, xmit_mp);
8644 
8645 			/* Assert that it is not deleted yet. */
8646 			ASSERT(save_ire->ire_ptpn != NULL);
8647 			IRB_REFRELE(save_ire->ire_bucket);
8648 			ire_refrele(save_ire);
8649 
8650 			if (copy_mp != NULL) {
8651 				/*
8652 				 * If we found a (no)resolver, we ignore any
8653 				 * trailing top priority IRE_CACHE in further
8654 				 * loops. This ensures that we do not omit any
8655 				 * (no)resolver.
8656 				 * This IRE_CACHE, if any, will be processed
8657 				 * by another thread entering ip_newroute().
8658 				 * IRE_CACHE entries, if any, will be processed
8659 				 * by another thread entering ip_newroute(),
8660 				 * (upon resolver response, for instance).
8661 				 * This aims to force parallel multirt
8662 				 * resolutions as soon as a packet must be sent.
8663 				 * In the best case, after the tx of only one
8664 				 * packet, all reachable routes are resolved.
8665 				 * Otherwise, the resolution of all RTF_MULTIRT
8666 				 * routes would require several emissions.
8667 				 */
8668 				multirt_flags &= ~MULTIRT_CACHEGW;
8669 
8670 				/*
8671 				 * Search for the next unresolved multirt
8672 				 * route.
8673 				 */
8674 				copy_mp = NULL;
8675 				save_ire = NULL;
8676 				ire = NULL;
8677 				multirt_resolve_next = B_TRUE;
8678 				continue;
8679 			}
8680 
8681 			/*
8682 			 * Don't need sire anymore
8683 			 */
8684 			if (sire != NULL)
8685 				ire_refrele(sire);
8686 
8687 			ipif_refrele(src_ipif);
8688 			ill_refrele(dst_ill);
8689 			return;
8690 		}
8691 		case IRE_IF_RESOLVER:
8692 			/*
8693 			 * We can't build an IRE_CACHE yet, but at least we
8694 			 * found a resolver that can help.
8695 			 */
8696 			res_mp = dst_ill->ill_resolver_mp;
8697 			if (!OK_RESOLVER_MP(res_mp))
8698 				break;
8699 
8700 			/*
8701 			 * To be at this point in the code with a non-zero gw
8702 			 * means that dst is reachable through a gateway that
8703 			 * we have never resolved.  By changing dst to the gw
8704 			 * addr we resolve the gateway first.
8705 			 * When ire_add_then_send() tries to put the IP dg
8706 			 * to dst, it will reenter ip_newroute() at which
8707 			 * time we will find the IRE_CACHE for the gw and
8708 			 * create another IRE_CACHE in case IRE_CACHE above.
8709 			 */
8710 			if (gw != INADDR_ANY) {
8711 				/*
8712 				 * The source ipif that was determined above was
8713 				 * relative to the destination address, not the
8714 				 * gateway's. If src_ipif was not taken out of
8715 				 * the IRE_IF_RESOLVER entry, we'll need to call
8716 				 * ipif_select_source() again.
8717 				 */
8718 				if (src_ipif != ire->ire_ipif) {
8719 					ipif_refrele(src_ipif);
8720 					src_ipif = ipif_select_source(dst_ill,
8721 					    gw, zoneid);
8722 					if (src_ipif == NULL) {
8723 						if (ip_debug > 2) {
8724 							pr_addr_dbg(
8725 							    "ip_newroute: no "
8726 							    "src for gw %s ",
8727 							    AF_INET, &gw);
8728 							printf("on "
8729 							    "interface %s\n",
8730 							    dst_ill->ill_name);
8731 						}
8732 						goto icmp_err_ret;
8733 					}
8734 				}
8735 				save_dst = dst;
8736 				dst = gw;
8737 				gw = INADDR_ANY;
8738 			}
8739 
8740 			/*
8741 			 * We obtain a partial IRE_CACHE which we will pass
8742 			 * along with the resolver query.  When the response
8743 			 * comes back it will be there ready for us to add.
8744 			 * The ire_max_frag is atomically set under the
8745 			 * irebucket lock in ire_add_v[46].
8746 			 */
8747 
8748 			ire = ire_create_mp(
8749 			    (uchar_t *)&dst,		/* dest address */
8750 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8751 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8752 			    (uchar_t *)&gw,		/* gateway address */
8753 			    NULL,			/* ire_max_frag */
8754 			    NULL,			/* no src nce */
8755 			    dst_ill->ill_rq,		/* recv-from queue */
8756 			    dst_ill->ill_wq,		/* send-to queue */
8757 			    IRE_CACHE,
8758 			    src_ipif,			/* Interface ipif */
8759 			    save_ire->ire_mask,		/* Parent mask */
8760 			    0,
8761 			    save_ire->ire_ihandle,	/* Interface handle */
8762 			    0,				/* flags if any */
8763 			    &(save_ire->ire_uinfo),
8764 			    NULL,
8765 			    NULL,
8766 			    ipst);
8767 
8768 			if (ire == NULL) {
8769 				ire_refrele(save_ire);
8770 				break;
8771 			}
8772 
8773 			if ((sire != NULL) &&
8774 			    (sire->ire_flags & RTF_MULTIRT)) {
8775 				copy_mp = copymsg(first_mp);
8776 				if (copy_mp != NULL)
8777 					MULTIRT_DEBUG_TAG(copy_mp);
8778 			}
8779 
8780 			ire->ire_marks |= ire_marks;
8781 
8782 			/*
8783 			 * Construct message chain for the resolver
8784 			 * of the form:
8785 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8786 			 * Packet could contain a IPSEC_OUT mp.
8787 			 *
8788 			 * NOTE : ire will be added later when the response
8789 			 * comes back from ARP. If the response does not
8790 			 * come back, ARP frees the packet. For this reason,
8791 			 * we can't REFHOLD the bucket of save_ire to prevent
8792 			 * deletions. We may not be able to REFRELE the bucket
8793 			 * if the response never comes back. Thus, before
8794 			 * adding the ire, ire_add_v4 will make sure that the
8795 			 * interface route does not get deleted. This is the
8796 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8797 			 * where we can always prevent deletions because of
8798 			 * the synchronous nature of adding IRES i.e
8799 			 * ire_add_then_send is called after creating the IRE.
8800 			 */
8801 			ASSERT(ire->ire_mp != NULL);
8802 			ire->ire_mp->b_cont = first_mp;
8803 			/* Have saved_mp handy, for cleanup if canput fails */
8804 			saved_mp = mp;
8805 			mp = copyb(res_mp);
8806 			if (mp == NULL) {
8807 				/* Prepare for cleanup */
8808 				mp = saved_mp; /* pkt */
8809 				ire_delete(ire); /* ire_mp */
8810 				ire = NULL;
8811 				ire_refrele(save_ire);
8812 				if (copy_mp != NULL) {
8813 					MULTIRT_DEBUG_UNTAG(copy_mp);
8814 					freemsg(copy_mp);
8815 					copy_mp = NULL;
8816 				}
8817 				break;
8818 			}
8819 			linkb(mp, ire->ire_mp);
8820 
8821 			/*
8822 			 * Fill in the source and dest addrs for the resolver.
8823 			 * NOTE: this depends on memory layouts imposed by
8824 			 * ill_init().
8825 			 */
8826 			areq = (areq_t *)mp->b_rptr;
8827 			addrp = (ipaddr_t *)((char *)areq +
8828 			    areq->areq_sender_addr_offset);
8829 			*addrp = save_ire->ire_src_addr;
8830 
8831 			ire_refrele(save_ire);
8832 			addrp = (ipaddr_t *)((char *)areq +
8833 			    areq->areq_target_addr_offset);
8834 			*addrp = dst;
8835 			/* Up to the resolver. */
8836 			if (canputnext(dst_ill->ill_rq) &&
8837 			    !(dst_ill->ill_arp_closing)) {
8838 				putnext(dst_ill->ill_rq, mp);
8839 				ire = NULL;
8840 				if (copy_mp != NULL) {
8841 					/*
8842 					 * If we found a resolver, we ignore
8843 					 * any trailing top priority IRE_CACHE
8844 					 * in the further loops. This ensures
8845 					 * that we do not omit any resolver.
8846 					 * IRE_CACHE entries, if any, will be
8847 					 * processed next time we enter
8848 					 * ip_newroute().
8849 					 */
8850 					multirt_flags &= ~MULTIRT_CACHEGW;
8851 					/*
8852 					 * Search for the next unresolved
8853 					 * multirt route.
8854 					 */
8855 					first_mp = copy_mp;
8856 					copy_mp = NULL;
8857 					/* Prepare the next resolution loop. */
8858 					mp = first_mp;
8859 					EXTRACT_PKT_MP(mp, first_mp,
8860 					    mctl_present);
8861 					if (mctl_present)
8862 						io = (ipsec_out_t *)
8863 						    first_mp->b_rptr;
8864 					ipha = (ipha_t *)mp->b_rptr;
8865 
8866 					ASSERT(sire != NULL);
8867 
8868 					dst = save_dst;
8869 					multirt_resolve_next = B_TRUE;
8870 					continue;
8871 				}
8872 
8873 				if (sire != NULL)
8874 					ire_refrele(sire);
8875 
8876 				/*
8877 				 * The response will come back in ip_wput
8878 				 * with db_type IRE_DB_TYPE.
8879 				 */
8880 				ipif_refrele(src_ipif);
8881 				ill_refrele(dst_ill);
8882 				return;
8883 			} else {
8884 				/* Prepare for cleanup */
8885 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8886 				    mp);
8887 				mp->b_cont = NULL;
8888 				freeb(mp); /* areq */
8889 				/*
8890 				 * this is an ire that is not added to the
8891 				 * cache. ire_freemblk will handle the release
8892 				 * of any resources associated with the ire.
8893 				 */
8894 				ire_delete(ire); /* ire_mp */
8895 				mp = saved_mp; /* pkt */
8896 				ire = NULL;
8897 				if (copy_mp != NULL) {
8898 					MULTIRT_DEBUG_UNTAG(copy_mp);
8899 					freemsg(copy_mp);
8900 					copy_mp = NULL;
8901 				}
8902 				break;
8903 			}
8904 		default:
8905 			break;
8906 		}
8907 	} while (multirt_resolve_next);
8908 
8909 	ip1dbg(("ip_newroute: dropped\n"));
8910 	/* Did this packet originate externally? */
8911 	if (mp->b_prev) {
8912 		mp->b_next = NULL;
8913 		mp->b_prev = NULL;
8914 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8915 	} else {
8916 		if (dst_ill != NULL) {
8917 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8918 		} else {
8919 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8920 		}
8921 	}
8922 	ASSERT(copy_mp == NULL);
8923 	MULTIRT_DEBUG_UNTAG(first_mp);
8924 	freemsg(first_mp);
8925 	if (ire != NULL)
8926 		ire_refrele(ire);
8927 	if (sire != NULL)
8928 		ire_refrele(sire);
8929 	if (src_ipif != NULL)
8930 		ipif_refrele(src_ipif);
8931 	if (dst_ill != NULL)
8932 		ill_refrele(dst_ill);
8933 	return;
8934 
8935 icmp_err_ret:
8936 	ip1dbg(("ip_newroute: no route\n"));
8937 	if (src_ipif != NULL)
8938 		ipif_refrele(src_ipif);
8939 	if (dst_ill != NULL)
8940 		ill_refrele(dst_ill);
8941 	if (sire != NULL)
8942 		ire_refrele(sire);
8943 	/* Did this packet originate externally? */
8944 	if (mp->b_prev) {
8945 		mp->b_next = NULL;
8946 		mp->b_prev = NULL;
8947 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8948 		q = WR(q);
8949 	} else {
8950 		/*
8951 		 * There is no outgoing ill, so just increment the
8952 		 * system MIB.
8953 		 */
8954 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8955 		/*
8956 		 * Since ip_wput() isn't close to finished, we fill
8957 		 * in enough of the header for credible error reporting.
8958 		 */
8959 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8960 			/* Failed */
8961 			MULTIRT_DEBUG_UNTAG(first_mp);
8962 			freemsg(first_mp);
8963 			if (ire != NULL)
8964 				ire_refrele(ire);
8965 			return;
8966 		}
8967 	}
8968 
8969 	/*
8970 	 * At this point we will have ire only if RTF_BLACKHOLE
8971 	 * or RTF_REJECT flags are set on the IRE. It will not
8972 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8973 	 */
8974 	if (ire != NULL) {
8975 		if (ire->ire_flags & RTF_BLACKHOLE) {
8976 			ire_refrele(ire);
8977 			MULTIRT_DEBUG_UNTAG(first_mp);
8978 			freemsg(first_mp);
8979 			return;
8980 		}
8981 		ire_refrele(ire);
8982 	}
8983 	if (ip_source_routed(ipha, ipst)) {
8984 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8985 		    zoneid, ipst);
8986 		return;
8987 	}
8988 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8989 }
8990 
8991 ip_opt_info_t zero_info;
8992 
8993 /*
8994  * IPv4 -
8995  * ip_newroute_ipif is called by ip_wput_multicast and
8996  * ip_rput_forward_multicast whenever we need to send
8997  * out a packet to a destination address for which we do not have specific
8998  * routing information. It is used when the packet will be sent out
8999  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9000  * socket option is set or icmp error message wants to go out on a particular
9001  * interface for a unicast packet.
9002  *
9003  * In most cases, the destination address is resolved thanks to the ipif
9004  * intrinsic resolver. However, there are some cases where the call to
9005  * ip_newroute_ipif must take into account the potential presence of
9006  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9007  * that uses the interface. This is specified through flags,
9008  * which can be a combination of:
9009  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9010  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9011  *   and flags. Additionally, the packet source address has to be set to
9012  *   the specified address. The caller is thus expected to set this flag
9013  *   if the packet has no specific source address yet.
9014  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9015  *   flag, the resulting ire will inherit the flag. All unresolved routes
9016  *   to the destination must be explored in the same call to
9017  *   ip_newroute_ipif().
9018  */
9019 static void
9020 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9021     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9022 {
9023 	areq_t	*areq;
9024 	ire_t	*ire = NULL;
9025 	mblk_t	*res_mp;
9026 	ipaddr_t *addrp;
9027 	mblk_t *first_mp;
9028 	ire_t	*save_ire = NULL;
9029 	ipif_t	*src_ipif = NULL;
9030 	ushort_t ire_marks = 0;
9031 	ill_t	*dst_ill = NULL;
9032 	ipha_t *ipha;
9033 	mblk_t	*saved_mp;
9034 	ire_t   *fire = NULL;
9035 	mblk_t  *copy_mp = NULL;
9036 	boolean_t multirt_resolve_next;
9037 	boolean_t unspec_src;
9038 	ipaddr_t ipha_dst;
9039 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9040 
9041 	/*
9042 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9043 	 * here for uniformity
9044 	 */
9045 	ipif_refhold(ipif);
9046 
9047 	/*
9048 	 * This loop is run only once in most cases.
9049 	 * We loop to resolve further routes only when the destination
9050 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9051 	 */
9052 	do {
9053 		if (dst_ill != NULL) {
9054 			ill_refrele(dst_ill);
9055 			dst_ill = NULL;
9056 		}
9057 		if (src_ipif != NULL) {
9058 			ipif_refrele(src_ipif);
9059 			src_ipif = NULL;
9060 		}
9061 		multirt_resolve_next = B_FALSE;
9062 
9063 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9064 		    ipif->ipif_ill->ill_name));
9065 
9066 		first_mp = mp;
9067 		if (DB_TYPE(mp) == M_CTL)
9068 			mp = mp->b_cont;
9069 		ipha = (ipha_t *)mp->b_rptr;
9070 
9071 		/*
9072 		 * Save the packet destination address, we may need it after
9073 		 * the packet has been consumed.
9074 		 */
9075 		ipha_dst = ipha->ipha_dst;
9076 
9077 		/*
9078 		 * If the interface is a pt-pt interface we look for an
9079 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9080 		 * local_address and the pt-pt destination address. Otherwise
9081 		 * we just match the local address.
9082 		 * NOTE: dst could be different than ipha->ipha_dst in case
9083 		 * of sending igmp multicast packets over a point-to-point
9084 		 * connection.
9085 		 * Thus we must be careful enough to check ipha_dst to be a
9086 		 * multicast address, otherwise it will take xmit_if path for
9087 		 * multicast packets resulting into kernel stack overflow by
9088 		 * repeated calls to ip_newroute_ipif from ire_send().
9089 		 */
9090 		if (CLASSD(ipha_dst) &&
9091 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9092 			goto err_ret;
9093 		}
9094 
9095 		/*
9096 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9097 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9098 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9099 		 * propagate its flags to the new ire.
9100 		 */
9101 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9102 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9103 			ip2dbg(("ip_newroute_ipif: "
9104 			    "ipif_lookup_multi_ire("
9105 			    "ipif %p, dst %08x) = fire %p\n",
9106 			    (void *)ipif, ntohl(dst), (void *)fire));
9107 		}
9108 
9109 		/*
9110 		 * Note: While we pick a dst_ill we are really only
9111 		 * interested in the ill for load spreading. The source
9112 		 * ipif is determined by source address selection below.
9113 		 */
9114 		if (IS_IPMP(ipif->ipif_ill)) {
9115 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9116 
9117 			if (CLASSD(ipha_dst))
9118 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9119 			else
9120 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9121 		} else {
9122 			dst_ill = ipif->ipif_ill;
9123 			ill_refhold(dst_ill);
9124 		}
9125 
9126 		if (dst_ill == NULL) {
9127 			if (ip_debug > 2) {
9128 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9129 				    "for dst %s\n", AF_INET, &dst);
9130 			}
9131 			goto err_ret;
9132 		}
9133 
9134 		/*
9135 		 * Pick a source address preferring non-deprecated ones.
9136 		 * Unlike ip_newroute, we don't do any source address
9137 		 * selection here since for multicast it really does not help
9138 		 * in inbound load spreading as in the unicast case.
9139 		 */
9140 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9141 		    (fire->ire_flags & RTF_SETSRC)) {
9142 			/*
9143 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9144 			 * on that interface. This ire has RTF_SETSRC flag, so
9145 			 * the source address of the packet must be changed.
9146 			 * Check that the ipif matching the requested source
9147 			 * address still exists.
9148 			 */
9149 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9150 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9151 		}
9152 
9153 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9154 
9155 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9156 		    (IS_IPMP(ipif->ipif_ill) ||
9157 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9158 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9159 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9160 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9161 		    (src_ipif == NULL) &&
9162 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9163 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9164 			if (src_ipif == NULL) {
9165 				if (ip_debug > 2) {
9166 					/* ip1dbg */
9167 					pr_addr_dbg("ip_newroute_ipif: "
9168 					    "no src for dst %s",
9169 					    AF_INET, &dst);
9170 				}
9171 				ip1dbg((" on interface %s\n",
9172 				    dst_ill->ill_name));
9173 				goto err_ret;
9174 			}
9175 			ipif_refrele(ipif);
9176 			ipif = src_ipif;
9177 			ipif_refhold(ipif);
9178 		}
9179 		if (src_ipif == NULL) {
9180 			src_ipif = ipif;
9181 			ipif_refhold(src_ipif);
9182 		}
9183 
9184 		/*
9185 		 * Assign a source address while we have the conn.
9186 		 * We can't have ip_wput_ire pick a source address when the
9187 		 * packet returns from arp since conn_unspec_src might be set
9188 		 * and we lose the conn when going through arp.
9189 		 */
9190 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9191 			ipha->ipha_src = src_ipif->ipif_src_addr;
9192 
9193 		/*
9194 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9195 		 * that the outgoing interface does not have an interface ire.
9196 		 */
9197 		if (CLASSD(ipha_dst) && (connp == NULL ||
9198 		    connp->conn_outgoing_ill == NULL) &&
9199 		    infop->ip_opt_ill_index == 0) {
9200 			/* ipif_to_ire returns an held ire */
9201 			ire = ipif_to_ire(ipif);
9202 			if (ire == NULL)
9203 				goto err_ret;
9204 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9205 				goto err_ret;
9206 			save_ire = ire;
9207 
9208 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9209 			    "flags %04x\n",
9210 			    (void *)ire, (void *)ipif, flags));
9211 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9212 			    (fire->ire_flags & RTF_MULTIRT)) {
9213 				/*
9214 				 * As requested by flags, an IRE_OFFSUBNET was
9215 				 * looked up on that interface. This ire has
9216 				 * RTF_MULTIRT flag, so the resolution loop will
9217 				 * be re-entered to resolve additional routes on
9218 				 * other interfaces. For that purpose, a copy of
9219 				 * the packet is performed at this point.
9220 				 */
9221 				fire->ire_last_used_time = lbolt;
9222 				copy_mp = copymsg(first_mp);
9223 				if (copy_mp) {
9224 					MULTIRT_DEBUG_TAG(copy_mp);
9225 				}
9226 			}
9227 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9228 			    (fire->ire_flags & RTF_SETSRC)) {
9229 				/*
9230 				 * As requested by flags, an IRE_OFFSUBET was
9231 				 * looked up on that interface. This ire has
9232 				 * RTF_SETSRC flag, so the source address of the
9233 				 * packet must be changed.
9234 				 */
9235 				ipha->ipha_src = fire->ire_src_addr;
9236 			}
9237 		} else {
9238 			/*
9239 			 * The only ways we can come here are:
9240 			 * 1) IP_BOUND_IF socket option is set
9241 			 * 2) SO_DONTROUTE socket option is set
9242 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9243 			 * In all cases, the new ire will not be added
9244 			 * into cache table.
9245 			 */
9246 			ASSERT(connp == NULL || connp->conn_dontroute ||
9247 			    connp->conn_outgoing_ill != NULL ||
9248 			    infop->ip_opt_ill_index != 0);
9249 			ire_marks |= IRE_MARK_NOADD;
9250 		}
9251 
9252 		switch (ipif->ipif_net_type) {
9253 		case IRE_IF_NORESOLVER: {
9254 			/* We have what we need to build an IRE_CACHE. */
9255 
9256 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9257 			    (dst_ill->ill_resolver_mp == NULL)) {
9258 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9259 				    "for IRE_IF_NORESOLVER ire %p has "
9260 				    "no ill_resolver_mp\n",
9261 				    (void *)dst_ill, (void *)ire));
9262 				break;
9263 			}
9264 
9265 			/*
9266 			 * The new ire inherits the IRE_OFFSUBNET flags
9267 			 * and source address, if this was requested.
9268 			 */
9269 			ire = ire_create(
9270 			    (uchar_t *)&dst,		/* dest address */
9271 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9272 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9273 			    NULL,			/* gateway address */
9274 			    &ipif->ipif_mtu,
9275 			    NULL,			/* no src nce */
9276 			    dst_ill->ill_rq,		/* recv-from queue */
9277 			    dst_ill->ill_wq,		/* send-to queue */
9278 			    IRE_CACHE,
9279 			    src_ipif,
9280 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9281 			    (fire != NULL) ?		/* Parent handle */
9282 			    fire->ire_phandle : 0,
9283 			    (save_ire != NULL) ?	/* Interface handle */
9284 			    save_ire->ire_ihandle : 0,
9285 			    (fire != NULL) ?
9286 			    (fire->ire_flags &
9287 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9288 			    (save_ire == NULL ? &ire_uinfo_null :
9289 			    &save_ire->ire_uinfo),
9290 			    NULL,
9291 			    NULL,
9292 			    ipst);
9293 
9294 			if (ire == NULL) {
9295 				if (save_ire != NULL)
9296 					ire_refrele(save_ire);
9297 				break;
9298 			}
9299 
9300 			ire->ire_marks |= ire_marks;
9301 
9302 			/*
9303 			 * If IRE_MARK_NOADD is set then we need to convert
9304 			 * the max_fragp to a useable value now. This is
9305 			 * normally done in ire_add_v[46]. We also need to
9306 			 * associate the ire with an nce (normally would be
9307 			 * done in ip_wput_nondata()).
9308 			 *
9309 			 * Note that IRE_MARK_NOADD packets created here
9310 			 * do not have a non-null ire_mp pointer. The null
9311 			 * value of ire_bucket indicates that they were
9312 			 * never added.
9313 			 */
9314 			if (ire->ire_marks & IRE_MARK_NOADD) {
9315 				uint_t  max_frag;
9316 
9317 				max_frag = *ire->ire_max_fragp;
9318 				ire->ire_max_fragp = NULL;
9319 				ire->ire_max_frag = max_frag;
9320 
9321 				if ((ire->ire_nce = ndp_lookup_v4(
9322 				    ire_to_ill(ire),
9323 				    (ire->ire_gateway_addr != INADDR_ANY ?
9324 				    &ire->ire_gateway_addr : &ire->ire_addr),
9325 				    B_FALSE)) == NULL) {
9326 					if (save_ire != NULL)
9327 						ire_refrele(save_ire);
9328 					break;
9329 				}
9330 				ASSERT(ire->ire_nce->nce_state ==
9331 				    ND_REACHABLE);
9332 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9333 			}
9334 
9335 			/* Prevent save_ire from getting deleted */
9336 			if (save_ire != NULL) {
9337 				IRB_REFHOLD(save_ire->ire_bucket);
9338 				/* Has it been removed already ? */
9339 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9340 					IRB_REFRELE(save_ire->ire_bucket);
9341 					ire_refrele(save_ire);
9342 					break;
9343 				}
9344 			}
9345 
9346 			ire_add_then_send(q, ire, first_mp);
9347 
9348 			/* Assert that save_ire is not deleted yet. */
9349 			if (save_ire != NULL) {
9350 				ASSERT(save_ire->ire_ptpn != NULL);
9351 				IRB_REFRELE(save_ire->ire_bucket);
9352 				ire_refrele(save_ire);
9353 				save_ire = NULL;
9354 			}
9355 			if (fire != NULL) {
9356 				ire_refrele(fire);
9357 				fire = NULL;
9358 			}
9359 
9360 			/*
9361 			 * the resolution loop is re-entered if this
9362 			 * was requested through flags and if we
9363 			 * actually are in a multirouting case.
9364 			 */
9365 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9366 				boolean_t need_resolve =
9367 				    ire_multirt_need_resolve(ipha_dst,
9368 				    msg_getlabel(copy_mp), ipst);
9369 				if (!need_resolve) {
9370 					MULTIRT_DEBUG_UNTAG(copy_mp);
9371 					freemsg(copy_mp);
9372 					copy_mp = NULL;
9373 				} else {
9374 					/*
9375 					 * ipif_lookup_group() calls
9376 					 * ire_lookup_multi() that uses
9377 					 * ire_ftable_lookup() to find
9378 					 * an IRE_INTERFACE for the group.
9379 					 * In the multirt case,
9380 					 * ire_lookup_multi() then invokes
9381 					 * ire_multirt_lookup() to find
9382 					 * the next resolvable ire.
9383 					 * As a result, we obtain an new
9384 					 * interface, derived from the
9385 					 * next ire.
9386 					 */
9387 					ipif_refrele(ipif);
9388 					ipif = ipif_lookup_group(ipha_dst,
9389 					    zoneid, ipst);
9390 					ip2dbg(("ip_newroute_ipif: "
9391 					    "multirt dst %08x, ipif %p\n",
9392 					    htonl(dst), (void *)ipif));
9393 					if (ipif != NULL) {
9394 						mp = copy_mp;
9395 						copy_mp = NULL;
9396 						multirt_resolve_next = B_TRUE;
9397 						continue;
9398 					} else {
9399 						freemsg(copy_mp);
9400 					}
9401 				}
9402 			}
9403 			if (ipif != NULL)
9404 				ipif_refrele(ipif);
9405 			ill_refrele(dst_ill);
9406 			ipif_refrele(src_ipif);
9407 			return;
9408 		}
9409 		case IRE_IF_RESOLVER:
9410 			/*
9411 			 * We can't build an IRE_CACHE yet, but at least
9412 			 * we found a resolver that can help.
9413 			 */
9414 			res_mp = dst_ill->ill_resolver_mp;
9415 			if (!OK_RESOLVER_MP(res_mp))
9416 				break;
9417 
9418 			/*
9419 			 * We obtain a partial IRE_CACHE which we will pass
9420 			 * along with the resolver query.  When the response
9421 			 * comes back it will be there ready for us to add.
9422 			 * The new ire inherits the IRE_OFFSUBNET flags
9423 			 * and source address, if this was requested.
9424 			 * The ire_max_frag is atomically set under the
9425 			 * irebucket lock in ire_add_v[46]. Only in the
9426 			 * case of IRE_MARK_NOADD, we set it here itself.
9427 			 */
9428 			ire = ire_create_mp(
9429 			    (uchar_t *)&dst,		/* dest address */
9430 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9431 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9432 			    NULL,			/* gateway address */
9433 			    (ire_marks & IRE_MARK_NOADD) ?
9434 			    ipif->ipif_mtu : 0,		/* max_frag */
9435 			    NULL,			/* no src nce */
9436 			    dst_ill->ill_rq,		/* recv-from queue */
9437 			    dst_ill->ill_wq,		/* send-to queue */
9438 			    IRE_CACHE,
9439 			    src_ipif,
9440 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9441 			    (fire != NULL) ?		/* Parent handle */
9442 			    fire->ire_phandle : 0,
9443 			    (save_ire != NULL) ?	/* Interface handle */
9444 			    save_ire->ire_ihandle : 0,
9445 			    (fire != NULL) ?		/* flags if any */
9446 			    (fire->ire_flags &
9447 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9448 			    (save_ire == NULL ? &ire_uinfo_null :
9449 			    &save_ire->ire_uinfo),
9450 			    NULL,
9451 			    NULL,
9452 			    ipst);
9453 
9454 			if (save_ire != NULL) {
9455 				ire_refrele(save_ire);
9456 				save_ire = NULL;
9457 			}
9458 			if (ire == NULL)
9459 				break;
9460 
9461 			ire->ire_marks |= ire_marks;
9462 			/*
9463 			 * Construct message chain for the resolver of the
9464 			 * form:
9465 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9466 			 *
9467 			 * NOTE : ire will be added later when the response
9468 			 * comes back from ARP. If the response does not
9469 			 * come back, ARP frees the packet. For this reason,
9470 			 * we can't REFHOLD the bucket of save_ire to prevent
9471 			 * deletions. We may not be able to REFRELE the
9472 			 * bucket if the response never comes back.
9473 			 * Thus, before adding the ire, ire_add_v4 will make
9474 			 * sure that the interface route does not get deleted.
9475 			 * This is the only case unlike ip_newroute_v6,
9476 			 * ip_newroute_ipif_v6 where we can always prevent
9477 			 * deletions because ire_add_then_send is called after
9478 			 * creating the IRE.
9479 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9480 			 * does not add this IRE into the IRE CACHE.
9481 			 */
9482 			ASSERT(ire->ire_mp != NULL);
9483 			ire->ire_mp->b_cont = first_mp;
9484 			/* Have saved_mp handy, for cleanup if canput fails */
9485 			saved_mp = mp;
9486 			mp = copyb(res_mp);
9487 			if (mp == NULL) {
9488 				/* Prepare for cleanup */
9489 				mp = saved_mp; /* pkt */
9490 				ire_delete(ire); /* ire_mp */
9491 				ire = NULL;
9492 				if (copy_mp != NULL) {
9493 					MULTIRT_DEBUG_UNTAG(copy_mp);
9494 					freemsg(copy_mp);
9495 					copy_mp = NULL;
9496 				}
9497 				break;
9498 			}
9499 			linkb(mp, ire->ire_mp);
9500 
9501 			/*
9502 			 * Fill in the source and dest addrs for the resolver.
9503 			 * NOTE: this depends on memory layouts imposed by
9504 			 * ill_init().  There are corner cases above where we
9505 			 * might've created the IRE with an INADDR_ANY source
9506 			 * address (e.g., if the zeroth ipif on an underlying
9507 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9508 			 * on the ill has a usable test address).  If so, tell
9509 			 * ARP to use ipha_src as its sender address.
9510 			 */
9511 			areq = (areq_t *)mp->b_rptr;
9512 			addrp = (ipaddr_t *)((char *)areq +
9513 			    areq->areq_sender_addr_offset);
9514 			if (ire->ire_src_addr != INADDR_ANY)
9515 				*addrp = ire->ire_src_addr;
9516 			else
9517 				*addrp = ipha->ipha_src;
9518 			addrp = (ipaddr_t *)((char *)areq +
9519 			    areq->areq_target_addr_offset);
9520 			*addrp = dst;
9521 			/* Up to the resolver. */
9522 			if (canputnext(dst_ill->ill_rq) &&
9523 			    !(dst_ill->ill_arp_closing)) {
9524 				putnext(dst_ill->ill_rq, mp);
9525 				/*
9526 				 * The response will come back in ip_wput
9527 				 * with db_type IRE_DB_TYPE.
9528 				 */
9529 			} else {
9530 				mp->b_cont = NULL;
9531 				freeb(mp); /* areq */
9532 				ire_delete(ire); /* ire_mp */
9533 				saved_mp->b_next = NULL;
9534 				saved_mp->b_prev = NULL;
9535 				freemsg(first_mp); /* pkt */
9536 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9537 			}
9538 
9539 			if (fire != NULL) {
9540 				ire_refrele(fire);
9541 				fire = NULL;
9542 			}
9543 
9544 			/*
9545 			 * The resolution loop is re-entered if this was
9546 			 * requested through flags and we actually are
9547 			 * in a multirouting case.
9548 			 */
9549 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9550 				boolean_t need_resolve =
9551 				    ire_multirt_need_resolve(ipha_dst,
9552 				    msg_getlabel(copy_mp), ipst);
9553 				if (!need_resolve) {
9554 					MULTIRT_DEBUG_UNTAG(copy_mp);
9555 					freemsg(copy_mp);
9556 					copy_mp = NULL;
9557 				} else {
9558 					/*
9559 					 * ipif_lookup_group() calls
9560 					 * ire_lookup_multi() that uses
9561 					 * ire_ftable_lookup() to find
9562 					 * an IRE_INTERFACE for the group.
9563 					 * In the multirt case,
9564 					 * ire_lookup_multi() then invokes
9565 					 * ire_multirt_lookup() to find
9566 					 * the next resolvable ire.
9567 					 * As a result, we obtain an new
9568 					 * interface, derived from the
9569 					 * next ire.
9570 					 */
9571 					ipif_refrele(ipif);
9572 					ipif = ipif_lookup_group(ipha_dst,
9573 					    zoneid, ipst);
9574 					if (ipif != NULL) {
9575 						mp = copy_mp;
9576 						copy_mp = NULL;
9577 						multirt_resolve_next = B_TRUE;
9578 						continue;
9579 					} else {
9580 						freemsg(copy_mp);
9581 					}
9582 				}
9583 			}
9584 			if (ipif != NULL)
9585 				ipif_refrele(ipif);
9586 			ill_refrele(dst_ill);
9587 			ipif_refrele(src_ipif);
9588 			return;
9589 		default:
9590 			break;
9591 		}
9592 	} while (multirt_resolve_next);
9593 
9594 err_ret:
9595 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9596 	if (fire != NULL)
9597 		ire_refrele(fire);
9598 	ipif_refrele(ipif);
9599 	/* Did this packet originate externally? */
9600 	if (dst_ill != NULL)
9601 		ill_refrele(dst_ill);
9602 	if (src_ipif != NULL)
9603 		ipif_refrele(src_ipif);
9604 	if (mp->b_prev || mp->b_next) {
9605 		mp->b_next = NULL;
9606 		mp->b_prev = NULL;
9607 	} else {
9608 		/*
9609 		 * Since ip_wput() isn't close to finished, we fill
9610 		 * in enough of the header for credible error reporting.
9611 		 */
9612 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9613 			/* Failed */
9614 			freemsg(first_mp);
9615 			if (ire != NULL)
9616 				ire_refrele(ire);
9617 			return;
9618 		}
9619 	}
9620 	/*
9621 	 * At this point we will have ire only if RTF_BLACKHOLE
9622 	 * or RTF_REJECT flags are set on the IRE. It will not
9623 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9624 	 */
9625 	if (ire != NULL) {
9626 		if (ire->ire_flags & RTF_BLACKHOLE) {
9627 			ire_refrele(ire);
9628 			freemsg(first_mp);
9629 			return;
9630 		}
9631 		ire_refrele(ire);
9632 	}
9633 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9634 }
9635 
9636 /* Name/Value Table Lookup Routine */
9637 char *
9638 ip_nv_lookup(nv_t *nv, int value)
9639 {
9640 	if (!nv)
9641 		return (NULL);
9642 	for (; nv->nv_name; nv++) {
9643 		if (nv->nv_value == value)
9644 			return (nv->nv_name);
9645 	}
9646 	return ("unknown");
9647 }
9648 
9649 /*
9650  * This is a module open, i.e. this is a control stream for access
9651  * to a DLPI device.  We allocate an ill_t as the instance data in
9652  * this case.
9653  */
9654 int
9655 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9656 {
9657 	ill_t	*ill;
9658 	int	err;
9659 	zoneid_t zoneid;
9660 	netstack_t *ns;
9661 	ip_stack_t *ipst;
9662 
9663 	/*
9664 	 * Prevent unprivileged processes from pushing IP so that
9665 	 * they can't send raw IP.
9666 	 */
9667 	if (secpolicy_net_rawaccess(credp) != 0)
9668 		return (EPERM);
9669 
9670 	ns = netstack_find_by_cred(credp);
9671 	ASSERT(ns != NULL);
9672 	ipst = ns->netstack_ip;
9673 	ASSERT(ipst != NULL);
9674 
9675 	/*
9676 	 * For exclusive stacks we set the zoneid to zero
9677 	 * to make IP operate as if in the global zone.
9678 	 */
9679 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9680 		zoneid = GLOBAL_ZONEID;
9681 	else
9682 		zoneid = crgetzoneid(credp);
9683 
9684 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9685 	q->q_ptr = WR(q)->q_ptr = ill;
9686 	ill->ill_ipst = ipst;
9687 	ill->ill_zoneid = zoneid;
9688 
9689 	/*
9690 	 * ill_init initializes the ill fields and then sends down
9691 	 * down a DL_INFO_REQ after calling qprocson.
9692 	 */
9693 	err = ill_init(q, ill);
9694 	if (err != 0) {
9695 		mi_free(ill);
9696 		netstack_rele(ipst->ips_netstack);
9697 		q->q_ptr = NULL;
9698 		WR(q)->q_ptr = NULL;
9699 		return (err);
9700 	}
9701 
9702 	/* ill_init initializes the ipsq marking this thread as writer */
9703 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9704 	/* Wait for the DL_INFO_ACK */
9705 	mutex_enter(&ill->ill_lock);
9706 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9707 		/*
9708 		 * Return value of 0 indicates a pending signal.
9709 		 */
9710 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9711 		if (err == 0) {
9712 			mutex_exit(&ill->ill_lock);
9713 			(void) ip_close(q, 0);
9714 			return (EINTR);
9715 		}
9716 	}
9717 	mutex_exit(&ill->ill_lock);
9718 
9719 	/*
9720 	 * ip_rput_other could have set an error  in ill_error on
9721 	 * receipt of M_ERROR.
9722 	 */
9723 
9724 	err = ill->ill_error;
9725 	if (err != 0) {
9726 		(void) ip_close(q, 0);
9727 		return (err);
9728 	}
9729 
9730 	ill->ill_credp = credp;
9731 	crhold(credp);
9732 
9733 	mutex_enter(&ipst->ips_ip_mi_lock);
9734 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9735 	    credp);
9736 	mutex_exit(&ipst->ips_ip_mi_lock);
9737 	if (err) {
9738 		(void) ip_close(q, 0);
9739 		return (err);
9740 	}
9741 	return (0);
9742 }
9743 
9744 /* For /dev/ip aka AF_INET open */
9745 int
9746 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9747 {
9748 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9749 }
9750 
9751 /* For /dev/ip6 aka AF_INET6 open */
9752 int
9753 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9754 {
9755 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9756 }
9757 
9758 /* IP open routine. */
9759 int
9760 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9761     boolean_t isv6)
9762 {
9763 	conn_t 		*connp;
9764 	major_t		maj;
9765 	zoneid_t	zoneid;
9766 	netstack_t	*ns;
9767 	ip_stack_t	*ipst;
9768 
9769 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9770 
9771 	/* Allow reopen. */
9772 	if (q->q_ptr != NULL)
9773 		return (0);
9774 
9775 	if (sflag & MODOPEN) {
9776 		/* This is a module open */
9777 		return (ip_modopen(q, devp, flag, sflag, credp));
9778 	}
9779 
9780 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9781 		/*
9782 		 * Non streams based socket looking for a stream
9783 		 * to access IP
9784 		 */
9785 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9786 		    credp, isv6));
9787 	}
9788 
9789 	ns = netstack_find_by_cred(credp);
9790 	ASSERT(ns != NULL);
9791 	ipst = ns->netstack_ip;
9792 	ASSERT(ipst != NULL);
9793 
9794 	/*
9795 	 * For exclusive stacks we set the zoneid to zero
9796 	 * to make IP operate as if in the global zone.
9797 	 */
9798 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9799 		zoneid = GLOBAL_ZONEID;
9800 	else
9801 		zoneid = crgetzoneid(credp);
9802 
9803 	/*
9804 	 * We are opening as a device. This is an IP client stream, and we
9805 	 * allocate an conn_t as the instance data.
9806 	 */
9807 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9808 
9809 	/*
9810 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9811 	 * done by netstack_find_by_cred()
9812 	 */
9813 	netstack_rele(ipst->ips_netstack);
9814 
9815 	connp->conn_zoneid = zoneid;
9816 	connp->conn_sqp = NULL;
9817 	connp->conn_initial_sqp = NULL;
9818 	connp->conn_final_sqp = NULL;
9819 
9820 	connp->conn_upq = q;
9821 	q->q_ptr = WR(q)->q_ptr = connp;
9822 
9823 	if (flag & SO_SOCKSTR)
9824 		connp->conn_flags |= IPCL_SOCKET;
9825 
9826 	/* Minor tells us which /dev entry was opened */
9827 	if (isv6) {
9828 		connp->conn_flags |= IPCL_ISV6;
9829 		connp->conn_af_isv6 = B_TRUE;
9830 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9831 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9832 	} else {
9833 		connp->conn_af_isv6 = B_FALSE;
9834 		connp->conn_pkt_isv6 = B_FALSE;
9835 	}
9836 
9837 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9838 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9839 		connp->conn_minor_arena = ip_minor_arena_la;
9840 	} else {
9841 		/*
9842 		 * Either minor numbers in the large arena were exhausted
9843 		 * or a non socket application is doing the open.
9844 		 * Try to allocate from the small arena.
9845 		 */
9846 		if ((connp->conn_dev =
9847 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9848 			/* CONN_DEC_REF takes care of netstack_rele() */
9849 			q->q_ptr = WR(q)->q_ptr = NULL;
9850 			CONN_DEC_REF(connp);
9851 			return (EBUSY);
9852 		}
9853 		connp->conn_minor_arena = ip_minor_arena_sa;
9854 	}
9855 
9856 	maj = getemajor(*devp);
9857 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9858 
9859 	/*
9860 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9861 	 */
9862 	connp->conn_cred = credp;
9863 
9864 	/*
9865 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9866 	 */
9867 	connp->conn_recv = ip_conn_input;
9868 
9869 	crhold(connp->conn_cred);
9870 
9871 	/*
9872 	 * If the caller has the process-wide flag set, then default to MAC
9873 	 * exempt mode.  This allows read-down to unlabeled hosts.
9874 	 */
9875 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9876 		connp->conn_mac_exempt = B_TRUE;
9877 
9878 	connp->conn_rq = q;
9879 	connp->conn_wq = WR(q);
9880 
9881 	/* Non-zero default values */
9882 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9883 
9884 	/*
9885 	 * Make the conn globally visible to walkers
9886 	 */
9887 	ASSERT(connp->conn_ref == 1);
9888 	mutex_enter(&connp->conn_lock);
9889 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9890 	mutex_exit(&connp->conn_lock);
9891 
9892 	qprocson(q);
9893 
9894 	return (0);
9895 }
9896 
9897 /*
9898  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9899  * Note that there is no race since either ip_output function works - it
9900  * is just an optimization to enter the best ip_output routine directly.
9901  */
9902 void
9903 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9904     ip_stack_t *ipst)
9905 {
9906 	if (isv6)  {
9907 		if (bump_mib) {
9908 			BUMP_MIB(&ipst->ips_ip6_mib,
9909 			    ipIfStatsOutSwitchIPVersion);
9910 		}
9911 		connp->conn_send = ip_output_v6;
9912 		connp->conn_pkt_isv6 = B_TRUE;
9913 	} else {
9914 		if (bump_mib) {
9915 			BUMP_MIB(&ipst->ips_ip_mib,
9916 			    ipIfStatsOutSwitchIPVersion);
9917 		}
9918 		connp->conn_send = ip_output;
9919 		connp->conn_pkt_isv6 = B_FALSE;
9920 	}
9921 
9922 }
9923 
9924 /*
9925  * See if IPsec needs loading because of the options in mp.
9926  */
9927 static boolean_t
9928 ipsec_opt_present(mblk_t *mp)
9929 {
9930 	uint8_t *optcp, *next_optcp, *opt_endcp;
9931 	struct opthdr *opt;
9932 	struct T_opthdr *topt;
9933 	int opthdr_len;
9934 	t_uscalar_t optname, optlevel;
9935 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9936 	ipsec_req_t *ipsr;
9937 
9938 	/*
9939 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9940 	 * return TRUE.
9941 	 */
9942 
9943 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9944 	opt_endcp = optcp + tor->OPT_length;
9945 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9946 		opthdr_len = sizeof (struct T_opthdr);
9947 	} else {		/* O_OPTMGMT_REQ */
9948 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9949 		opthdr_len = sizeof (struct opthdr);
9950 	}
9951 	for (; optcp < opt_endcp; optcp = next_optcp) {
9952 		if (optcp + opthdr_len > opt_endcp)
9953 			return (B_FALSE);	/* Not enough option header. */
9954 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9955 			topt = (struct T_opthdr *)optcp;
9956 			optlevel = topt->level;
9957 			optname = topt->name;
9958 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9959 		} else {
9960 			opt = (struct opthdr *)optcp;
9961 			optlevel = opt->level;
9962 			optname = opt->name;
9963 			next_optcp = optcp + opthdr_len +
9964 			    _TPI_ALIGN_OPT(opt->len);
9965 		}
9966 		if ((next_optcp < optcp) || /* wraparound pointer space */
9967 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9968 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9969 			return (B_FALSE); /* bad option buffer */
9970 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9971 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9972 			/*
9973 			 * Check to see if it's an all-bypass or all-zeroes
9974 			 * IPsec request.  Don't bother loading IPsec if
9975 			 * the socket doesn't want to use it.  (A good example
9976 			 * is a bypass request.)
9977 			 *
9978 			 * Basically, if any of the non-NEVER bits are set,
9979 			 * load IPsec.
9980 			 */
9981 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9982 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9983 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9984 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9985 			    != 0)
9986 				return (B_TRUE);
9987 		}
9988 	}
9989 	return (B_FALSE);
9990 }
9991 
9992 /*
9993  * If conn is is waiting for ipsec to finish loading, kick it.
9994  */
9995 /* ARGSUSED */
9996 static void
9997 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9998 {
9999 	t_scalar_t	optreq_prim;
10000 	mblk_t		*mp;
10001 	cred_t		*cr;
10002 	int		err = 0;
10003 
10004 	/*
10005 	 * This function is called, after ipsec loading is complete.
10006 	 * Since IP checks exclusively and atomically (i.e it prevents
10007 	 * ipsec load from completing until ip_optcom_req completes)
10008 	 * whether ipsec load is complete, there cannot be a race with IP
10009 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10010 	 */
10011 	mutex_enter(&connp->conn_lock);
10012 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10013 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10014 		mp = connp->conn_ipsec_opt_mp;
10015 		connp->conn_ipsec_opt_mp = NULL;
10016 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10017 		mutex_exit(&connp->conn_lock);
10018 
10019 		/*
10020 		 * All Solaris components should pass a db_credp
10021 		 * for this TPI message, hence we ASSERT.
10022 		 * But in case there is some other M_PROTO that looks
10023 		 * like a TPI message sent by some other kernel
10024 		 * component, we check and return an error.
10025 		 */
10026 		cr = msg_getcred(mp, NULL);
10027 		ASSERT(cr != NULL);
10028 		if (cr == NULL) {
10029 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10030 			if (mp != NULL)
10031 				qreply(connp->conn_wq, mp);
10032 			return;
10033 		}
10034 
10035 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10036 
10037 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10038 		if (optreq_prim == T_OPTMGMT_REQ) {
10039 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10040 			    &ip_opt_obj, B_FALSE);
10041 		} else {
10042 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10043 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10044 			    &ip_opt_obj, B_FALSE);
10045 		}
10046 		if (err != EINPROGRESS)
10047 			CONN_OPER_PENDING_DONE(connp);
10048 		return;
10049 	}
10050 	mutex_exit(&connp->conn_lock);
10051 }
10052 
10053 /*
10054  * Called from the ipsec_loader thread, outside any perimeter, to tell
10055  * ip qenable any of the queues waiting for the ipsec loader to
10056  * complete.
10057  */
10058 void
10059 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10060 {
10061 	netstack_t *ns = ipss->ipsec_netstack;
10062 
10063 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10064 }
10065 
10066 /*
10067  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10068  * determines the grp on which it has to become exclusive, queues the mp
10069  * and IPSQ draining restarts the optmgmt
10070  */
10071 static boolean_t
10072 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10073 {
10074 	conn_t *connp = Q_TO_CONN(q);
10075 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10076 
10077 	/*
10078 	 * Take IPsec requests and treat them special.
10079 	 */
10080 	if (ipsec_opt_present(mp)) {
10081 		/* First check if IPsec is loaded. */
10082 		mutex_enter(&ipss->ipsec_loader_lock);
10083 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10084 			mutex_exit(&ipss->ipsec_loader_lock);
10085 			return (B_FALSE);
10086 		}
10087 		mutex_enter(&connp->conn_lock);
10088 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10089 
10090 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10091 		connp->conn_ipsec_opt_mp = mp;
10092 		mutex_exit(&connp->conn_lock);
10093 		mutex_exit(&ipss->ipsec_loader_lock);
10094 
10095 		ipsec_loader_loadnow(ipss);
10096 		return (B_TRUE);
10097 	}
10098 	return (B_FALSE);
10099 }
10100 
10101 /*
10102  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10103  * all of them are copied to the conn_t. If the req is "zero", the policy is
10104  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10105  * fields.
10106  * We keep only the latest setting of the policy and thus policy setting
10107  * is not incremental/cumulative.
10108  *
10109  * Requests to set policies with multiple alternative actions will
10110  * go through a different API.
10111  */
10112 int
10113 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10114 {
10115 	uint_t ah_req = 0;
10116 	uint_t esp_req = 0;
10117 	uint_t se_req = 0;
10118 	ipsec_selkey_t sel;
10119 	ipsec_act_t *actp = NULL;
10120 	uint_t nact;
10121 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10122 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10123 	ipsec_policy_root_t *pr;
10124 	ipsec_policy_head_t *ph;
10125 	int fam;
10126 	boolean_t is_pol_reset;
10127 	int error = 0;
10128 	netstack_t	*ns = connp->conn_netstack;
10129 	ip_stack_t	*ipst = ns->netstack_ip;
10130 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10131 
10132 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10133 
10134 	/*
10135 	 * The IP_SEC_OPT option does not allow variable length parameters,
10136 	 * hence a request cannot be NULL.
10137 	 */
10138 	if (req == NULL)
10139 		return (EINVAL);
10140 
10141 	ah_req = req->ipsr_ah_req;
10142 	esp_req = req->ipsr_esp_req;
10143 	se_req = req->ipsr_self_encap_req;
10144 
10145 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10146 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10147 		return (EINVAL);
10148 
10149 	/*
10150 	 * Are we dealing with a request to reset the policy (i.e.
10151 	 * zero requests).
10152 	 */
10153 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10154 	    (esp_req & REQ_MASK) == 0 &&
10155 	    (se_req & REQ_MASK) == 0);
10156 
10157 	if (!is_pol_reset) {
10158 		/*
10159 		 * If we couldn't load IPsec, fail with "protocol
10160 		 * not supported".
10161 		 * IPsec may not have been loaded for a request with zero
10162 		 * policies, so we don't fail in this case.
10163 		 */
10164 		mutex_enter(&ipss->ipsec_loader_lock);
10165 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10166 			mutex_exit(&ipss->ipsec_loader_lock);
10167 			return (EPROTONOSUPPORT);
10168 		}
10169 		mutex_exit(&ipss->ipsec_loader_lock);
10170 
10171 		/*
10172 		 * Test for valid requests. Invalid algorithms
10173 		 * need to be tested by IPsec code because new
10174 		 * algorithms can be added dynamically.
10175 		 */
10176 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10177 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10178 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10179 			return (EINVAL);
10180 		}
10181 
10182 		/*
10183 		 * Only privileged users can issue these
10184 		 * requests.
10185 		 */
10186 		if (((ah_req & IPSEC_PREF_NEVER) ||
10187 		    (esp_req & IPSEC_PREF_NEVER) ||
10188 		    (se_req & IPSEC_PREF_NEVER)) &&
10189 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10190 			return (EPERM);
10191 		}
10192 
10193 		/*
10194 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10195 		 * are mutually exclusive.
10196 		 */
10197 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10198 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10199 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10200 			/* Both of them are set */
10201 			return (EINVAL);
10202 		}
10203 	}
10204 
10205 	mutex_enter(&connp->conn_lock);
10206 
10207 	/*
10208 	 * If we have already cached policies in ip_bind_connected*(), don't
10209 	 * let them change now. We cache policies for connections
10210 	 * whose src,dst [addr, port] is known.
10211 	 */
10212 	if (connp->conn_policy_cached) {
10213 		mutex_exit(&connp->conn_lock);
10214 		return (EINVAL);
10215 	}
10216 
10217 	/*
10218 	 * We have a zero policies, reset the connection policy if already
10219 	 * set. This will cause the connection to inherit the
10220 	 * global policy, if any.
10221 	 */
10222 	if (is_pol_reset) {
10223 		if (connp->conn_policy != NULL) {
10224 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10225 			connp->conn_policy = NULL;
10226 		}
10227 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10228 		connp->conn_in_enforce_policy = B_FALSE;
10229 		connp->conn_out_enforce_policy = B_FALSE;
10230 		mutex_exit(&connp->conn_lock);
10231 		return (0);
10232 	}
10233 
10234 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10235 	    ipst->ips_netstack);
10236 	if (ph == NULL)
10237 		goto enomem;
10238 
10239 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10240 	if (actp == NULL)
10241 		goto enomem;
10242 
10243 	/*
10244 	 * Always allocate IPv4 policy entries, since they can also
10245 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10246 	 */
10247 	bzero(&sel, sizeof (sel));
10248 	sel.ipsl_valid = IPSL_IPV4;
10249 
10250 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10251 	    ipst->ips_netstack);
10252 	if (pin4 == NULL)
10253 		goto enomem;
10254 
10255 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10256 	    ipst->ips_netstack);
10257 	if (pout4 == NULL)
10258 		goto enomem;
10259 
10260 	if (connp->conn_af_isv6) {
10261 		/*
10262 		 * We're looking at a v6 socket, also allocate the
10263 		 * v6-specific entries...
10264 		 */
10265 		sel.ipsl_valid = IPSL_IPV6;
10266 		pin6 = ipsec_policy_create(&sel, actp, nact,
10267 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10268 		if (pin6 == NULL)
10269 			goto enomem;
10270 
10271 		pout6 = ipsec_policy_create(&sel, actp, nact,
10272 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10273 		if (pout6 == NULL)
10274 			goto enomem;
10275 
10276 		/*
10277 		 * .. and file them away in the right place.
10278 		 */
10279 		fam = IPSEC_AF_V6;
10280 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10281 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10282 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10283 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10284 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10285 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10286 	}
10287 
10288 	ipsec_actvec_free(actp, nact);
10289 
10290 	/*
10291 	 * File the v4 policies.
10292 	 */
10293 	fam = IPSEC_AF_V4;
10294 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10295 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10296 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10297 
10298 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10299 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10300 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10301 
10302 	/*
10303 	 * If the requests need security, set enforce_policy.
10304 	 * If the requests are IPSEC_PREF_NEVER, one should
10305 	 * still set conn_out_enforce_policy so that an ipsec_out
10306 	 * gets attached in ip_wput. This is needed so that
10307 	 * for connections that we don't cache policy in ip_bind,
10308 	 * if global policy matches in ip_wput_attach_policy, we
10309 	 * don't wrongly inherit global policy. Similarly, we need
10310 	 * to set conn_in_enforce_policy also so that we don't verify
10311 	 * policy wrongly.
10312 	 */
10313 	if ((ah_req & REQ_MASK) != 0 ||
10314 	    (esp_req & REQ_MASK) != 0 ||
10315 	    (se_req & REQ_MASK) != 0) {
10316 		connp->conn_in_enforce_policy = B_TRUE;
10317 		connp->conn_out_enforce_policy = B_TRUE;
10318 		connp->conn_flags |= IPCL_CHECK_POLICY;
10319 	}
10320 
10321 	mutex_exit(&connp->conn_lock);
10322 	return (error);
10323 #undef REQ_MASK
10324 
10325 	/*
10326 	 * Common memory-allocation-failure exit path.
10327 	 */
10328 enomem:
10329 	mutex_exit(&connp->conn_lock);
10330 	if (actp != NULL)
10331 		ipsec_actvec_free(actp, nact);
10332 	if (pin4 != NULL)
10333 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10334 	if (pout4 != NULL)
10335 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10336 	if (pin6 != NULL)
10337 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10338 	if (pout6 != NULL)
10339 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10340 	return (ENOMEM);
10341 }
10342 
10343 /*
10344  * Only for options that pass in an IP addr. Currently only V4 options
10345  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10346  * So this function assumes level is IPPROTO_IP
10347  */
10348 int
10349 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10350     mblk_t *first_mp)
10351 {
10352 	ipif_t *ipif = NULL;
10353 	int error;
10354 	ill_t *ill;
10355 	int zoneid;
10356 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10357 
10358 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10359 
10360 	if (addr != INADDR_ANY || checkonly) {
10361 		ASSERT(connp != NULL);
10362 		zoneid = IPCL_ZONEID(connp);
10363 		if (option == IP_NEXTHOP) {
10364 			ipif = ipif_lookup_onlink_addr(addr,
10365 			    connp->conn_zoneid, ipst);
10366 		} else {
10367 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10368 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10369 			    &error, ipst);
10370 		}
10371 		if (ipif == NULL) {
10372 			if (error == EINPROGRESS)
10373 				return (error);
10374 			if ((option == IP_MULTICAST_IF) ||
10375 			    (option == IP_NEXTHOP))
10376 				return (EHOSTUNREACH);
10377 			else
10378 				return (EINVAL);
10379 		} else if (checkonly) {
10380 			if (option == IP_MULTICAST_IF) {
10381 				ill = ipif->ipif_ill;
10382 				/* not supported by the virtual network iface */
10383 				if (IS_VNI(ill)) {
10384 					ipif_refrele(ipif);
10385 					return (EINVAL);
10386 				}
10387 			}
10388 			ipif_refrele(ipif);
10389 			return (0);
10390 		}
10391 		ill = ipif->ipif_ill;
10392 		mutex_enter(&connp->conn_lock);
10393 		mutex_enter(&ill->ill_lock);
10394 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10395 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10396 			mutex_exit(&ill->ill_lock);
10397 			mutex_exit(&connp->conn_lock);
10398 			ipif_refrele(ipif);
10399 			return (option == IP_MULTICAST_IF ?
10400 			    EHOSTUNREACH : EINVAL);
10401 		}
10402 	} else {
10403 		mutex_enter(&connp->conn_lock);
10404 	}
10405 
10406 	/* None of the options below are supported on the VNI */
10407 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10408 		mutex_exit(&ill->ill_lock);
10409 		mutex_exit(&connp->conn_lock);
10410 		ipif_refrele(ipif);
10411 		return (EINVAL);
10412 	}
10413 
10414 	switch (option) {
10415 	case IP_MULTICAST_IF:
10416 		connp->conn_multicast_ipif = ipif;
10417 		break;
10418 	case IP_NEXTHOP:
10419 		connp->conn_nexthop_v4 = addr;
10420 		connp->conn_nexthop_set = B_TRUE;
10421 		break;
10422 	}
10423 
10424 	if (ipif != NULL) {
10425 		mutex_exit(&ill->ill_lock);
10426 		mutex_exit(&connp->conn_lock);
10427 		ipif_refrele(ipif);
10428 		return (0);
10429 	}
10430 	mutex_exit(&connp->conn_lock);
10431 	/* We succeded in cleared the option */
10432 	return (0);
10433 }
10434 
10435 /*
10436  * For options that pass in an ifindex specifying the ill. V6 options always
10437  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10438  */
10439 int
10440 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10441     int level, int option, mblk_t *first_mp)
10442 {
10443 	ill_t *ill = NULL;
10444 	int error = 0;
10445 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10446 
10447 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10448 	if (ifindex != 0) {
10449 		ASSERT(connp != NULL);
10450 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10451 		    first_mp, ip_restart_optmgmt, &error, ipst);
10452 		if (ill != NULL) {
10453 			if (checkonly) {
10454 				/* not supported by the virtual network iface */
10455 				if (IS_VNI(ill)) {
10456 					ill_refrele(ill);
10457 					return (EINVAL);
10458 				}
10459 				ill_refrele(ill);
10460 				return (0);
10461 			}
10462 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10463 			    0, NULL)) {
10464 				ill_refrele(ill);
10465 				ill = NULL;
10466 				mutex_enter(&connp->conn_lock);
10467 				goto setit;
10468 			}
10469 			mutex_enter(&connp->conn_lock);
10470 			mutex_enter(&ill->ill_lock);
10471 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10472 				mutex_exit(&ill->ill_lock);
10473 				mutex_exit(&connp->conn_lock);
10474 				ill_refrele(ill);
10475 				ill = NULL;
10476 				mutex_enter(&connp->conn_lock);
10477 			}
10478 			goto setit;
10479 		} else if (error == EINPROGRESS) {
10480 			return (error);
10481 		} else {
10482 			error = 0;
10483 		}
10484 	}
10485 	mutex_enter(&connp->conn_lock);
10486 setit:
10487 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10488 
10489 	/*
10490 	 * The options below assume that the ILL (if any) transmits and/or
10491 	 * receives traffic. Neither of which is true for the virtual network
10492 	 * interface, so fail setting these on a VNI.
10493 	 */
10494 	if (IS_VNI(ill)) {
10495 		ASSERT(ill != NULL);
10496 		mutex_exit(&ill->ill_lock);
10497 		mutex_exit(&connp->conn_lock);
10498 		ill_refrele(ill);
10499 		return (EINVAL);
10500 	}
10501 
10502 	if (level == IPPROTO_IP) {
10503 		switch (option) {
10504 		case IP_BOUND_IF:
10505 			connp->conn_incoming_ill = ill;
10506 			connp->conn_outgoing_ill = ill;
10507 			break;
10508 
10509 		case IP_MULTICAST_IF:
10510 			/*
10511 			 * This option is an internal special. The socket
10512 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10513 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10514 			 * specifies an ifindex and we try first on V6 ill's.
10515 			 * If we don't find one, we they try using on v4 ill's
10516 			 * intenally and we come here.
10517 			 */
10518 			if (!checkonly && ill != NULL) {
10519 				ipif_t	*ipif;
10520 				ipif = ill->ill_ipif;
10521 
10522 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10523 					mutex_exit(&ill->ill_lock);
10524 					mutex_exit(&connp->conn_lock);
10525 					ill_refrele(ill);
10526 					ill = NULL;
10527 					mutex_enter(&connp->conn_lock);
10528 				} else {
10529 					connp->conn_multicast_ipif = ipif;
10530 				}
10531 			}
10532 			break;
10533 
10534 		case IP_DHCPINIT_IF:
10535 			if (connp->conn_dhcpinit_ill != NULL) {
10536 				/*
10537 				 * We've locked the conn so conn_cleanup_ill()
10538 				 * cannot clear conn_dhcpinit_ill -- so it's
10539 				 * safe to access the ill.
10540 				 */
10541 				ill_t *oill = connp->conn_dhcpinit_ill;
10542 
10543 				ASSERT(oill->ill_dhcpinit != 0);
10544 				atomic_dec_32(&oill->ill_dhcpinit);
10545 				connp->conn_dhcpinit_ill = NULL;
10546 			}
10547 
10548 			if (ill != NULL) {
10549 				connp->conn_dhcpinit_ill = ill;
10550 				atomic_inc_32(&ill->ill_dhcpinit);
10551 			}
10552 			break;
10553 		}
10554 	} else {
10555 		switch (option) {
10556 		case IPV6_BOUND_IF:
10557 			connp->conn_incoming_ill = ill;
10558 			connp->conn_outgoing_ill = ill;
10559 			break;
10560 
10561 		case IPV6_MULTICAST_IF:
10562 			/*
10563 			 * Set conn_multicast_ill to be the IPv6 ill.
10564 			 * Set conn_multicast_ipif to be an IPv4 ipif
10565 			 * for ifindex to make IPv4 mapped addresses
10566 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10567 			 * Even if no IPv6 ill exists for the ifindex
10568 			 * we need to check for an IPv4 ifindex in order
10569 			 * for this to work with mapped addresses. In that
10570 			 * case only set conn_multicast_ipif.
10571 			 */
10572 			if (!checkonly) {
10573 				if (ifindex == 0) {
10574 					connp->conn_multicast_ill = NULL;
10575 					connp->conn_multicast_ipif = NULL;
10576 				} else if (ill != NULL) {
10577 					connp->conn_multicast_ill = ill;
10578 				}
10579 			}
10580 			break;
10581 		}
10582 	}
10583 
10584 	if (ill != NULL) {
10585 		mutex_exit(&ill->ill_lock);
10586 		mutex_exit(&connp->conn_lock);
10587 		ill_refrele(ill);
10588 		return (0);
10589 	}
10590 	mutex_exit(&connp->conn_lock);
10591 	/*
10592 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10593 	 * locate the ill and could not set the option (ifindex != 0)
10594 	 */
10595 	return (ifindex == 0 ? 0 : EINVAL);
10596 }
10597 
10598 /* This routine sets socket options. */
10599 /* ARGSUSED */
10600 int
10601 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10602     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10603     void *dummy, cred_t *cr, mblk_t *first_mp)
10604 {
10605 	int		*i1 = (int *)invalp;
10606 	conn_t		*connp = Q_TO_CONN(q);
10607 	int		error = 0;
10608 	boolean_t	checkonly;
10609 	ire_t		*ire;
10610 	boolean_t	found;
10611 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10612 
10613 	switch (optset_context) {
10614 
10615 	case SETFN_OPTCOM_CHECKONLY:
10616 		checkonly = B_TRUE;
10617 		/*
10618 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10619 		 * inlen != 0 implies value supplied and
10620 		 * 	we have to "pretend" to set it.
10621 		 * inlen == 0 implies that there is no
10622 		 * 	value part in T_CHECK request and just validation
10623 		 * done elsewhere should be enough, we just return here.
10624 		 */
10625 		if (inlen == 0) {
10626 			*outlenp = 0;
10627 			return (0);
10628 		}
10629 		break;
10630 	case SETFN_OPTCOM_NEGOTIATE:
10631 	case SETFN_UD_NEGOTIATE:
10632 	case SETFN_CONN_NEGOTIATE:
10633 		checkonly = B_FALSE;
10634 		break;
10635 	default:
10636 		/*
10637 		 * We should never get here
10638 		 */
10639 		*outlenp = 0;
10640 		return (EINVAL);
10641 	}
10642 
10643 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10644 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10645 
10646 	/*
10647 	 * For fixed length options, no sanity check
10648 	 * of passed in length is done. It is assumed *_optcom_req()
10649 	 * routines do the right thing.
10650 	 */
10651 
10652 	switch (level) {
10653 	case SOL_SOCKET:
10654 		/*
10655 		 * conn_lock protects the bitfields, and is used to
10656 		 * set the fields atomically.
10657 		 */
10658 		switch (name) {
10659 		case SO_BROADCAST:
10660 			if (!checkonly) {
10661 				/* TODO: use value someplace? */
10662 				mutex_enter(&connp->conn_lock);
10663 				connp->conn_broadcast = *i1 ? 1 : 0;
10664 				mutex_exit(&connp->conn_lock);
10665 			}
10666 			break;	/* goto sizeof (int) option return */
10667 		case SO_USELOOPBACK:
10668 			if (!checkonly) {
10669 				/* TODO: use value someplace? */
10670 				mutex_enter(&connp->conn_lock);
10671 				connp->conn_loopback = *i1 ? 1 : 0;
10672 				mutex_exit(&connp->conn_lock);
10673 			}
10674 			break;	/* goto sizeof (int) option return */
10675 		case SO_DONTROUTE:
10676 			if (!checkonly) {
10677 				mutex_enter(&connp->conn_lock);
10678 				connp->conn_dontroute = *i1 ? 1 : 0;
10679 				mutex_exit(&connp->conn_lock);
10680 			}
10681 			break;	/* goto sizeof (int) option return */
10682 		case SO_REUSEADDR:
10683 			if (!checkonly) {
10684 				mutex_enter(&connp->conn_lock);
10685 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10686 				mutex_exit(&connp->conn_lock);
10687 			}
10688 			break;	/* goto sizeof (int) option return */
10689 		case SO_PROTOTYPE:
10690 			if (!checkonly) {
10691 				mutex_enter(&connp->conn_lock);
10692 				connp->conn_proto = *i1;
10693 				mutex_exit(&connp->conn_lock);
10694 			}
10695 			break;	/* goto sizeof (int) option return */
10696 		case SO_ALLZONES:
10697 			if (!checkonly) {
10698 				mutex_enter(&connp->conn_lock);
10699 				if (IPCL_IS_BOUND(connp)) {
10700 					mutex_exit(&connp->conn_lock);
10701 					return (EINVAL);
10702 				}
10703 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10704 				mutex_exit(&connp->conn_lock);
10705 			}
10706 			break;	/* goto sizeof (int) option return */
10707 		case SO_ANON_MLP:
10708 			if (!checkonly) {
10709 				mutex_enter(&connp->conn_lock);
10710 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10711 				mutex_exit(&connp->conn_lock);
10712 			}
10713 			break;	/* goto sizeof (int) option return */
10714 		case SO_MAC_EXEMPT:
10715 			if (secpolicy_net_mac_aware(cr) != 0 ||
10716 			    IPCL_IS_BOUND(connp))
10717 				return (EACCES);
10718 			if (!checkonly) {
10719 				mutex_enter(&connp->conn_lock);
10720 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10721 				mutex_exit(&connp->conn_lock);
10722 			}
10723 			break;	/* goto sizeof (int) option return */
10724 		default:
10725 			/*
10726 			 * "soft" error (negative)
10727 			 * option not handled at this level
10728 			 * Note: Do not modify *outlenp
10729 			 */
10730 			return (-EINVAL);
10731 		}
10732 		break;
10733 	case IPPROTO_IP:
10734 		switch (name) {
10735 		case IP_NEXTHOP:
10736 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10737 				return (EPERM);
10738 			/* FALLTHRU */
10739 		case IP_MULTICAST_IF: {
10740 			ipaddr_t addr = *i1;
10741 
10742 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10743 			    first_mp);
10744 			if (error != 0)
10745 				return (error);
10746 			break;	/* goto sizeof (int) option return */
10747 		}
10748 
10749 		case IP_MULTICAST_TTL:
10750 			/* Recorded in transport above IP */
10751 			*outvalp = *invalp;
10752 			*outlenp = sizeof (uchar_t);
10753 			return (0);
10754 		case IP_MULTICAST_LOOP:
10755 			if (!checkonly) {
10756 				mutex_enter(&connp->conn_lock);
10757 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10758 				mutex_exit(&connp->conn_lock);
10759 			}
10760 			*outvalp = *invalp;
10761 			*outlenp = sizeof (uchar_t);
10762 			return (0);
10763 		case IP_ADD_MEMBERSHIP:
10764 		case MCAST_JOIN_GROUP:
10765 		case IP_DROP_MEMBERSHIP:
10766 		case MCAST_LEAVE_GROUP: {
10767 			struct ip_mreq *mreqp;
10768 			struct group_req *greqp;
10769 			ire_t *ire;
10770 			boolean_t done = B_FALSE;
10771 			ipaddr_t group, ifaddr;
10772 			struct sockaddr_in *sin;
10773 			uint32_t *ifindexp;
10774 			boolean_t mcast_opt = B_TRUE;
10775 			mcast_record_t fmode;
10776 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10777 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10778 
10779 			switch (name) {
10780 			case IP_ADD_MEMBERSHIP:
10781 				mcast_opt = B_FALSE;
10782 				/* FALLTHRU */
10783 			case MCAST_JOIN_GROUP:
10784 				fmode = MODE_IS_EXCLUDE;
10785 				optfn = ip_opt_add_group;
10786 				break;
10787 
10788 			case IP_DROP_MEMBERSHIP:
10789 				mcast_opt = B_FALSE;
10790 				/* FALLTHRU */
10791 			case MCAST_LEAVE_GROUP:
10792 				fmode = MODE_IS_INCLUDE;
10793 				optfn = ip_opt_delete_group;
10794 				break;
10795 			}
10796 
10797 			if (mcast_opt) {
10798 				greqp = (struct group_req *)i1;
10799 				sin = (struct sockaddr_in *)&greqp->gr_group;
10800 				if (sin->sin_family != AF_INET) {
10801 					*outlenp = 0;
10802 					return (ENOPROTOOPT);
10803 				}
10804 				group = (ipaddr_t)sin->sin_addr.s_addr;
10805 				ifaddr = INADDR_ANY;
10806 				ifindexp = &greqp->gr_interface;
10807 			} else {
10808 				mreqp = (struct ip_mreq *)i1;
10809 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10810 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10811 				ifindexp = NULL;
10812 			}
10813 
10814 			/*
10815 			 * In the multirouting case, we need to replicate
10816 			 * the request on all interfaces that will take part
10817 			 * in replication.  We do so because multirouting is
10818 			 * reflective, thus we will probably receive multi-
10819 			 * casts on those interfaces.
10820 			 * The ip_multirt_apply_membership() succeeds if the
10821 			 * operation succeeds on at least one interface.
10822 			 */
10823 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10824 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10825 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10826 			if (ire != NULL) {
10827 				if (ire->ire_flags & RTF_MULTIRT) {
10828 					error = ip_multirt_apply_membership(
10829 					    optfn, ire, connp, checkonly, group,
10830 					    fmode, INADDR_ANY, first_mp);
10831 					done = B_TRUE;
10832 				}
10833 				ire_refrele(ire);
10834 			}
10835 			if (!done) {
10836 				error = optfn(connp, checkonly, group, ifaddr,
10837 				    ifindexp, fmode, INADDR_ANY, first_mp);
10838 			}
10839 			if (error) {
10840 				/*
10841 				 * EINPROGRESS is a soft error, needs retry
10842 				 * so don't make *outlenp zero.
10843 				 */
10844 				if (error != EINPROGRESS)
10845 					*outlenp = 0;
10846 				return (error);
10847 			}
10848 			/* OK return - copy input buffer into output buffer */
10849 			if (invalp != outvalp) {
10850 				/* don't trust bcopy for identical src/dst */
10851 				bcopy(invalp, outvalp, inlen);
10852 			}
10853 			*outlenp = inlen;
10854 			return (0);
10855 		}
10856 		case IP_BLOCK_SOURCE:
10857 		case IP_UNBLOCK_SOURCE:
10858 		case IP_ADD_SOURCE_MEMBERSHIP:
10859 		case IP_DROP_SOURCE_MEMBERSHIP:
10860 		case MCAST_BLOCK_SOURCE:
10861 		case MCAST_UNBLOCK_SOURCE:
10862 		case MCAST_JOIN_SOURCE_GROUP:
10863 		case MCAST_LEAVE_SOURCE_GROUP: {
10864 			struct ip_mreq_source *imreqp;
10865 			struct group_source_req *gsreqp;
10866 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10867 			uint32_t ifindex = 0;
10868 			mcast_record_t fmode;
10869 			struct sockaddr_in *sin;
10870 			ire_t *ire;
10871 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10872 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10873 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10874 
10875 			switch (name) {
10876 			case IP_BLOCK_SOURCE:
10877 				mcast_opt = B_FALSE;
10878 				/* FALLTHRU */
10879 			case MCAST_BLOCK_SOURCE:
10880 				fmode = MODE_IS_EXCLUDE;
10881 				optfn = ip_opt_add_group;
10882 				break;
10883 
10884 			case IP_UNBLOCK_SOURCE:
10885 				mcast_opt = B_FALSE;
10886 				/* FALLTHRU */
10887 			case MCAST_UNBLOCK_SOURCE:
10888 				fmode = MODE_IS_EXCLUDE;
10889 				optfn = ip_opt_delete_group;
10890 				break;
10891 
10892 			case IP_ADD_SOURCE_MEMBERSHIP:
10893 				mcast_opt = B_FALSE;
10894 				/* FALLTHRU */
10895 			case MCAST_JOIN_SOURCE_GROUP:
10896 				fmode = MODE_IS_INCLUDE;
10897 				optfn = ip_opt_add_group;
10898 				break;
10899 
10900 			case IP_DROP_SOURCE_MEMBERSHIP:
10901 				mcast_opt = B_FALSE;
10902 				/* FALLTHRU */
10903 			case MCAST_LEAVE_SOURCE_GROUP:
10904 				fmode = MODE_IS_INCLUDE;
10905 				optfn = ip_opt_delete_group;
10906 				break;
10907 			}
10908 
10909 			if (mcast_opt) {
10910 				gsreqp = (struct group_source_req *)i1;
10911 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10912 					*outlenp = 0;
10913 					return (ENOPROTOOPT);
10914 				}
10915 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10916 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10917 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10918 				src = (ipaddr_t)sin->sin_addr.s_addr;
10919 				ifindex = gsreqp->gsr_interface;
10920 			} else {
10921 				imreqp = (struct ip_mreq_source *)i1;
10922 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10923 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10924 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10925 			}
10926 
10927 			/*
10928 			 * In the multirouting case, we need to replicate
10929 			 * the request as noted in the mcast cases above.
10930 			 */
10931 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10932 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10933 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10934 			if (ire != NULL) {
10935 				if (ire->ire_flags & RTF_MULTIRT) {
10936 					error = ip_multirt_apply_membership(
10937 					    optfn, ire, connp, checkonly, grp,
10938 					    fmode, src, first_mp);
10939 					done = B_TRUE;
10940 				}
10941 				ire_refrele(ire);
10942 			}
10943 			if (!done) {
10944 				error = optfn(connp, checkonly, grp, ifaddr,
10945 				    &ifindex, fmode, src, first_mp);
10946 			}
10947 			if (error != 0) {
10948 				/*
10949 				 * EINPROGRESS is a soft error, needs retry
10950 				 * so don't make *outlenp zero.
10951 				 */
10952 				if (error != EINPROGRESS)
10953 					*outlenp = 0;
10954 				return (error);
10955 			}
10956 			/* OK return - copy input buffer into output buffer */
10957 			if (invalp != outvalp) {
10958 				bcopy(invalp, outvalp, inlen);
10959 			}
10960 			*outlenp = inlen;
10961 			return (0);
10962 		}
10963 		case IP_SEC_OPT:
10964 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10965 			if (error != 0) {
10966 				*outlenp = 0;
10967 				return (error);
10968 			}
10969 			break;
10970 		case IP_HDRINCL:
10971 		case IP_OPTIONS:
10972 		case T_IP_OPTIONS:
10973 		case IP_TOS:
10974 		case T_IP_TOS:
10975 		case IP_TTL:
10976 		case IP_RECVDSTADDR:
10977 		case IP_RECVOPTS:
10978 			/* OK return - copy input buffer into output buffer */
10979 			if (invalp != outvalp) {
10980 				/* don't trust bcopy for identical src/dst */
10981 				bcopy(invalp, outvalp, inlen);
10982 			}
10983 			*outlenp = inlen;
10984 			return (0);
10985 		case IP_RECVIF:
10986 			/* Retrieve the inbound interface index */
10987 			if (!checkonly) {
10988 				mutex_enter(&connp->conn_lock);
10989 				connp->conn_recvif = *i1 ? 1 : 0;
10990 				mutex_exit(&connp->conn_lock);
10991 			}
10992 			break;	/* goto sizeof (int) option return */
10993 		case IP_RECVPKTINFO:
10994 			if (!checkonly) {
10995 				mutex_enter(&connp->conn_lock);
10996 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10997 				mutex_exit(&connp->conn_lock);
10998 			}
10999 			break;	/* goto sizeof (int) option return */
11000 		case IP_RECVSLLA:
11001 			/* Retrieve the source link layer address */
11002 			if (!checkonly) {
11003 				mutex_enter(&connp->conn_lock);
11004 				connp->conn_recvslla = *i1 ? 1 : 0;
11005 				mutex_exit(&connp->conn_lock);
11006 			}
11007 			break;	/* goto sizeof (int) option return */
11008 		case MRT_INIT:
11009 		case MRT_DONE:
11010 		case MRT_ADD_VIF:
11011 		case MRT_DEL_VIF:
11012 		case MRT_ADD_MFC:
11013 		case MRT_DEL_MFC:
11014 		case MRT_ASSERT:
11015 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11016 				*outlenp = 0;
11017 				return (error);
11018 			}
11019 			error = ip_mrouter_set((int)name, q, checkonly,
11020 			    (uchar_t *)invalp, inlen, first_mp);
11021 			if (error) {
11022 				*outlenp = 0;
11023 				return (error);
11024 			}
11025 			/* OK return - copy input buffer into output buffer */
11026 			if (invalp != outvalp) {
11027 				/* don't trust bcopy for identical src/dst */
11028 				bcopy(invalp, outvalp, inlen);
11029 			}
11030 			*outlenp = inlen;
11031 			return (0);
11032 		case IP_BOUND_IF:
11033 		case IP_DHCPINIT_IF:
11034 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11035 			    level, name, first_mp);
11036 			if (error != 0)
11037 				return (error);
11038 			break; 		/* goto sizeof (int) option return */
11039 
11040 		case IP_UNSPEC_SRC:
11041 			/* Allow sending with a zero source address */
11042 			if (!checkonly) {
11043 				mutex_enter(&connp->conn_lock);
11044 				connp->conn_unspec_src = *i1 ? 1 : 0;
11045 				mutex_exit(&connp->conn_lock);
11046 			}
11047 			break;	/* goto sizeof (int) option return */
11048 		default:
11049 			/*
11050 			 * "soft" error (negative)
11051 			 * option not handled at this level
11052 			 * Note: Do not modify *outlenp
11053 			 */
11054 			return (-EINVAL);
11055 		}
11056 		break;
11057 	case IPPROTO_IPV6:
11058 		switch (name) {
11059 		case IPV6_BOUND_IF:
11060 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11061 			    level, name, first_mp);
11062 			if (error != 0)
11063 				return (error);
11064 			break; 		/* goto sizeof (int) option return */
11065 
11066 		case IPV6_MULTICAST_IF:
11067 			/*
11068 			 * The only possible errors are EINPROGRESS and
11069 			 * EINVAL. EINPROGRESS will be restarted and is not
11070 			 * a hard error. We call this option on both V4 and V6
11071 			 * If both return EINVAL, then this call returns
11072 			 * EINVAL. If at least one of them succeeds we
11073 			 * return success.
11074 			 */
11075 			found = B_FALSE;
11076 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11077 			    level, name, first_mp);
11078 			if (error == EINPROGRESS)
11079 				return (error);
11080 			if (error == 0)
11081 				found = B_TRUE;
11082 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11083 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11084 			if (error == 0)
11085 				found = B_TRUE;
11086 			if (!found)
11087 				return (error);
11088 			break; 		/* goto sizeof (int) option return */
11089 
11090 		case IPV6_MULTICAST_HOPS:
11091 			/* Recorded in transport above IP */
11092 			break;	/* goto sizeof (int) option return */
11093 		case IPV6_MULTICAST_LOOP:
11094 			if (!checkonly) {
11095 				mutex_enter(&connp->conn_lock);
11096 				connp->conn_multicast_loop = *i1;
11097 				mutex_exit(&connp->conn_lock);
11098 			}
11099 			break;	/* goto sizeof (int) option return */
11100 		case IPV6_JOIN_GROUP:
11101 		case MCAST_JOIN_GROUP:
11102 		case IPV6_LEAVE_GROUP:
11103 		case MCAST_LEAVE_GROUP: {
11104 			struct ipv6_mreq *ip_mreqp;
11105 			struct group_req *greqp;
11106 			ire_t *ire;
11107 			boolean_t done = B_FALSE;
11108 			in6_addr_t groupv6;
11109 			uint32_t ifindex;
11110 			boolean_t mcast_opt = B_TRUE;
11111 			mcast_record_t fmode;
11112 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11113 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11114 
11115 			switch (name) {
11116 			case IPV6_JOIN_GROUP:
11117 				mcast_opt = B_FALSE;
11118 				/* FALLTHRU */
11119 			case MCAST_JOIN_GROUP:
11120 				fmode = MODE_IS_EXCLUDE;
11121 				optfn = ip_opt_add_group_v6;
11122 				break;
11123 
11124 			case IPV6_LEAVE_GROUP:
11125 				mcast_opt = B_FALSE;
11126 				/* FALLTHRU */
11127 			case MCAST_LEAVE_GROUP:
11128 				fmode = MODE_IS_INCLUDE;
11129 				optfn = ip_opt_delete_group_v6;
11130 				break;
11131 			}
11132 
11133 			if (mcast_opt) {
11134 				struct sockaddr_in *sin;
11135 				struct sockaddr_in6 *sin6;
11136 				greqp = (struct group_req *)i1;
11137 				if (greqp->gr_group.ss_family == AF_INET) {
11138 					sin = (struct sockaddr_in *)
11139 					    &(greqp->gr_group);
11140 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11141 					    &groupv6);
11142 				} else {
11143 					sin6 = (struct sockaddr_in6 *)
11144 					    &(greqp->gr_group);
11145 					groupv6 = sin6->sin6_addr;
11146 				}
11147 				ifindex = greqp->gr_interface;
11148 			} else {
11149 				ip_mreqp = (struct ipv6_mreq *)i1;
11150 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11151 				ifindex = ip_mreqp->ipv6mr_interface;
11152 			}
11153 			/*
11154 			 * In the multirouting case, we need to replicate
11155 			 * the request on all interfaces that will take part
11156 			 * in replication.  We do so because multirouting is
11157 			 * reflective, thus we will probably receive multi-
11158 			 * casts on those interfaces.
11159 			 * The ip_multirt_apply_membership_v6() succeeds if
11160 			 * the operation succeeds on at least one interface.
11161 			 */
11162 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11163 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11164 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11165 			if (ire != NULL) {
11166 				if (ire->ire_flags & RTF_MULTIRT) {
11167 					error = ip_multirt_apply_membership_v6(
11168 					    optfn, ire, connp, checkonly,
11169 					    &groupv6, fmode, &ipv6_all_zeros,
11170 					    first_mp);
11171 					done = B_TRUE;
11172 				}
11173 				ire_refrele(ire);
11174 			}
11175 			if (!done) {
11176 				error = optfn(connp, checkonly, &groupv6,
11177 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11178 			}
11179 			if (error) {
11180 				/*
11181 				 * EINPROGRESS is a soft error, needs retry
11182 				 * so don't make *outlenp zero.
11183 				 */
11184 				if (error != EINPROGRESS)
11185 					*outlenp = 0;
11186 				return (error);
11187 			}
11188 			/* OK return - copy input buffer into output buffer */
11189 			if (invalp != outvalp) {
11190 				/* don't trust bcopy for identical src/dst */
11191 				bcopy(invalp, outvalp, inlen);
11192 			}
11193 			*outlenp = inlen;
11194 			return (0);
11195 		}
11196 		case MCAST_BLOCK_SOURCE:
11197 		case MCAST_UNBLOCK_SOURCE:
11198 		case MCAST_JOIN_SOURCE_GROUP:
11199 		case MCAST_LEAVE_SOURCE_GROUP: {
11200 			struct group_source_req *gsreqp;
11201 			in6_addr_t v6grp, v6src;
11202 			uint32_t ifindex;
11203 			mcast_record_t fmode;
11204 			ire_t *ire;
11205 			boolean_t done = B_FALSE;
11206 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11207 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11208 
11209 			switch (name) {
11210 			case MCAST_BLOCK_SOURCE:
11211 				fmode = MODE_IS_EXCLUDE;
11212 				optfn = ip_opt_add_group_v6;
11213 				break;
11214 			case MCAST_UNBLOCK_SOURCE:
11215 				fmode = MODE_IS_EXCLUDE;
11216 				optfn = ip_opt_delete_group_v6;
11217 				break;
11218 			case MCAST_JOIN_SOURCE_GROUP:
11219 				fmode = MODE_IS_INCLUDE;
11220 				optfn = ip_opt_add_group_v6;
11221 				break;
11222 			case MCAST_LEAVE_SOURCE_GROUP:
11223 				fmode = MODE_IS_INCLUDE;
11224 				optfn = ip_opt_delete_group_v6;
11225 				break;
11226 			}
11227 
11228 			gsreqp = (struct group_source_req *)i1;
11229 			ifindex = gsreqp->gsr_interface;
11230 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11231 				struct sockaddr_in *s;
11232 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11233 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11234 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11235 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11236 			} else {
11237 				struct sockaddr_in6 *s6;
11238 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11239 				v6grp = s6->sin6_addr;
11240 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11241 				v6src = s6->sin6_addr;
11242 			}
11243 
11244 			/*
11245 			 * In the multirouting case, we need to replicate
11246 			 * the request as noted in the mcast cases above.
11247 			 */
11248 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11249 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11250 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11251 			if (ire != NULL) {
11252 				if (ire->ire_flags & RTF_MULTIRT) {
11253 					error = ip_multirt_apply_membership_v6(
11254 					    optfn, ire, connp, checkonly,
11255 					    &v6grp, fmode, &v6src, first_mp);
11256 					done = B_TRUE;
11257 				}
11258 				ire_refrele(ire);
11259 			}
11260 			if (!done) {
11261 				error = optfn(connp, checkonly, &v6grp,
11262 				    ifindex, fmode, &v6src, first_mp);
11263 			}
11264 			if (error != 0) {
11265 				/*
11266 				 * EINPROGRESS is a soft error, needs retry
11267 				 * so don't make *outlenp zero.
11268 				 */
11269 				if (error != EINPROGRESS)
11270 					*outlenp = 0;
11271 				return (error);
11272 			}
11273 			/* OK return - copy input buffer into output buffer */
11274 			if (invalp != outvalp) {
11275 				bcopy(invalp, outvalp, inlen);
11276 			}
11277 			*outlenp = inlen;
11278 			return (0);
11279 		}
11280 		case IPV6_UNICAST_HOPS:
11281 			/* Recorded in transport above IP */
11282 			break;	/* goto sizeof (int) option return */
11283 		case IPV6_UNSPEC_SRC:
11284 			/* Allow sending with a zero source address */
11285 			if (!checkonly) {
11286 				mutex_enter(&connp->conn_lock);
11287 				connp->conn_unspec_src = *i1 ? 1 : 0;
11288 				mutex_exit(&connp->conn_lock);
11289 			}
11290 			break;	/* goto sizeof (int) option return */
11291 		case IPV6_RECVPKTINFO:
11292 			if (!checkonly) {
11293 				mutex_enter(&connp->conn_lock);
11294 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11295 				mutex_exit(&connp->conn_lock);
11296 			}
11297 			break;	/* goto sizeof (int) option return */
11298 		case IPV6_RECVTCLASS:
11299 			if (!checkonly) {
11300 				if (*i1 < 0 || *i1 > 1) {
11301 					return (EINVAL);
11302 				}
11303 				mutex_enter(&connp->conn_lock);
11304 				connp->conn_ipv6_recvtclass = *i1;
11305 				mutex_exit(&connp->conn_lock);
11306 			}
11307 			break;
11308 		case IPV6_RECVPATHMTU:
11309 			if (!checkonly) {
11310 				if (*i1 < 0 || *i1 > 1) {
11311 					return (EINVAL);
11312 				}
11313 				mutex_enter(&connp->conn_lock);
11314 				connp->conn_ipv6_recvpathmtu = *i1;
11315 				mutex_exit(&connp->conn_lock);
11316 			}
11317 			break;
11318 		case IPV6_RECVHOPLIMIT:
11319 			if (!checkonly) {
11320 				mutex_enter(&connp->conn_lock);
11321 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11322 				mutex_exit(&connp->conn_lock);
11323 			}
11324 			break;	/* goto sizeof (int) option return */
11325 		case IPV6_RECVHOPOPTS:
11326 			if (!checkonly) {
11327 				mutex_enter(&connp->conn_lock);
11328 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11329 				mutex_exit(&connp->conn_lock);
11330 			}
11331 			break;	/* goto sizeof (int) option return */
11332 		case IPV6_RECVDSTOPTS:
11333 			if (!checkonly) {
11334 				mutex_enter(&connp->conn_lock);
11335 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11336 				mutex_exit(&connp->conn_lock);
11337 			}
11338 			break;	/* goto sizeof (int) option return */
11339 		case IPV6_RECVRTHDR:
11340 			if (!checkonly) {
11341 				mutex_enter(&connp->conn_lock);
11342 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11343 				mutex_exit(&connp->conn_lock);
11344 			}
11345 			break;	/* goto sizeof (int) option return */
11346 		case IPV6_RECVRTHDRDSTOPTS:
11347 			if (!checkonly) {
11348 				mutex_enter(&connp->conn_lock);
11349 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11350 				mutex_exit(&connp->conn_lock);
11351 			}
11352 			break;	/* goto sizeof (int) option return */
11353 		case IPV6_PKTINFO:
11354 			if (inlen == 0)
11355 				return (-EINVAL);	/* clearing option */
11356 			error = ip6_set_pktinfo(cr, connp,
11357 			    (struct in6_pktinfo *)invalp);
11358 			if (error != 0)
11359 				*outlenp = 0;
11360 			else
11361 				*outlenp = inlen;
11362 			return (error);
11363 		case IPV6_NEXTHOP: {
11364 			struct sockaddr_in6 *sin6;
11365 
11366 			/* Verify that the nexthop is reachable */
11367 			if (inlen == 0)
11368 				return (-EINVAL);	/* clearing option */
11369 
11370 			sin6 = (struct sockaddr_in6 *)invalp;
11371 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11372 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11373 			    NULL, MATCH_IRE_DEFAULT, ipst);
11374 
11375 			if (ire == NULL) {
11376 				*outlenp = 0;
11377 				return (EHOSTUNREACH);
11378 			}
11379 			ire_refrele(ire);
11380 			return (-EINVAL);
11381 		}
11382 		case IPV6_SEC_OPT:
11383 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11384 			if (error != 0) {
11385 				*outlenp = 0;
11386 				return (error);
11387 			}
11388 			break;
11389 		case IPV6_SRC_PREFERENCES: {
11390 			/*
11391 			 * This is implemented strictly in the ip module
11392 			 * (here and in tcp_opt_*() to accomodate tcp
11393 			 * sockets).  Modules above ip pass this option
11394 			 * down here since ip is the only one that needs to
11395 			 * be aware of source address preferences.
11396 			 *
11397 			 * This socket option only affects connected
11398 			 * sockets that haven't already bound to a specific
11399 			 * IPv6 address.  In other words, sockets that
11400 			 * don't call bind() with an address other than the
11401 			 * unspecified address and that call connect().
11402 			 * ip_bind_connected_v6() passes these preferences
11403 			 * to the ipif_select_source_v6() function.
11404 			 */
11405 			if (inlen != sizeof (uint32_t))
11406 				return (EINVAL);
11407 			error = ip6_set_src_preferences(connp,
11408 			    *(uint32_t *)invalp);
11409 			if (error != 0) {
11410 				*outlenp = 0;
11411 				return (error);
11412 			} else {
11413 				*outlenp = sizeof (uint32_t);
11414 			}
11415 			break;
11416 		}
11417 		case IPV6_V6ONLY:
11418 			if (*i1 < 0 || *i1 > 1) {
11419 				return (EINVAL);
11420 			}
11421 			mutex_enter(&connp->conn_lock);
11422 			connp->conn_ipv6_v6only = *i1;
11423 			mutex_exit(&connp->conn_lock);
11424 			break;
11425 		default:
11426 			return (-EINVAL);
11427 		}
11428 		break;
11429 	default:
11430 		/*
11431 		 * "soft" error (negative)
11432 		 * option not handled at this level
11433 		 * Note: Do not modify *outlenp
11434 		 */
11435 		return (-EINVAL);
11436 	}
11437 	/*
11438 	 * Common case of return from an option that is sizeof (int)
11439 	 */
11440 	*(int *)outvalp = *i1;
11441 	*outlenp = sizeof (int);
11442 	return (0);
11443 }
11444 
11445 /*
11446  * This routine gets default values of certain options whose default
11447  * values are maintained by protocol specific code
11448  */
11449 /* ARGSUSED */
11450 int
11451 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11452 {
11453 	int *i1 = (int *)ptr;
11454 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11455 
11456 	switch (level) {
11457 	case IPPROTO_IP:
11458 		switch (name) {
11459 		case IP_MULTICAST_TTL:
11460 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11461 			return (sizeof (uchar_t));
11462 		case IP_MULTICAST_LOOP:
11463 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11464 			return (sizeof (uchar_t));
11465 		default:
11466 			return (-1);
11467 		}
11468 	case IPPROTO_IPV6:
11469 		switch (name) {
11470 		case IPV6_UNICAST_HOPS:
11471 			*i1 = ipst->ips_ipv6_def_hops;
11472 			return (sizeof (int));
11473 		case IPV6_MULTICAST_HOPS:
11474 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11475 			return (sizeof (int));
11476 		case IPV6_MULTICAST_LOOP:
11477 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11478 			return (sizeof (int));
11479 		case IPV6_V6ONLY:
11480 			*i1 = 1;
11481 			return (sizeof (int));
11482 		default:
11483 			return (-1);
11484 		}
11485 	default:
11486 		return (-1);
11487 	}
11488 	/* NOTREACHED */
11489 }
11490 
11491 /*
11492  * Given a destination address and a pointer to where to put the information
11493  * this routine fills in the mtuinfo.
11494  */
11495 int
11496 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11497     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11498 {
11499 	ire_t *ire;
11500 	ip_stack_t	*ipst = ns->netstack_ip;
11501 
11502 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11503 		return (-1);
11504 
11505 	bzero(mtuinfo, sizeof (*mtuinfo));
11506 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11507 	mtuinfo->ip6m_addr.sin6_port = port;
11508 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11509 
11510 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11511 	if (ire != NULL) {
11512 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11513 		ire_refrele(ire);
11514 	} else {
11515 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11516 	}
11517 	return (sizeof (struct ip6_mtuinfo));
11518 }
11519 
11520 /*
11521  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11522  * checking of cred and that ip_g_mrouter is set should be done and
11523  * isn't.  This doesn't matter as the error checking is done properly for the
11524  * other MRT options coming in through ip_opt_set.
11525  */
11526 int
11527 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11528 {
11529 	conn_t		*connp = Q_TO_CONN(q);
11530 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11531 
11532 	switch (level) {
11533 	case IPPROTO_IP:
11534 		switch (name) {
11535 		case MRT_VERSION:
11536 		case MRT_ASSERT:
11537 			(void) ip_mrouter_get(name, q, ptr);
11538 			return (sizeof (int));
11539 		case IP_SEC_OPT:
11540 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11541 		case IP_NEXTHOP:
11542 			if (connp->conn_nexthop_set) {
11543 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11544 				return (sizeof (ipaddr_t));
11545 			} else
11546 				return (0);
11547 		case IP_RECVPKTINFO:
11548 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11549 			return (sizeof (int));
11550 		default:
11551 			break;
11552 		}
11553 		break;
11554 	case IPPROTO_IPV6:
11555 		switch (name) {
11556 		case IPV6_SEC_OPT:
11557 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11558 		case IPV6_SRC_PREFERENCES: {
11559 			return (ip6_get_src_preferences(connp,
11560 			    (uint32_t *)ptr));
11561 		}
11562 		case IPV6_V6ONLY:
11563 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11564 			return (sizeof (int));
11565 		case IPV6_PATHMTU:
11566 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11567 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11568 		default:
11569 			break;
11570 		}
11571 		break;
11572 	default:
11573 		break;
11574 	}
11575 	return (-1);
11576 }
11577 /* Named Dispatch routine to get a current value out of our parameter table. */
11578 /* ARGSUSED */
11579 static int
11580 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11581 {
11582 	ipparam_t *ippa = (ipparam_t *)cp;
11583 
11584 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11585 	return (0);
11586 }
11587 
11588 /* ARGSUSED */
11589 static int
11590 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11591 {
11592 
11593 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11594 	return (0);
11595 }
11596 
11597 /*
11598  * Set ip{,6}_forwarding values.  This means walking through all of the
11599  * ill's and toggling their forwarding values.
11600  */
11601 /* ARGSUSED */
11602 static int
11603 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11604 {
11605 	long new_value;
11606 	int *forwarding_value = (int *)cp;
11607 	ill_t *ill;
11608 	boolean_t isv6;
11609 	ill_walk_context_t ctx;
11610 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11611 
11612 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11613 
11614 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11615 	    new_value < 0 || new_value > 1) {
11616 		return (EINVAL);
11617 	}
11618 
11619 	*forwarding_value = new_value;
11620 
11621 	/*
11622 	 * Regardless of the current value of ip_forwarding, set all per-ill
11623 	 * values of ip_forwarding to the value being set.
11624 	 *
11625 	 * Bring all the ill's up to date with the new global value.
11626 	 */
11627 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11628 
11629 	if (isv6)
11630 		ill = ILL_START_WALK_V6(&ctx, ipst);
11631 	else
11632 		ill = ILL_START_WALK_V4(&ctx, ipst);
11633 
11634 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11635 		(void) ill_forward_set(ill, new_value != 0);
11636 
11637 	rw_exit(&ipst->ips_ill_g_lock);
11638 	return (0);
11639 }
11640 
11641 /*
11642  * Walk through the param array specified registering each element with the
11643  * Named Dispatch handler. This is called only during init. So it is ok
11644  * not to acquire any locks
11645  */
11646 static boolean_t
11647 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11648     ipndp_t *ipnd, size_t ipnd_cnt)
11649 {
11650 	for (; ippa_cnt-- > 0; ippa++) {
11651 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11652 			if (!nd_load(ndp, ippa->ip_param_name,
11653 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11654 				nd_free(ndp);
11655 				return (B_FALSE);
11656 			}
11657 		}
11658 	}
11659 
11660 	for (; ipnd_cnt-- > 0; ipnd++) {
11661 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11662 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11663 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11664 			    ipnd->ip_ndp_data)) {
11665 				nd_free(ndp);
11666 				return (B_FALSE);
11667 			}
11668 		}
11669 	}
11670 
11671 	return (B_TRUE);
11672 }
11673 
11674 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11675 /* ARGSUSED */
11676 static int
11677 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11678 {
11679 	long		new_value;
11680 	ipparam_t	*ippa = (ipparam_t *)cp;
11681 
11682 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11683 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11684 		return (EINVAL);
11685 	}
11686 	ippa->ip_param_value = new_value;
11687 	return (0);
11688 }
11689 
11690 /*
11691  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11692  * When an ipf is passed here for the first time, if
11693  * we already have in-order fragments on the queue, we convert from the fast-
11694  * path reassembly scheme to the hard-case scheme.  From then on, additional
11695  * fragments are reassembled here.  We keep track of the start and end offsets
11696  * of each piece, and the number of holes in the chain.  When the hole count
11697  * goes to zero, we are done!
11698  *
11699  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11700  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11701  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11702  * after the call to ip_reassemble().
11703  */
11704 int
11705 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11706     size_t msg_len)
11707 {
11708 	uint_t	end;
11709 	mblk_t	*next_mp;
11710 	mblk_t	*mp1;
11711 	uint_t	offset;
11712 	boolean_t incr_dups = B_TRUE;
11713 	boolean_t offset_zero_seen = B_FALSE;
11714 	boolean_t pkt_boundary_checked = B_FALSE;
11715 
11716 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11717 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11718 
11719 	/* Add in byte count */
11720 	ipf->ipf_count += msg_len;
11721 	if (ipf->ipf_end) {
11722 		/*
11723 		 * We were part way through in-order reassembly, but now there
11724 		 * is a hole.  We walk through messages already queued, and
11725 		 * mark them for hard case reassembly.  We know that up till
11726 		 * now they were in order starting from offset zero.
11727 		 */
11728 		offset = 0;
11729 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11730 			IP_REASS_SET_START(mp1, offset);
11731 			if (offset == 0) {
11732 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11733 				offset = -ipf->ipf_nf_hdr_len;
11734 			}
11735 			offset += mp1->b_wptr - mp1->b_rptr;
11736 			IP_REASS_SET_END(mp1, offset);
11737 		}
11738 		/* One hole at the end. */
11739 		ipf->ipf_hole_cnt = 1;
11740 		/* Brand it as a hard case, forever. */
11741 		ipf->ipf_end = 0;
11742 	}
11743 	/* Walk through all the new pieces. */
11744 	do {
11745 		end = start + (mp->b_wptr - mp->b_rptr);
11746 		/*
11747 		 * If start is 0, decrease 'end' only for the first mblk of
11748 		 * the fragment. Otherwise 'end' can get wrong value in the
11749 		 * second pass of the loop if first mblk is exactly the
11750 		 * size of ipf_nf_hdr_len.
11751 		 */
11752 		if (start == 0 && !offset_zero_seen) {
11753 			/* First segment */
11754 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11755 			end -= ipf->ipf_nf_hdr_len;
11756 			offset_zero_seen = B_TRUE;
11757 		}
11758 		next_mp = mp->b_cont;
11759 		/*
11760 		 * We are checking to see if there is any interesing data
11761 		 * to process.  If there isn't and the mblk isn't the
11762 		 * one which carries the unfragmentable header then we
11763 		 * drop it.  It's possible to have just the unfragmentable
11764 		 * header come through without any data.  That needs to be
11765 		 * saved.
11766 		 *
11767 		 * If the assert at the top of this function holds then the
11768 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11769 		 * is infrequently traveled enough that the test is left in
11770 		 * to protect against future code changes which break that
11771 		 * invariant.
11772 		 */
11773 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11774 			/* Empty.  Blast it. */
11775 			IP_REASS_SET_START(mp, 0);
11776 			IP_REASS_SET_END(mp, 0);
11777 			/*
11778 			 * If the ipf points to the mblk we are about to free,
11779 			 * update ipf to point to the next mblk (or NULL
11780 			 * if none).
11781 			 */
11782 			if (ipf->ipf_mp->b_cont == mp)
11783 				ipf->ipf_mp->b_cont = next_mp;
11784 			freeb(mp);
11785 			continue;
11786 		}
11787 		mp->b_cont = NULL;
11788 		IP_REASS_SET_START(mp, start);
11789 		IP_REASS_SET_END(mp, end);
11790 		if (!ipf->ipf_tail_mp) {
11791 			ipf->ipf_tail_mp = mp;
11792 			ipf->ipf_mp->b_cont = mp;
11793 			if (start == 0 || !more) {
11794 				ipf->ipf_hole_cnt = 1;
11795 				/*
11796 				 * if the first fragment comes in more than one
11797 				 * mblk, this loop will be executed for each
11798 				 * mblk. Need to adjust hole count so exiting
11799 				 * this routine will leave hole count at 1.
11800 				 */
11801 				if (next_mp)
11802 					ipf->ipf_hole_cnt++;
11803 			} else
11804 				ipf->ipf_hole_cnt = 2;
11805 			continue;
11806 		} else if (ipf->ipf_last_frag_seen && !more &&
11807 		    !pkt_boundary_checked) {
11808 			/*
11809 			 * We check datagram boundary only if this fragment
11810 			 * claims to be the last fragment and we have seen a
11811 			 * last fragment in the past too. We do this only
11812 			 * once for a given fragment.
11813 			 *
11814 			 * start cannot be 0 here as fragments with start=0
11815 			 * and MF=0 gets handled as a complete packet. These
11816 			 * fragments should not reach here.
11817 			 */
11818 
11819 			if (start + msgdsize(mp) !=
11820 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11821 				/*
11822 				 * We have two fragments both of which claim
11823 				 * to be the last fragment but gives conflicting
11824 				 * information about the whole datagram size.
11825 				 * Something fishy is going on. Drop the
11826 				 * fragment and free up the reassembly list.
11827 				 */
11828 				return (IP_REASS_FAILED);
11829 			}
11830 
11831 			/*
11832 			 * We shouldn't come to this code block again for this
11833 			 * particular fragment.
11834 			 */
11835 			pkt_boundary_checked = B_TRUE;
11836 		}
11837 
11838 		/* New stuff at or beyond tail? */
11839 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11840 		if (start >= offset) {
11841 			if (ipf->ipf_last_frag_seen) {
11842 				/* current fragment is beyond last fragment */
11843 				return (IP_REASS_FAILED);
11844 			}
11845 			/* Link it on end. */
11846 			ipf->ipf_tail_mp->b_cont = mp;
11847 			ipf->ipf_tail_mp = mp;
11848 			if (more) {
11849 				if (start != offset)
11850 					ipf->ipf_hole_cnt++;
11851 			} else if (start == offset && next_mp == NULL)
11852 					ipf->ipf_hole_cnt--;
11853 			continue;
11854 		}
11855 		mp1 = ipf->ipf_mp->b_cont;
11856 		offset = IP_REASS_START(mp1);
11857 		/* New stuff at the front? */
11858 		if (start < offset) {
11859 			if (start == 0) {
11860 				if (end >= offset) {
11861 					/* Nailed the hole at the begining. */
11862 					ipf->ipf_hole_cnt--;
11863 				}
11864 			} else if (end < offset) {
11865 				/*
11866 				 * A hole, stuff, and a hole where there used
11867 				 * to be just a hole.
11868 				 */
11869 				ipf->ipf_hole_cnt++;
11870 			}
11871 			mp->b_cont = mp1;
11872 			/* Check for overlap. */
11873 			while (end > offset) {
11874 				if (end < IP_REASS_END(mp1)) {
11875 					mp->b_wptr -= end - offset;
11876 					IP_REASS_SET_END(mp, offset);
11877 					BUMP_MIB(ill->ill_ip_mib,
11878 					    ipIfStatsReasmPartDups);
11879 					break;
11880 				}
11881 				/* Did we cover another hole? */
11882 				if ((mp1->b_cont &&
11883 				    IP_REASS_END(mp1) !=
11884 				    IP_REASS_START(mp1->b_cont) &&
11885 				    end >= IP_REASS_START(mp1->b_cont)) ||
11886 				    (!ipf->ipf_last_frag_seen && !more)) {
11887 					ipf->ipf_hole_cnt--;
11888 				}
11889 				/* Clip out mp1. */
11890 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11891 					/*
11892 					 * After clipping out mp1, this guy
11893 					 * is now hanging off the end.
11894 					 */
11895 					ipf->ipf_tail_mp = mp;
11896 				}
11897 				IP_REASS_SET_START(mp1, 0);
11898 				IP_REASS_SET_END(mp1, 0);
11899 				/* Subtract byte count */
11900 				ipf->ipf_count -= mp1->b_datap->db_lim -
11901 				    mp1->b_datap->db_base;
11902 				freeb(mp1);
11903 				BUMP_MIB(ill->ill_ip_mib,
11904 				    ipIfStatsReasmPartDups);
11905 				mp1 = mp->b_cont;
11906 				if (!mp1)
11907 					break;
11908 				offset = IP_REASS_START(mp1);
11909 			}
11910 			ipf->ipf_mp->b_cont = mp;
11911 			continue;
11912 		}
11913 		/*
11914 		 * The new piece starts somewhere between the start of the head
11915 		 * and before the end of the tail.
11916 		 */
11917 		for (; mp1; mp1 = mp1->b_cont) {
11918 			offset = IP_REASS_END(mp1);
11919 			if (start < offset) {
11920 				if (end <= offset) {
11921 					/* Nothing new. */
11922 					IP_REASS_SET_START(mp, 0);
11923 					IP_REASS_SET_END(mp, 0);
11924 					/* Subtract byte count */
11925 					ipf->ipf_count -= mp->b_datap->db_lim -
11926 					    mp->b_datap->db_base;
11927 					if (incr_dups) {
11928 						ipf->ipf_num_dups++;
11929 						incr_dups = B_FALSE;
11930 					}
11931 					freeb(mp);
11932 					BUMP_MIB(ill->ill_ip_mib,
11933 					    ipIfStatsReasmDuplicates);
11934 					break;
11935 				}
11936 				/*
11937 				 * Trim redundant stuff off beginning of new
11938 				 * piece.
11939 				 */
11940 				IP_REASS_SET_START(mp, offset);
11941 				mp->b_rptr += offset - start;
11942 				BUMP_MIB(ill->ill_ip_mib,
11943 				    ipIfStatsReasmPartDups);
11944 				start = offset;
11945 				if (!mp1->b_cont) {
11946 					/*
11947 					 * After trimming, this guy is now
11948 					 * hanging off the end.
11949 					 */
11950 					mp1->b_cont = mp;
11951 					ipf->ipf_tail_mp = mp;
11952 					if (!more) {
11953 						ipf->ipf_hole_cnt--;
11954 					}
11955 					break;
11956 				}
11957 			}
11958 			if (start >= IP_REASS_START(mp1->b_cont))
11959 				continue;
11960 			/* Fill a hole */
11961 			if (start > offset)
11962 				ipf->ipf_hole_cnt++;
11963 			mp->b_cont = mp1->b_cont;
11964 			mp1->b_cont = mp;
11965 			mp1 = mp->b_cont;
11966 			offset = IP_REASS_START(mp1);
11967 			if (end >= offset) {
11968 				ipf->ipf_hole_cnt--;
11969 				/* Check for overlap. */
11970 				while (end > offset) {
11971 					if (end < IP_REASS_END(mp1)) {
11972 						mp->b_wptr -= end - offset;
11973 						IP_REASS_SET_END(mp, offset);
11974 						/*
11975 						 * TODO we might bump
11976 						 * this up twice if there is
11977 						 * overlap at both ends.
11978 						 */
11979 						BUMP_MIB(ill->ill_ip_mib,
11980 						    ipIfStatsReasmPartDups);
11981 						break;
11982 					}
11983 					/* Did we cover another hole? */
11984 					if ((mp1->b_cont &&
11985 					    IP_REASS_END(mp1)
11986 					    != IP_REASS_START(mp1->b_cont) &&
11987 					    end >=
11988 					    IP_REASS_START(mp1->b_cont)) ||
11989 					    (!ipf->ipf_last_frag_seen &&
11990 					    !more)) {
11991 						ipf->ipf_hole_cnt--;
11992 					}
11993 					/* Clip out mp1. */
11994 					if ((mp->b_cont = mp1->b_cont) ==
11995 					    NULL) {
11996 						/*
11997 						 * After clipping out mp1,
11998 						 * this guy is now hanging
11999 						 * off the end.
12000 						 */
12001 						ipf->ipf_tail_mp = mp;
12002 					}
12003 					IP_REASS_SET_START(mp1, 0);
12004 					IP_REASS_SET_END(mp1, 0);
12005 					/* Subtract byte count */
12006 					ipf->ipf_count -=
12007 					    mp1->b_datap->db_lim -
12008 					    mp1->b_datap->db_base;
12009 					freeb(mp1);
12010 					BUMP_MIB(ill->ill_ip_mib,
12011 					    ipIfStatsReasmPartDups);
12012 					mp1 = mp->b_cont;
12013 					if (!mp1)
12014 						break;
12015 					offset = IP_REASS_START(mp1);
12016 				}
12017 			}
12018 			break;
12019 		}
12020 	} while (start = end, mp = next_mp);
12021 
12022 	/* Fragment just processed could be the last one. Remember this fact */
12023 	if (!more)
12024 		ipf->ipf_last_frag_seen = B_TRUE;
12025 
12026 	/* Still got holes? */
12027 	if (ipf->ipf_hole_cnt)
12028 		return (IP_REASS_PARTIAL);
12029 	/* Clean up overloaded fields to avoid upstream disasters. */
12030 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12031 		IP_REASS_SET_START(mp1, 0);
12032 		IP_REASS_SET_END(mp1, 0);
12033 	}
12034 	return (IP_REASS_COMPLETE);
12035 }
12036 
12037 /*
12038  * ipsec processing for the fast path, used for input UDP Packets
12039  * Returns true if ready for passup to UDP.
12040  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12041  * was an ESP-in-UDP packet, etc.).
12042  */
12043 static boolean_t
12044 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12045     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12046 {
12047 	uint32_t	ill_index;
12048 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12049 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12050 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12051 	udp_t		*udp = connp->conn_udp;
12052 
12053 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12054 	/* The ill_index of the incoming ILL */
12055 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12056 
12057 	/* pass packet up to the transport */
12058 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12059 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12060 		    NULL, mctl_present);
12061 		if (*first_mpp == NULL) {
12062 			return (B_FALSE);
12063 		}
12064 	}
12065 
12066 	/* Initiate IPPF processing for fastpath UDP */
12067 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12068 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12069 		if (*mpp == NULL) {
12070 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12071 			    "deferred/dropped during IPPF processing\n"));
12072 			return (B_FALSE);
12073 		}
12074 	}
12075 	/*
12076 	 * Remove 0-spi if it's 0, or move everything behind
12077 	 * the UDP header over it and forward to ESP via
12078 	 * ip_proto_input().
12079 	 */
12080 	if (udp->udp_nat_t_endpoint) {
12081 		if (mctl_present) {
12082 			/* mctl_present *shouldn't* happen. */
12083 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12084 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12085 			    &ipss->ipsec_dropper);
12086 			*first_mpp = NULL;
12087 			return (B_FALSE);
12088 		}
12089 
12090 		/* "ill" is "recv_ill" in actuality. */
12091 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12092 			return (B_FALSE);
12093 
12094 		/* Else continue like a normal UDP packet. */
12095 	}
12096 
12097 	/*
12098 	 * We make the checks as below since we are in the fast path
12099 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12100 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12101 	 */
12102 	if (connp->conn_recvif || connp->conn_recvslla ||
12103 	    connp->conn_ip_recvpktinfo) {
12104 		if (connp->conn_recvif) {
12105 			in_flags = IPF_RECVIF;
12106 		}
12107 		/*
12108 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12109 		 * so the flag passed to ip_add_info is based on IP version
12110 		 * of connp.
12111 		 */
12112 		if (connp->conn_ip_recvpktinfo) {
12113 			if (connp->conn_af_isv6) {
12114 				/*
12115 				 * V6 only needs index
12116 				 */
12117 				in_flags |= IPF_RECVIF;
12118 			} else {
12119 				/*
12120 				 * V4 needs index + matching address.
12121 				 */
12122 				in_flags |= IPF_RECVADDR;
12123 			}
12124 		}
12125 		if (connp->conn_recvslla) {
12126 			in_flags |= IPF_RECVSLLA;
12127 		}
12128 		/*
12129 		 * since in_flags are being set ill will be
12130 		 * referenced in ip_add_info, so it better not
12131 		 * be NULL.
12132 		 */
12133 		/*
12134 		 * the actual data will be contained in b_cont
12135 		 * upon successful return of the following call.
12136 		 * If the call fails then the original mblk is
12137 		 * returned.
12138 		 */
12139 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12140 		    ipst);
12141 	}
12142 
12143 	return (B_TRUE);
12144 }
12145 
12146 /*
12147  * Fragmentation reassembly.  Each ILL has a hash table for
12148  * queuing packets undergoing reassembly for all IPIFs
12149  * associated with the ILL.  The hash is based on the packet
12150  * IP ident field.  The ILL frag hash table was allocated
12151  * as a timer block at the time the ILL was created.  Whenever
12152  * there is anything on the reassembly queue, the timer will
12153  * be running.  Returns B_TRUE if successful else B_FALSE;
12154  * frees mp on failure.
12155  */
12156 static boolean_t
12157 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12158     uint32_t *cksum_val, uint16_t *cksum_flags)
12159 {
12160 	uint32_t	frag_offset_flags;
12161 	mblk_t		*mp = *mpp;
12162 	mblk_t		*t_mp;
12163 	ipaddr_t	dst;
12164 	uint8_t		proto = ipha->ipha_protocol;
12165 	uint32_t	sum_val;
12166 	uint16_t	sum_flags;
12167 	ipf_t		*ipf;
12168 	ipf_t		**ipfp;
12169 	ipfb_t		*ipfb;
12170 	uint16_t	ident;
12171 	uint32_t	offset;
12172 	ipaddr_t	src;
12173 	uint_t		hdr_length;
12174 	uint32_t	end;
12175 	mblk_t		*mp1;
12176 	mblk_t		*tail_mp;
12177 	size_t		count;
12178 	size_t		msg_len;
12179 	uint8_t		ecn_info = 0;
12180 	uint32_t	packet_size;
12181 	boolean_t	pruned = B_FALSE;
12182 	ip_stack_t *ipst = ill->ill_ipst;
12183 
12184 	if (cksum_val != NULL)
12185 		*cksum_val = 0;
12186 	if (cksum_flags != NULL)
12187 		*cksum_flags = 0;
12188 
12189 	/*
12190 	 * Drop the fragmented as early as possible, if
12191 	 * we don't have resource(s) to re-assemble.
12192 	 */
12193 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12194 		freemsg(mp);
12195 		return (B_FALSE);
12196 	}
12197 
12198 	/* Check for fragmentation offset; return if there's none */
12199 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12200 	    (IPH_MF | IPH_OFFSET)) == 0)
12201 		return (B_TRUE);
12202 
12203 	/*
12204 	 * We utilize hardware computed checksum info only for UDP since
12205 	 * IP fragmentation is a normal occurrence for the protocol.  In
12206 	 * addition, checksum offload support for IP fragments carrying
12207 	 * UDP payload is commonly implemented across network adapters.
12208 	 */
12209 	ASSERT(recv_ill != NULL);
12210 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12211 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12212 		mblk_t *mp1 = mp->b_cont;
12213 		int32_t len;
12214 
12215 		/* Record checksum information from the packet */
12216 		sum_val = (uint32_t)DB_CKSUM16(mp);
12217 		sum_flags = DB_CKSUMFLAGS(mp);
12218 
12219 		/* IP payload offset from beginning of mblk */
12220 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12221 
12222 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12223 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12224 		    offset >= DB_CKSUMSTART(mp) &&
12225 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12226 			uint32_t adj;
12227 			/*
12228 			 * Partial checksum has been calculated by hardware
12229 			 * and attached to the packet; in addition, any
12230 			 * prepended extraneous data is even byte aligned.
12231 			 * If any such data exists, we adjust the checksum;
12232 			 * this would also handle any postpended data.
12233 			 */
12234 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12235 			    mp, mp1, len, adj);
12236 
12237 			/* One's complement subtract extraneous checksum */
12238 			if (adj >= sum_val)
12239 				sum_val = ~(adj - sum_val) & 0xFFFF;
12240 			else
12241 				sum_val -= adj;
12242 		}
12243 	} else {
12244 		sum_val = 0;
12245 		sum_flags = 0;
12246 	}
12247 
12248 	/* Clear hardware checksumming flag */
12249 	DB_CKSUMFLAGS(mp) = 0;
12250 
12251 	ident = ipha->ipha_ident;
12252 	offset = (frag_offset_flags << 3) & 0xFFFF;
12253 	src = ipha->ipha_src;
12254 	dst = ipha->ipha_dst;
12255 	hdr_length = IPH_HDR_LENGTH(ipha);
12256 	end = ntohs(ipha->ipha_length) - hdr_length;
12257 
12258 	/* If end == 0 then we have a packet with no data, so just free it */
12259 	if (end == 0) {
12260 		freemsg(mp);
12261 		return (B_FALSE);
12262 	}
12263 
12264 	/* Record the ECN field info. */
12265 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12266 	if (offset != 0) {
12267 		/*
12268 		 * If this isn't the first piece, strip the header, and
12269 		 * add the offset to the end value.
12270 		 */
12271 		mp->b_rptr += hdr_length;
12272 		end += offset;
12273 	}
12274 
12275 	msg_len = MBLKSIZE(mp);
12276 	tail_mp = mp;
12277 	while (tail_mp->b_cont != NULL) {
12278 		tail_mp = tail_mp->b_cont;
12279 		msg_len += MBLKSIZE(tail_mp);
12280 	}
12281 
12282 	/* If the reassembly list for this ILL will get too big, prune it */
12283 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12284 	    ipst->ips_ip_reass_queue_bytes) {
12285 		ill_frag_prune(ill,
12286 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12287 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12288 		pruned = B_TRUE;
12289 	}
12290 
12291 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12292 	mutex_enter(&ipfb->ipfb_lock);
12293 
12294 	ipfp = &ipfb->ipfb_ipf;
12295 	/* Try to find an existing fragment queue for this packet. */
12296 	for (;;) {
12297 		ipf = ipfp[0];
12298 		if (ipf != NULL) {
12299 			/*
12300 			 * It has to match on ident and src/dst address.
12301 			 */
12302 			if (ipf->ipf_ident == ident &&
12303 			    ipf->ipf_src == src &&
12304 			    ipf->ipf_dst == dst &&
12305 			    ipf->ipf_protocol == proto) {
12306 				/*
12307 				 * If we have received too many
12308 				 * duplicate fragments for this packet
12309 				 * free it.
12310 				 */
12311 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12312 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12313 					freemsg(mp);
12314 					mutex_exit(&ipfb->ipfb_lock);
12315 					return (B_FALSE);
12316 				}
12317 				/* Found it. */
12318 				break;
12319 			}
12320 			ipfp = &ipf->ipf_hash_next;
12321 			continue;
12322 		}
12323 
12324 		/*
12325 		 * If we pruned the list, do we want to store this new
12326 		 * fragment?. We apply an optimization here based on the
12327 		 * fact that most fragments will be received in order.
12328 		 * So if the offset of this incoming fragment is zero,
12329 		 * it is the first fragment of a new packet. We will
12330 		 * keep it.  Otherwise drop the fragment, as we have
12331 		 * probably pruned the packet already (since the
12332 		 * packet cannot be found).
12333 		 */
12334 		if (pruned && offset != 0) {
12335 			mutex_exit(&ipfb->ipfb_lock);
12336 			freemsg(mp);
12337 			return (B_FALSE);
12338 		}
12339 
12340 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12341 			/*
12342 			 * Too many fragmented packets in this hash
12343 			 * bucket. Free the oldest.
12344 			 */
12345 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12346 		}
12347 
12348 		/* New guy.  Allocate a frag message. */
12349 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12350 		if (mp1 == NULL) {
12351 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12352 			freemsg(mp);
12353 reass_done:
12354 			mutex_exit(&ipfb->ipfb_lock);
12355 			return (B_FALSE);
12356 		}
12357 
12358 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12359 		mp1->b_cont = mp;
12360 
12361 		/* Initialize the fragment header. */
12362 		ipf = (ipf_t *)mp1->b_rptr;
12363 		ipf->ipf_mp = mp1;
12364 		ipf->ipf_ptphn = ipfp;
12365 		ipfp[0] = ipf;
12366 		ipf->ipf_hash_next = NULL;
12367 		ipf->ipf_ident = ident;
12368 		ipf->ipf_protocol = proto;
12369 		ipf->ipf_src = src;
12370 		ipf->ipf_dst = dst;
12371 		ipf->ipf_nf_hdr_len = 0;
12372 		/* Record reassembly start time. */
12373 		ipf->ipf_timestamp = gethrestime_sec();
12374 		/* Record ipf generation and account for frag header */
12375 		ipf->ipf_gen = ill->ill_ipf_gen++;
12376 		ipf->ipf_count = MBLKSIZE(mp1);
12377 		ipf->ipf_last_frag_seen = B_FALSE;
12378 		ipf->ipf_ecn = ecn_info;
12379 		ipf->ipf_num_dups = 0;
12380 		ipfb->ipfb_frag_pkts++;
12381 		ipf->ipf_checksum = 0;
12382 		ipf->ipf_checksum_flags = 0;
12383 
12384 		/* Store checksum value in fragment header */
12385 		if (sum_flags != 0) {
12386 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12387 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12388 			ipf->ipf_checksum = sum_val;
12389 			ipf->ipf_checksum_flags = sum_flags;
12390 		}
12391 
12392 		/*
12393 		 * We handle reassembly two ways.  In the easy case,
12394 		 * where all the fragments show up in order, we do
12395 		 * minimal bookkeeping, and just clip new pieces on
12396 		 * the end.  If we ever see a hole, then we go off
12397 		 * to ip_reassemble which has to mark the pieces and
12398 		 * keep track of the number of holes, etc.  Obviously,
12399 		 * the point of having both mechanisms is so we can
12400 		 * handle the easy case as efficiently as possible.
12401 		 */
12402 		if (offset == 0) {
12403 			/* Easy case, in-order reassembly so far. */
12404 			ipf->ipf_count += msg_len;
12405 			ipf->ipf_tail_mp = tail_mp;
12406 			/*
12407 			 * Keep track of next expected offset in
12408 			 * ipf_end.
12409 			 */
12410 			ipf->ipf_end = end;
12411 			ipf->ipf_nf_hdr_len = hdr_length;
12412 		} else {
12413 			/* Hard case, hole at the beginning. */
12414 			ipf->ipf_tail_mp = NULL;
12415 			/*
12416 			 * ipf_end == 0 means that we have given up
12417 			 * on easy reassembly.
12418 			 */
12419 			ipf->ipf_end = 0;
12420 
12421 			/* Forget checksum offload from now on */
12422 			ipf->ipf_checksum_flags = 0;
12423 
12424 			/*
12425 			 * ipf_hole_cnt is set by ip_reassemble.
12426 			 * ipf_count is updated by ip_reassemble.
12427 			 * No need to check for return value here
12428 			 * as we don't expect reassembly to complete
12429 			 * or fail for the first fragment itself.
12430 			 */
12431 			(void) ip_reassemble(mp, ipf,
12432 			    (frag_offset_flags & IPH_OFFSET) << 3,
12433 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12434 		}
12435 		/* Update per ipfb and ill byte counts */
12436 		ipfb->ipfb_count += ipf->ipf_count;
12437 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12438 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12439 		/* If the frag timer wasn't already going, start it. */
12440 		mutex_enter(&ill->ill_lock);
12441 		ill_frag_timer_start(ill);
12442 		mutex_exit(&ill->ill_lock);
12443 		goto reass_done;
12444 	}
12445 
12446 	/*
12447 	 * If the packet's flag has changed (it could be coming up
12448 	 * from an interface different than the previous, therefore
12449 	 * possibly different checksum capability), then forget about
12450 	 * any stored checksum states.  Otherwise add the value to
12451 	 * the existing one stored in the fragment header.
12452 	 */
12453 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12454 		sum_val += ipf->ipf_checksum;
12455 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12456 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12457 		ipf->ipf_checksum = sum_val;
12458 	} else if (ipf->ipf_checksum_flags != 0) {
12459 		/* Forget checksum offload from now on */
12460 		ipf->ipf_checksum_flags = 0;
12461 	}
12462 
12463 	/*
12464 	 * We have a new piece of a datagram which is already being
12465 	 * reassembled.  Update the ECN info if all IP fragments
12466 	 * are ECN capable.  If there is one which is not, clear
12467 	 * all the info.  If there is at least one which has CE
12468 	 * code point, IP needs to report that up to transport.
12469 	 */
12470 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12471 		if (ecn_info == IPH_ECN_CE)
12472 			ipf->ipf_ecn = IPH_ECN_CE;
12473 	} else {
12474 		ipf->ipf_ecn = IPH_ECN_NECT;
12475 	}
12476 	if (offset && ipf->ipf_end == offset) {
12477 		/* The new fragment fits at the end */
12478 		ipf->ipf_tail_mp->b_cont = mp;
12479 		/* Update the byte count */
12480 		ipf->ipf_count += msg_len;
12481 		/* Update per ipfb and ill byte counts */
12482 		ipfb->ipfb_count += msg_len;
12483 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12484 		atomic_add_32(&ill->ill_frag_count, msg_len);
12485 		if (frag_offset_flags & IPH_MF) {
12486 			/* More to come. */
12487 			ipf->ipf_end = end;
12488 			ipf->ipf_tail_mp = tail_mp;
12489 			goto reass_done;
12490 		}
12491 	} else {
12492 		/* Go do the hard cases. */
12493 		int ret;
12494 
12495 		if (offset == 0)
12496 			ipf->ipf_nf_hdr_len = hdr_length;
12497 
12498 		/* Save current byte count */
12499 		count = ipf->ipf_count;
12500 		ret = ip_reassemble(mp, ipf,
12501 		    (frag_offset_flags & IPH_OFFSET) << 3,
12502 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12503 		/* Count of bytes added and subtracted (freeb()ed) */
12504 		count = ipf->ipf_count - count;
12505 		if (count) {
12506 			/* Update per ipfb and ill byte counts */
12507 			ipfb->ipfb_count += count;
12508 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12509 			atomic_add_32(&ill->ill_frag_count, count);
12510 		}
12511 		if (ret == IP_REASS_PARTIAL) {
12512 			goto reass_done;
12513 		} else if (ret == IP_REASS_FAILED) {
12514 			/* Reassembly failed. Free up all resources */
12515 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12516 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12517 				IP_REASS_SET_START(t_mp, 0);
12518 				IP_REASS_SET_END(t_mp, 0);
12519 			}
12520 			freemsg(mp);
12521 			goto reass_done;
12522 		}
12523 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12524 	}
12525 	/*
12526 	 * We have completed reassembly.  Unhook the frag header from
12527 	 * the reassembly list.
12528 	 *
12529 	 * Before we free the frag header, record the ECN info
12530 	 * to report back to the transport.
12531 	 */
12532 	ecn_info = ipf->ipf_ecn;
12533 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12534 	ipfp = ipf->ipf_ptphn;
12535 
12536 	/* We need to supply these to caller */
12537 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12538 		sum_val = ipf->ipf_checksum;
12539 	else
12540 		sum_val = 0;
12541 
12542 	mp1 = ipf->ipf_mp;
12543 	count = ipf->ipf_count;
12544 	ipf = ipf->ipf_hash_next;
12545 	if (ipf != NULL)
12546 		ipf->ipf_ptphn = ipfp;
12547 	ipfp[0] = ipf;
12548 	atomic_add_32(&ill->ill_frag_count, -count);
12549 	ASSERT(ipfb->ipfb_count >= count);
12550 	ipfb->ipfb_count -= count;
12551 	ipfb->ipfb_frag_pkts--;
12552 	mutex_exit(&ipfb->ipfb_lock);
12553 	/* Ditch the frag header. */
12554 	mp = mp1->b_cont;
12555 
12556 	freeb(mp1);
12557 
12558 	/* Restore original IP length in header. */
12559 	packet_size = (uint32_t)msgdsize(mp);
12560 	if (packet_size > IP_MAXPACKET) {
12561 		freemsg(mp);
12562 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12563 		return (B_FALSE);
12564 	}
12565 
12566 	if (DB_REF(mp) > 1) {
12567 		mblk_t *mp2 = copymsg(mp);
12568 
12569 		freemsg(mp);
12570 		if (mp2 == NULL) {
12571 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12572 			return (B_FALSE);
12573 		}
12574 		mp = mp2;
12575 	}
12576 	ipha = (ipha_t *)mp->b_rptr;
12577 
12578 	ipha->ipha_length = htons((uint16_t)packet_size);
12579 	/* We're now complete, zip the frag state */
12580 	ipha->ipha_fragment_offset_and_flags = 0;
12581 	/* Record the ECN info. */
12582 	ipha->ipha_type_of_service &= 0xFC;
12583 	ipha->ipha_type_of_service |= ecn_info;
12584 	*mpp = mp;
12585 
12586 	/* Reassembly is successful; return checksum information if needed */
12587 	if (cksum_val != NULL)
12588 		*cksum_val = sum_val;
12589 	if (cksum_flags != NULL)
12590 		*cksum_flags = sum_flags;
12591 
12592 	return (B_TRUE);
12593 }
12594 
12595 /*
12596  * Perform ip header check sum update local options.
12597  * return B_TRUE if all is well, else return B_FALSE and release
12598  * the mp. caller is responsible for decrementing ire ref cnt.
12599  */
12600 static boolean_t
12601 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12602     ip_stack_t *ipst)
12603 {
12604 	mblk_t		*first_mp;
12605 	boolean_t	mctl_present;
12606 	uint16_t	sum;
12607 
12608 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12609 	/*
12610 	 * Don't do the checksum if it has gone through AH/ESP
12611 	 * processing.
12612 	 */
12613 	if (!mctl_present) {
12614 		sum = ip_csum_hdr(ipha);
12615 		if (sum != 0) {
12616 			if (ill != NULL) {
12617 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12618 			} else {
12619 				BUMP_MIB(&ipst->ips_ip_mib,
12620 				    ipIfStatsInCksumErrs);
12621 			}
12622 			freemsg(first_mp);
12623 			return (B_FALSE);
12624 		}
12625 	}
12626 
12627 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12628 		if (mctl_present)
12629 			freeb(first_mp);
12630 		return (B_FALSE);
12631 	}
12632 
12633 	return (B_TRUE);
12634 }
12635 
12636 /*
12637  * All udp packet are delivered to the local host via this routine.
12638  */
12639 void
12640 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12641     ill_t *recv_ill)
12642 {
12643 	uint32_t	sum;
12644 	uint32_t	u1;
12645 	boolean_t	mctl_present;
12646 	conn_t		*connp;
12647 	mblk_t		*first_mp;
12648 	uint16_t	*up;
12649 	ill_t		*ill = (ill_t *)q->q_ptr;
12650 	uint16_t	reass_hck_flags = 0;
12651 	ip_stack_t	*ipst;
12652 
12653 	ASSERT(recv_ill != NULL);
12654 	ipst = recv_ill->ill_ipst;
12655 
12656 #define	rptr    ((uchar_t *)ipha)
12657 
12658 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12659 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12660 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12661 	ASSERT(ill != NULL);
12662 
12663 	/*
12664 	 * FAST PATH for udp packets
12665 	 */
12666 
12667 	/* u1 is # words of IP options */
12668 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12669 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12670 
12671 	/* IP options present */
12672 	if (u1 != 0)
12673 		goto ipoptions;
12674 
12675 	/* Check the IP header checksum.  */
12676 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12677 		/* Clear the IP header h/w cksum flag */
12678 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12679 	} else if (!mctl_present) {
12680 		/*
12681 		 * Don't verify header checksum if this packet is coming
12682 		 * back from AH/ESP as we already did it.
12683 		 */
12684 #define	uph	((uint16_t *)ipha)
12685 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12686 		    uph[6] + uph[7] + uph[8] + uph[9];
12687 #undef	uph
12688 		/* finish doing IP checksum */
12689 		sum = (sum & 0xFFFF) + (sum >> 16);
12690 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12691 		if (sum != 0 && sum != 0xFFFF) {
12692 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12693 			freemsg(first_mp);
12694 			return;
12695 		}
12696 	}
12697 
12698 	/*
12699 	 * Count for SNMP of inbound packets for ire.
12700 	 * if mctl is present this might be a secure packet and
12701 	 * has already been counted for in ip_proto_input().
12702 	 */
12703 	if (!mctl_present) {
12704 		UPDATE_IB_PKT_COUNT(ire);
12705 		ire->ire_last_used_time = lbolt;
12706 	}
12707 
12708 	/* packet part of fragmented IP packet? */
12709 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12710 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12711 		goto fragmented;
12712 	}
12713 
12714 	/* u1 = IP header length (20 bytes) */
12715 	u1 = IP_SIMPLE_HDR_LENGTH;
12716 
12717 	/* packet does not contain complete IP & UDP headers */
12718 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12719 		goto udppullup;
12720 
12721 	/* up points to UDP header */
12722 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12723 #define	iphs    ((uint16_t *)ipha)
12724 
12725 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12726 	if (up[3] != 0) {
12727 		mblk_t *mp1 = mp->b_cont;
12728 		boolean_t cksum_err;
12729 		uint16_t hck_flags = 0;
12730 
12731 		/* Pseudo-header checksum */
12732 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12733 		    iphs[9] + up[2];
12734 
12735 		/*
12736 		 * Revert to software checksum calculation if the interface
12737 		 * isn't capable of checksum offload or if IPsec is present.
12738 		 */
12739 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12740 			hck_flags = DB_CKSUMFLAGS(mp);
12741 
12742 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12743 			IP_STAT(ipst, ip_in_sw_cksum);
12744 
12745 		IP_CKSUM_RECV(hck_flags, u1,
12746 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12747 		    (int32_t)((uchar_t *)up - rptr),
12748 		    mp, mp1, cksum_err);
12749 
12750 		if (cksum_err) {
12751 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12752 			if (hck_flags & HCK_FULLCKSUM)
12753 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12754 			else if (hck_flags & HCK_PARTIALCKSUM)
12755 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12756 			else
12757 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12758 
12759 			freemsg(first_mp);
12760 			return;
12761 		}
12762 	}
12763 
12764 	/* Non-fragmented broadcast or multicast packet? */
12765 	if (ire->ire_type == IRE_BROADCAST)
12766 		goto udpslowpath;
12767 
12768 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12769 	    ire->ire_zoneid, ipst)) != NULL) {
12770 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12771 		IP_STAT(ipst, ip_udp_fast_path);
12772 
12773 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12774 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12775 			freemsg(mp);
12776 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12777 		} else {
12778 			if (!mctl_present) {
12779 				BUMP_MIB(ill->ill_ip_mib,
12780 				    ipIfStatsHCInDelivers);
12781 			}
12782 			/*
12783 			 * mp and first_mp can change.
12784 			 */
12785 			if (ip_udp_check(q, connp, recv_ill,
12786 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12787 				/* Send it upstream */
12788 				(connp->conn_recv)(connp, mp, NULL);
12789 			}
12790 		}
12791 		/*
12792 		 * freeb() cannot deal with null mblk being passed
12793 		 * in and first_mp can be set to null in the call
12794 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12795 		 */
12796 		if (mctl_present && first_mp != NULL) {
12797 			freeb(first_mp);
12798 		}
12799 		CONN_DEC_REF(connp);
12800 		return;
12801 	}
12802 
12803 	/*
12804 	 * if we got here we know the packet is not fragmented and
12805 	 * has no options. The classifier could not find a conn_t and
12806 	 * most likely its an icmp packet so send it through slow path.
12807 	 */
12808 
12809 	goto udpslowpath;
12810 
12811 ipoptions:
12812 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12813 		goto slow_done;
12814 	}
12815 
12816 	UPDATE_IB_PKT_COUNT(ire);
12817 	ire->ire_last_used_time = lbolt;
12818 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12819 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12820 fragmented:
12821 		/*
12822 		 * "sum" and "reass_hck_flags" are non-zero if the
12823 		 * reassembled packet has a valid hardware computed
12824 		 * checksum information associated with it.
12825 		 */
12826 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12827 		    &reass_hck_flags)) {
12828 			goto slow_done;
12829 		}
12830 
12831 		/*
12832 		 * Make sure that first_mp points back to mp as
12833 		 * the mp we came in with could have changed in
12834 		 * ip_rput_fragment().
12835 		 */
12836 		ASSERT(!mctl_present);
12837 		ipha = (ipha_t *)mp->b_rptr;
12838 		first_mp = mp;
12839 	}
12840 
12841 	/* Now we have a complete datagram, destined for this machine. */
12842 	u1 = IPH_HDR_LENGTH(ipha);
12843 	/* Pull up the UDP header, if necessary. */
12844 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12845 udppullup:
12846 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12847 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12848 			freemsg(first_mp);
12849 			goto slow_done;
12850 		}
12851 		ipha = (ipha_t *)mp->b_rptr;
12852 	}
12853 
12854 	/*
12855 	 * Validate the checksum for the reassembled packet; for the
12856 	 * pullup case we calculate the payload checksum in software.
12857 	 */
12858 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12859 	if (up[3] != 0) {
12860 		boolean_t cksum_err;
12861 
12862 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12863 			IP_STAT(ipst, ip_in_sw_cksum);
12864 
12865 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12866 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12867 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12868 		    iphs[9] + up[2], sum, cksum_err);
12869 
12870 		if (cksum_err) {
12871 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12872 
12873 			if (reass_hck_flags & HCK_FULLCKSUM)
12874 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12875 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12876 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12877 			else
12878 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12879 
12880 			freemsg(first_mp);
12881 			goto slow_done;
12882 		}
12883 	}
12884 udpslowpath:
12885 
12886 	/* Clear hardware checksum flag to be safe */
12887 	DB_CKSUMFLAGS(mp) = 0;
12888 
12889 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12890 	    (ire->ire_type == IRE_BROADCAST),
12891 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12892 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12893 
12894 slow_done:
12895 	IP_STAT(ipst, ip_udp_slow_path);
12896 	return;
12897 
12898 #undef  iphs
12899 #undef  rptr
12900 }
12901 
12902 /* ARGSUSED */
12903 static mblk_t *
12904 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12905     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12906     ill_rx_ring_t *ill_ring)
12907 {
12908 	conn_t		*connp;
12909 	uint32_t	sum;
12910 	uint32_t	u1;
12911 	uint16_t	*up;
12912 	int		offset;
12913 	ssize_t		len;
12914 	mblk_t		*mp1;
12915 	boolean_t	syn_present = B_FALSE;
12916 	tcph_t		*tcph;
12917 	uint_t		tcph_flags;
12918 	uint_t		ip_hdr_len;
12919 	ill_t		*ill = (ill_t *)q->q_ptr;
12920 	zoneid_t	zoneid = ire->ire_zoneid;
12921 	boolean_t	cksum_err;
12922 	uint16_t	hck_flags = 0;
12923 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12924 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12925 
12926 #define	rptr	((uchar_t *)ipha)
12927 
12928 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12929 	ASSERT(ill != NULL);
12930 
12931 	/*
12932 	 * FAST PATH for tcp packets
12933 	 */
12934 
12935 	/* u1 is # words of IP options */
12936 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12937 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12938 
12939 	/* IP options present */
12940 	if (u1) {
12941 		goto ipoptions;
12942 	} else if (!mctl_present) {
12943 		/* Check the IP header checksum.  */
12944 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12945 			/* Clear the IP header h/w cksum flag */
12946 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12947 		} else if (!mctl_present) {
12948 			/*
12949 			 * Don't verify header checksum if this packet
12950 			 * is coming back from AH/ESP as we already did it.
12951 			 */
12952 #define	uph	((uint16_t *)ipha)
12953 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12954 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12955 #undef	uph
12956 			/* finish doing IP checksum */
12957 			sum = (sum & 0xFFFF) + (sum >> 16);
12958 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12959 			if (sum != 0 && sum != 0xFFFF) {
12960 				BUMP_MIB(ill->ill_ip_mib,
12961 				    ipIfStatsInCksumErrs);
12962 				goto error;
12963 			}
12964 		}
12965 	}
12966 
12967 	if (!mctl_present) {
12968 		UPDATE_IB_PKT_COUNT(ire);
12969 		ire->ire_last_used_time = lbolt;
12970 	}
12971 
12972 	/* packet part of fragmented IP packet? */
12973 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12974 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12975 		goto fragmented;
12976 	}
12977 
12978 	/* u1 = IP header length (20 bytes) */
12979 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12980 
12981 	/* does packet contain IP+TCP headers? */
12982 	len = mp->b_wptr - rptr;
12983 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12984 		IP_STAT(ipst, ip_tcppullup);
12985 		goto tcppullup;
12986 	}
12987 
12988 	/* TCP options present? */
12989 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12990 
12991 	/*
12992 	 * If options need to be pulled up, then goto tcpoptions.
12993 	 * otherwise we are still in the fast path
12994 	 */
12995 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12996 		IP_STAT(ipst, ip_tcpoptions);
12997 		goto tcpoptions;
12998 	}
12999 
13000 	/* multiple mblks of tcp data? */
13001 	if ((mp1 = mp->b_cont) != NULL) {
13002 		IP_STAT(ipst, ip_multipkttcp);
13003 		len += msgdsize(mp1);
13004 	}
13005 
13006 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13007 
13008 	/* part of pseudo checksum */
13009 
13010 	/* TCP datagram length */
13011 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13012 
13013 #define	iphs    ((uint16_t *)ipha)
13014 
13015 #ifdef	_BIG_ENDIAN
13016 	u1 += IPPROTO_TCP;
13017 #else
13018 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13019 #endif
13020 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13021 
13022 	/*
13023 	 * Revert to software checksum calculation if the interface
13024 	 * isn't capable of checksum offload or if IPsec is present.
13025 	 */
13026 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13027 		hck_flags = DB_CKSUMFLAGS(mp);
13028 
13029 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13030 		IP_STAT(ipst, ip_in_sw_cksum);
13031 
13032 	IP_CKSUM_RECV(hck_flags, u1,
13033 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13034 	    (int32_t)((uchar_t *)up - rptr),
13035 	    mp, mp1, cksum_err);
13036 
13037 	if (cksum_err) {
13038 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13039 
13040 		if (hck_flags & HCK_FULLCKSUM)
13041 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13042 		else if (hck_flags & HCK_PARTIALCKSUM)
13043 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13044 		else
13045 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13046 
13047 		goto error;
13048 	}
13049 
13050 try_again:
13051 
13052 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13053 	    zoneid, ipst)) == NULL) {
13054 		/* Send the TH_RST */
13055 		goto no_conn;
13056 	}
13057 
13058 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13059 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13060 
13061 	/*
13062 	 * TCP FAST PATH for AF_INET socket.
13063 	 *
13064 	 * TCP fast path to avoid extra work. An AF_INET socket type
13065 	 * does not have facility to receive extra information via
13066 	 * ip_process or ip_add_info. Also, when the connection was
13067 	 * established, we made a check if this connection is impacted
13068 	 * by any global IPsec policy or per connection policy (a
13069 	 * policy that comes in effect later will not apply to this
13070 	 * connection). Since all this can be determined at the
13071 	 * connection establishment time, a quick check of flags
13072 	 * can avoid extra work.
13073 	 */
13074 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13075 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13076 		ASSERT(first_mp == mp);
13077 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13078 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13079 			SET_SQUEUE(mp, tcp_rput_data, connp);
13080 			return (mp);
13081 		}
13082 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13083 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13084 		SET_SQUEUE(mp, tcp_input, connp);
13085 		return (mp);
13086 	}
13087 
13088 	if (tcph_flags == TH_SYN) {
13089 		if (IPCL_IS_TCP(connp)) {
13090 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13091 			DB_CKSUMSTART(mp) =
13092 			    (intptr_t)ip_squeue_get(ill_ring);
13093 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13094 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13095 				BUMP_MIB(ill->ill_ip_mib,
13096 				    ipIfStatsHCInDelivers);
13097 				SET_SQUEUE(mp, connp->conn_recv, connp);
13098 				return (mp);
13099 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13100 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13101 				BUMP_MIB(ill->ill_ip_mib,
13102 				    ipIfStatsHCInDelivers);
13103 				ip_squeue_enter_unbound++;
13104 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13105 				    connp);
13106 				return (mp);
13107 			}
13108 			syn_present = B_TRUE;
13109 		}
13110 	}
13111 
13112 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13113 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13114 
13115 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13116 		/* No need to send this packet to TCP */
13117 		if ((flags & TH_RST) || (flags & TH_URG)) {
13118 			CONN_DEC_REF(connp);
13119 			freemsg(first_mp);
13120 			return (NULL);
13121 		}
13122 		if (flags & TH_ACK) {
13123 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13124 			    ipst->ips_netstack->netstack_tcp, connp);
13125 			CONN_DEC_REF(connp);
13126 			return (NULL);
13127 		}
13128 
13129 		CONN_DEC_REF(connp);
13130 		freemsg(first_mp);
13131 		return (NULL);
13132 	}
13133 
13134 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13135 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13136 		    ipha, NULL, mctl_present);
13137 		if (first_mp == NULL) {
13138 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13139 			CONN_DEC_REF(connp);
13140 			return (NULL);
13141 		}
13142 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13143 			ASSERT(syn_present);
13144 			if (mctl_present) {
13145 				ASSERT(first_mp != mp);
13146 				first_mp->b_datap->db_struioflag |=
13147 				    STRUIO_POLICY;
13148 			} else {
13149 				ASSERT(first_mp == mp);
13150 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13151 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13152 			}
13153 		} else {
13154 			/*
13155 			 * Discard first_mp early since we're dealing with a
13156 			 * fully-connected conn_t and tcp doesn't do policy in
13157 			 * this case.
13158 			 */
13159 			if (mctl_present) {
13160 				freeb(first_mp);
13161 				mctl_present = B_FALSE;
13162 			}
13163 			first_mp = mp;
13164 		}
13165 	}
13166 
13167 	/* Initiate IPPF processing for fastpath */
13168 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13169 		uint32_t	ill_index;
13170 
13171 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13172 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13173 		if (mp == NULL) {
13174 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13175 			    "deferred/dropped during IPPF processing\n"));
13176 			CONN_DEC_REF(connp);
13177 			if (mctl_present)
13178 				freeb(first_mp);
13179 			return (NULL);
13180 		} else if (mctl_present) {
13181 			/*
13182 			 * ip_process might return a new mp.
13183 			 */
13184 			ASSERT(first_mp != mp);
13185 			first_mp->b_cont = mp;
13186 		} else {
13187 			first_mp = mp;
13188 		}
13189 
13190 	}
13191 
13192 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13193 		/*
13194 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13195 		 * make sure IPF_RECVIF is passed to ip_add_info.
13196 		 */
13197 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13198 		    IPCL_ZONEID(connp), ipst);
13199 		if (mp == NULL) {
13200 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13201 			CONN_DEC_REF(connp);
13202 			if (mctl_present)
13203 				freeb(first_mp);
13204 			return (NULL);
13205 		} else if (mctl_present) {
13206 			/*
13207 			 * ip_add_info might return a new mp.
13208 			 */
13209 			ASSERT(first_mp != mp);
13210 			first_mp->b_cont = mp;
13211 		} else {
13212 			first_mp = mp;
13213 		}
13214 	}
13215 
13216 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13217 	if (IPCL_IS_TCP(connp)) {
13218 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13219 		return (first_mp);
13220 	} else {
13221 		/* SOCK_RAW, IPPROTO_TCP case */
13222 		(connp->conn_recv)(connp, first_mp, NULL);
13223 		CONN_DEC_REF(connp);
13224 		return (NULL);
13225 	}
13226 
13227 no_conn:
13228 	/* Initiate IPPf processing, if needed. */
13229 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13230 		uint32_t ill_index;
13231 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13232 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13233 		if (first_mp == NULL) {
13234 			return (NULL);
13235 		}
13236 	}
13237 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13238 
13239 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13240 	    ipst->ips_netstack->netstack_tcp, NULL);
13241 	return (NULL);
13242 ipoptions:
13243 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13244 		goto slow_done;
13245 	}
13246 
13247 	UPDATE_IB_PKT_COUNT(ire);
13248 	ire->ire_last_used_time = lbolt;
13249 
13250 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13251 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13252 fragmented:
13253 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13254 			if (mctl_present)
13255 				freeb(first_mp);
13256 			goto slow_done;
13257 		}
13258 		/*
13259 		 * Make sure that first_mp points back to mp as
13260 		 * the mp we came in with could have changed in
13261 		 * ip_rput_fragment().
13262 		 */
13263 		ASSERT(!mctl_present);
13264 		ipha = (ipha_t *)mp->b_rptr;
13265 		first_mp = mp;
13266 	}
13267 
13268 	/* Now we have a complete datagram, destined for this machine. */
13269 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13270 
13271 	len = mp->b_wptr - mp->b_rptr;
13272 	/* Pull up a minimal TCP header, if necessary. */
13273 	if (len < (u1 + 20)) {
13274 tcppullup:
13275 		if (!pullupmsg(mp, u1 + 20)) {
13276 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13277 			goto error;
13278 		}
13279 		ipha = (ipha_t *)mp->b_rptr;
13280 		len = mp->b_wptr - mp->b_rptr;
13281 	}
13282 
13283 	/*
13284 	 * Extract the offset field from the TCP header.  As usual, we
13285 	 * try to help the compiler more than the reader.
13286 	 */
13287 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13288 	if (offset != 5) {
13289 tcpoptions:
13290 		if (offset < 5) {
13291 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13292 			goto error;
13293 		}
13294 		/*
13295 		 * There must be TCP options.
13296 		 * Make sure we can grab them.
13297 		 */
13298 		offset <<= 2;
13299 		offset += u1;
13300 		if (len < offset) {
13301 			if (!pullupmsg(mp, offset)) {
13302 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13303 				goto error;
13304 			}
13305 			ipha = (ipha_t *)mp->b_rptr;
13306 			len = mp->b_wptr - rptr;
13307 		}
13308 	}
13309 
13310 	/* Get the total packet length in len, including headers. */
13311 	if (mp->b_cont)
13312 		len = msgdsize(mp);
13313 
13314 	/*
13315 	 * Check the TCP checksum by pulling together the pseudo-
13316 	 * header checksum, and passing it to ip_csum to be added in
13317 	 * with the TCP datagram.
13318 	 *
13319 	 * Since we are not using the hwcksum if available we must
13320 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13321 	 * If either of these fails along the way the mblk is freed.
13322 	 * If this logic ever changes and mblk is reused to say send
13323 	 * ICMP's back, then this flag may need to be cleared in
13324 	 * other places as well.
13325 	 */
13326 	DB_CKSUMFLAGS(mp) = 0;
13327 
13328 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13329 
13330 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13331 #ifdef	_BIG_ENDIAN
13332 	u1 += IPPROTO_TCP;
13333 #else
13334 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13335 #endif
13336 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13337 	/*
13338 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13339 	 */
13340 	IP_STAT(ipst, ip_in_sw_cksum);
13341 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13342 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13343 		goto error;
13344 	}
13345 
13346 	IP_STAT(ipst, ip_tcp_slow_path);
13347 	goto try_again;
13348 #undef  iphs
13349 #undef  rptr
13350 
13351 error:
13352 	freemsg(first_mp);
13353 slow_done:
13354 	return (NULL);
13355 }
13356 
13357 /* ARGSUSED */
13358 static void
13359 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13360     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13361 {
13362 	conn_t		*connp;
13363 	uint32_t	sum;
13364 	uint32_t	u1;
13365 	ssize_t		len;
13366 	sctp_hdr_t	*sctph;
13367 	zoneid_t	zoneid = ire->ire_zoneid;
13368 	uint32_t	pktsum;
13369 	uint32_t	calcsum;
13370 	uint32_t	ports;
13371 	in6_addr_t	map_src, map_dst;
13372 	ill_t		*ill = (ill_t *)q->q_ptr;
13373 	ip_stack_t	*ipst;
13374 	sctp_stack_t	*sctps;
13375 	boolean_t	sctp_csum_err = B_FALSE;
13376 
13377 	ASSERT(recv_ill != NULL);
13378 	ipst = recv_ill->ill_ipst;
13379 	sctps = ipst->ips_netstack->netstack_sctp;
13380 
13381 #define	rptr	((uchar_t *)ipha)
13382 
13383 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13384 	ASSERT(ill != NULL);
13385 
13386 	/* u1 is # words of IP options */
13387 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13388 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13389 
13390 	/* IP options present */
13391 	if (u1 > 0) {
13392 		goto ipoptions;
13393 	} else {
13394 		/* Check the IP header checksum.  */
13395 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13396 		    !mctl_present) {
13397 #define	uph	((uint16_t *)ipha)
13398 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13399 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13400 #undef	uph
13401 			/* finish doing IP checksum */
13402 			sum = (sum & 0xFFFF) + (sum >> 16);
13403 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13404 			/*
13405 			 * Don't verify header checksum if this packet
13406 			 * is coming back from AH/ESP as we already did it.
13407 			 */
13408 			if (sum != 0 && sum != 0xFFFF) {
13409 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13410 				goto error;
13411 			}
13412 		}
13413 		/*
13414 		 * Since there is no SCTP h/w cksum support yet, just
13415 		 * clear the flag.
13416 		 */
13417 		DB_CKSUMFLAGS(mp) = 0;
13418 	}
13419 
13420 	/*
13421 	 * Don't verify header checksum if this packet is coming
13422 	 * back from AH/ESP as we already did it.
13423 	 */
13424 	if (!mctl_present) {
13425 		UPDATE_IB_PKT_COUNT(ire);
13426 		ire->ire_last_used_time = lbolt;
13427 	}
13428 
13429 	/* packet part of fragmented IP packet? */
13430 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13431 	if (u1 & (IPH_MF | IPH_OFFSET))
13432 		goto fragmented;
13433 
13434 	/* u1 = IP header length (20 bytes) */
13435 	u1 = IP_SIMPLE_HDR_LENGTH;
13436 
13437 find_sctp_client:
13438 	/* Pullup if we don't have the sctp common header. */
13439 	len = MBLKL(mp);
13440 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13441 		if (mp->b_cont == NULL ||
13442 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13443 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13444 			goto error;
13445 		}
13446 		ipha = (ipha_t *)mp->b_rptr;
13447 		len = MBLKL(mp);
13448 	}
13449 
13450 	sctph = (sctp_hdr_t *)(rptr + u1);
13451 #ifdef	DEBUG
13452 	if (!skip_sctp_cksum) {
13453 #endif
13454 		pktsum = sctph->sh_chksum;
13455 		sctph->sh_chksum = 0;
13456 		calcsum = sctp_cksum(mp, u1);
13457 		sctph->sh_chksum = pktsum;
13458 		if (calcsum != pktsum)
13459 			sctp_csum_err = B_TRUE;
13460 #ifdef	DEBUG	/* skip_sctp_cksum */
13461 	}
13462 #endif
13463 	/* get the ports */
13464 	ports = *(uint32_t *)&sctph->sh_sport;
13465 
13466 	IRE_REFRELE(ire);
13467 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13468 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13469 	if (sctp_csum_err) {
13470 		/*
13471 		 * No potential sctp checksum errors go to the Sun
13472 		 * sctp stack however they might be Adler-32 summed
13473 		 * packets a userland stack bound to a raw IP socket
13474 		 * could reasonably use. Note though that Adler-32 is
13475 		 * a long deprecated algorithm and customer sctp
13476 		 * networks should eventually migrate to CRC-32 at
13477 		 * which time this facility should be removed.
13478 		 */
13479 		flags |= IP_FF_SCTP_CSUM_ERR;
13480 		goto no_conn;
13481 	}
13482 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13483 	    sctps)) == NULL) {
13484 		/* Check for raw socket or OOTB handling */
13485 		goto no_conn;
13486 	}
13487 
13488 	/* Found a client; up it goes */
13489 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13490 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13491 	return;
13492 
13493 no_conn:
13494 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13495 	    ports, mctl_present, flags, B_TRUE, zoneid);
13496 	return;
13497 
13498 ipoptions:
13499 	DB_CKSUMFLAGS(mp) = 0;
13500 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13501 		goto slow_done;
13502 
13503 	UPDATE_IB_PKT_COUNT(ire);
13504 	ire->ire_last_used_time = lbolt;
13505 
13506 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13507 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13508 fragmented:
13509 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13510 			goto slow_done;
13511 		/*
13512 		 * Make sure that first_mp points back to mp as
13513 		 * the mp we came in with could have changed in
13514 		 * ip_rput_fragment().
13515 		 */
13516 		ASSERT(!mctl_present);
13517 		ipha = (ipha_t *)mp->b_rptr;
13518 		first_mp = mp;
13519 	}
13520 
13521 	/* Now we have a complete datagram, destined for this machine. */
13522 	u1 = IPH_HDR_LENGTH(ipha);
13523 	goto find_sctp_client;
13524 #undef  iphs
13525 #undef  rptr
13526 
13527 error:
13528 	freemsg(first_mp);
13529 slow_done:
13530 	IRE_REFRELE(ire);
13531 }
13532 
13533 #define	VER_BITS	0xF0
13534 #define	VERSION_6	0x60
13535 
13536 static boolean_t
13537 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13538     ipaddr_t *dstp, ip_stack_t *ipst)
13539 {
13540 	uint_t	opt_len;
13541 	ipha_t *ipha;
13542 	ssize_t len;
13543 	uint_t	pkt_len;
13544 
13545 	ASSERT(ill != NULL);
13546 	IP_STAT(ipst, ip_ipoptions);
13547 	ipha = *iphapp;
13548 
13549 #define	rptr    ((uchar_t *)ipha)
13550 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13551 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13552 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13553 		freemsg(mp);
13554 		return (B_FALSE);
13555 	}
13556 
13557 	/* multiple mblk or too short */
13558 	pkt_len = ntohs(ipha->ipha_length);
13559 
13560 	/* Get the number of words of IP options in the IP header. */
13561 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13562 	if (opt_len) {
13563 		/* IP Options present!  Validate and process. */
13564 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13565 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13566 			goto done;
13567 		}
13568 		/*
13569 		 * Recompute complete header length and make sure we
13570 		 * have access to all of it.
13571 		 */
13572 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13573 		if (len > (mp->b_wptr - rptr)) {
13574 			if (len > pkt_len) {
13575 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13576 				goto done;
13577 			}
13578 			if (!pullupmsg(mp, len)) {
13579 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13580 				goto done;
13581 			}
13582 			ipha = (ipha_t *)mp->b_rptr;
13583 		}
13584 		/*
13585 		 * Go off to ip_rput_options which returns the next hop
13586 		 * destination address, which may have been affected
13587 		 * by source routing.
13588 		 */
13589 		IP_STAT(ipst, ip_opt);
13590 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13591 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13592 			return (B_FALSE);
13593 		}
13594 	}
13595 	*iphapp = ipha;
13596 	return (B_TRUE);
13597 done:
13598 	/* clear b_prev - used by ip_mroute_decap */
13599 	mp->b_prev = NULL;
13600 	freemsg(mp);
13601 	return (B_FALSE);
13602 #undef  rptr
13603 }
13604 
13605 /*
13606  * Deal with the fact that there is no ire for the destination.
13607  */
13608 static ire_t *
13609 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13610 {
13611 	ipha_t	*ipha;
13612 	ill_t	*ill;
13613 	ire_t	*ire;
13614 	ip_stack_t *ipst;
13615 	enum	ire_forward_action ret_action;
13616 
13617 	ipha = (ipha_t *)mp->b_rptr;
13618 	ill = (ill_t *)q->q_ptr;
13619 
13620 	ASSERT(ill != NULL);
13621 	ipst = ill->ill_ipst;
13622 
13623 	/*
13624 	 * No IRE for this destination, so it can't be for us.
13625 	 * Unless we are forwarding, drop the packet.
13626 	 * We have to let source routed packets through
13627 	 * since we don't yet know if they are 'ping -l'
13628 	 * packets i.e. if they will go out over the
13629 	 * same interface as they came in on.
13630 	 */
13631 	if (ll_multicast) {
13632 		freemsg(mp);
13633 		return (NULL);
13634 	}
13635 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13636 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13637 		freemsg(mp);
13638 		return (NULL);
13639 	}
13640 
13641 	/*
13642 	 * Mark this packet as having originated externally.
13643 	 *
13644 	 * For non-forwarding code path, ire_send later double
13645 	 * checks this interface to see if it is still exists
13646 	 * post-ARP resolution.
13647 	 *
13648 	 * Also, IPQOS uses this to differentiate between
13649 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13650 	 * QOS packet processing in ip_wput_attach_llhdr().
13651 	 * The QoS module can mark the b_band for a fastpath message
13652 	 * or the dl_priority field in a unitdata_req header for
13653 	 * CoS marking. This info can only be found in
13654 	 * ip_wput_attach_llhdr().
13655 	 */
13656 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13657 	/*
13658 	 * Clear the indication that this may have a hardware checksum
13659 	 * as we are not using it
13660 	 */
13661 	DB_CKSUMFLAGS(mp) = 0;
13662 
13663 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13664 	    msg_getlabel(mp), ipst);
13665 
13666 	if (ire == NULL && ret_action == Forward_check_multirt) {
13667 		/* Let ip_newroute handle CGTP  */
13668 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13669 		return (NULL);
13670 	}
13671 
13672 	if (ire != NULL)
13673 		return (ire);
13674 
13675 	mp->b_prev = mp->b_next = 0;
13676 
13677 	if (ret_action == Forward_blackhole) {
13678 		freemsg(mp);
13679 		return (NULL);
13680 	}
13681 	/* send icmp unreachable */
13682 	q = WR(q);
13683 	/* Sent by forwarding path, and router is global zone */
13684 	if (ip_source_routed(ipha, ipst)) {
13685 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13686 		    GLOBAL_ZONEID, ipst);
13687 	} else {
13688 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13689 		    ipst);
13690 	}
13691 
13692 	return (NULL);
13693 
13694 }
13695 
13696 /*
13697  * check ip header length and align it.
13698  */
13699 static boolean_t
13700 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13701 {
13702 	ssize_t len;
13703 	ill_t *ill;
13704 	ipha_t	*ipha;
13705 
13706 	len = MBLKL(mp);
13707 
13708 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13709 		ill = (ill_t *)q->q_ptr;
13710 
13711 		if (!OK_32PTR(mp->b_rptr))
13712 			IP_STAT(ipst, ip_notaligned1);
13713 		else
13714 			IP_STAT(ipst, ip_notaligned2);
13715 		/* Guard against bogus device drivers */
13716 		if (len < 0) {
13717 			/* clear b_prev - used by ip_mroute_decap */
13718 			mp->b_prev = NULL;
13719 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13720 			freemsg(mp);
13721 			return (B_FALSE);
13722 		}
13723 
13724 		if (ip_rput_pullups++ == 0) {
13725 			ipha = (ipha_t *)mp->b_rptr;
13726 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13727 			    "ip_check_and_align_header: %s forced us to "
13728 			    " pullup pkt, hdr len %ld, hdr addr %p",
13729 			    ill->ill_name, len, (void *)ipha);
13730 		}
13731 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13732 			/* clear b_prev - used by ip_mroute_decap */
13733 			mp->b_prev = NULL;
13734 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13735 			freemsg(mp);
13736 			return (B_FALSE);
13737 		}
13738 	}
13739 	return (B_TRUE);
13740 }
13741 
13742 /*
13743  * Handle the situation where a packet came in on `ill' but matched an IRE
13744  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13745  * for interface statistics.
13746  */
13747 ire_t *
13748 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13749 {
13750 	ire_t		*new_ire;
13751 	ill_t		*ire_ill;
13752 	uint_t		ifindex;
13753 	ip_stack_t	*ipst = ill->ill_ipst;
13754 	boolean_t	strict_check = B_FALSE;
13755 
13756 	/*
13757 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13758 	 * issue (e.g. packet received on an underlying interface matched an
13759 	 * IRE_LOCAL on its associated group interface).
13760 	 */
13761 	if (ire->ire_rfq != NULL &&
13762 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13763 		return (ire);
13764 	}
13765 
13766 	/*
13767 	 * Do another ire lookup here, using the ingress ill, to see if the
13768 	 * interface is in a usesrc group.
13769 	 * As long as the ills belong to the same group, we don't consider
13770 	 * them to be arriving on the wrong interface. Thus, if the switch
13771 	 * is doing inbound load spreading, we won't drop packets when the
13772 	 * ip*_strict_dst_multihoming switch is on.
13773 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13774 	 * where the local address may not be unique. In this case we were
13775 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13776 	 * actually returned. The new lookup, which is more specific, should
13777 	 * only find the IRE_LOCAL associated with the ingress ill if one
13778 	 * exists.
13779 	 */
13780 
13781 	if (ire->ire_ipversion == IPV4_VERSION) {
13782 		if (ipst->ips_ip_strict_dst_multihoming)
13783 			strict_check = B_TRUE;
13784 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13785 		    ill->ill_ipif, ALL_ZONES, NULL,
13786 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13787 	} else {
13788 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13789 		if (ipst->ips_ipv6_strict_dst_multihoming)
13790 			strict_check = B_TRUE;
13791 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13792 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13793 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13794 	}
13795 	/*
13796 	 * If the same ire that was returned in ip_input() is found then this
13797 	 * is an indication that usesrc groups are in use. The packet
13798 	 * arrived on a different ill in the group than the one associated with
13799 	 * the destination address.  If a different ire was found then the same
13800 	 * IP address must be hosted on multiple ills. This is possible with
13801 	 * unnumbered point2point interfaces. We switch to use this new ire in
13802 	 * order to have accurate interface statistics.
13803 	 */
13804 	if (new_ire != NULL) {
13805 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13806 			ire_refrele(ire);
13807 			ire = new_ire;
13808 		} else {
13809 			ire_refrele(new_ire);
13810 		}
13811 		return (ire);
13812 	} else if ((ire->ire_rfq == NULL) &&
13813 	    (ire->ire_ipversion == IPV4_VERSION)) {
13814 		/*
13815 		 * The best match could have been the original ire which
13816 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13817 		 * the strict multihoming checks are irrelevant as we consider
13818 		 * local addresses hosted on lo0 to be interface agnostic. We
13819 		 * only expect a null ire_rfq on IREs which are associated with
13820 		 * lo0 hence we can return now.
13821 		 */
13822 		return (ire);
13823 	}
13824 
13825 	/*
13826 	 * Chase pointers once and store locally.
13827 	 */
13828 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13829 	    (ill_t *)(ire->ire_rfq->q_ptr);
13830 	ifindex = ill->ill_usesrc_ifindex;
13831 
13832 	/*
13833 	 * Check if it's a legal address on the 'usesrc' interface.
13834 	 */
13835 	if ((ifindex != 0) && (ire_ill != NULL) &&
13836 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13837 		return (ire);
13838 	}
13839 
13840 	/*
13841 	 * If the ip*_strict_dst_multihoming switch is on then we can
13842 	 * only accept this packet if the interface is marked as routing.
13843 	 */
13844 	if (!(strict_check))
13845 		return (ire);
13846 
13847 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13848 	    ILLF_ROUTER) != 0) {
13849 		return (ire);
13850 	}
13851 
13852 	ire_refrele(ire);
13853 	return (NULL);
13854 }
13855 
13856 /*
13857  *
13858  * This is the fast forward path. If we are here, we dont need to
13859  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13860  * needed to find the nexthop in this case is much simpler
13861  */
13862 ire_t *
13863 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13864 {
13865 	ipha_t	*ipha;
13866 	ire_t	*src_ire;
13867 	ill_t	*stq_ill;
13868 	uint_t	hlen;
13869 	uint_t	pkt_len;
13870 	uint32_t sum;
13871 	queue_t	*dev_q;
13872 	ip_stack_t *ipst = ill->ill_ipst;
13873 	mblk_t *fpmp;
13874 	enum	ire_forward_action ret_action;
13875 
13876 	ipha = (ipha_t *)mp->b_rptr;
13877 
13878 	if (ire != NULL &&
13879 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13880 	    ire->ire_zoneid != ALL_ZONES) {
13881 		/*
13882 		 * Should only use IREs that are visible to the global
13883 		 * zone for forwarding.
13884 		 */
13885 		ire_refrele(ire);
13886 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13887 		/*
13888 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13889 		 * transient cases. In such case, just drop the packet
13890 		 */
13891 		if (ire->ire_type != IRE_CACHE)
13892 			goto drop;
13893 	}
13894 
13895 	/*
13896 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13897 	 * The loopback address check for both src and dst has already
13898 	 * been checked in ip_input
13899 	 */
13900 
13901 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13902 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13903 		goto drop;
13904 	}
13905 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13906 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13907 
13908 	if (src_ire != NULL) {
13909 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13910 		ire_refrele(src_ire);
13911 		goto drop;
13912 	}
13913 
13914 	/* No ire cache of nexthop. So first create one  */
13915 	if (ire == NULL) {
13916 
13917 		ire = ire_forward_simple(dst, &ret_action, ipst);
13918 
13919 		/*
13920 		 * We only come to ip_fast_forward if ip_cgtp_filter
13921 		 * is not set. So ire_forward() should not return with
13922 		 * Forward_check_multirt as the next action.
13923 		 */
13924 		ASSERT(ret_action != Forward_check_multirt);
13925 		if (ire == NULL) {
13926 			/* An attempt was made to forward the packet */
13927 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13928 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13929 			mp->b_prev = mp->b_next = 0;
13930 			/* send icmp unreachable */
13931 			/* Sent by forwarding path, and router is global zone */
13932 			if (ret_action == Forward_ret_icmp_err) {
13933 				if (ip_source_routed(ipha, ipst)) {
13934 					icmp_unreachable(ill->ill_wq, mp,
13935 					    ICMP_SOURCE_ROUTE_FAILED,
13936 					    GLOBAL_ZONEID, ipst);
13937 				} else {
13938 					icmp_unreachable(ill->ill_wq, mp,
13939 					    ICMP_HOST_UNREACHABLE,
13940 					    GLOBAL_ZONEID, ipst);
13941 				}
13942 			} else {
13943 				freemsg(mp);
13944 			}
13945 			return (NULL);
13946 		}
13947 	}
13948 
13949 	/*
13950 	 * Forwarding fastpath exception case:
13951 	 * If any of the following are true, we take the slowpath:
13952 	 *	o forwarding is not enabled
13953 	 *	o incoming and outgoing interface are the same, or in the same
13954 	 *	  IPMP group.
13955 	 *	o corresponding ire is in incomplete state
13956 	 *	o packet needs fragmentation
13957 	 *	o ARP cache is not resolved
13958 	 *
13959 	 * The codeflow from here on is thus:
13960 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13961 	 */
13962 	pkt_len = ntohs(ipha->ipha_length);
13963 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13964 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13965 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13966 	    (ire->ire_nce == NULL) ||
13967 	    (pkt_len > ire->ire_max_frag) ||
13968 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13969 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13970 	    ipha->ipha_ttl <= 1) {
13971 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13972 		    ipha, ill, B_FALSE, B_TRUE);
13973 		return (ire);
13974 	}
13975 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13976 
13977 	DTRACE_PROBE4(ip4__forwarding__start,
13978 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13979 
13980 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13981 	    ipst->ips_ipv4firewall_forwarding,
13982 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13983 
13984 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13985 
13986 	if (mp == NULL)
13987 		goto drop;
13988 
13989 	mp->b_datap->db_struioun.cksum.flags = 0;
13990 	/* Adjust the checksum to reflect the ttl decrement. */
13991 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13992 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13993 	ipha->ipha_ttl--;
13994 
13995 	/*
13996 	 * Write the link layer header.  We can do this safely here,
13997 	 * because we have already tested to make sure that the IP
13998 	 * policy is not set, and that we have a fast path destination
13999 	 * header.
14000 	 */
14001 	mp->b_rptr -= hlen;
14002 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14003 
14004 	UPDATE_IB_PKT_COUNT(ire);
14005 	ire->ire_last_used_time = lbolt;
14006 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14007 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14008 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14009 
14010 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14011 		dev_q = ire->ire_stq->q_next;
14012 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14013 			goto indiscard;
14014 	}
14015 
14016 	DTRACE_PROBE4(ip4__physical__out__start,
14017 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14018 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14019 	    ipst->ips_ipv4firewall_physical_out,
14020 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14021 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14022 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14023 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14024 	    ip6_t *, NULL, int, 0);
14025 
14026 	if (mp != NULL) {
14027 		if (ipst->ips_ipobs_enabled) {
14028 			zoneid_t szone;
14029 
14030 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14031 			    ipst, ALL_ZONES);
14032 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14033 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14034 		}
14035 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14036 	}
14037 	return (ire);
14038 
14039 indiscard:
14040 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14041 drop:
14042 	if (mp != NULL)
14043 		freemsg(mp);
14044 	return (ire);
14045 
14046 }
14047 
14048 /*
14049  * This function is called in the forwarding slowpath, when
14050  * either the ire lacks the link-layer address, or the packet needs
14051  * further processing(eg. fragmentation), before transmission.
14052  */
14053 
14054 static void
14055 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14056     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14057 {
14058 	queue_t		*dev_q;
14059 	ire_t		*src_ire;
14060 	ip_stack_t	*ipst = ill->ill_ipst;
14061 	boolean_t	same_illgrp = B_FALSE;
14062 
14063 	ASSERT(ire->ire_stq != NULL);
14064 
14065 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14066 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14067 
14068 	/*
14069 	 * If the caller of this function is ip_fast_forward() skip the
14070 	 * next three checks as it does not apply.
14071 	 */
14072 	if (from_ip_fast_forward)
14073 		goto skip;
14074 
14075 	if (ll_multicast != 0) {
14076 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14077 		goto drop_pkt;
14078 	}
14079 
14080 	/*
14081 	 * check if ipha_src is a broadcast address. Note that this
14082 	 * check is redundant when we get here from ip_fast_forward()
14083 	 * which has already done this check. However, since we can
14084 	 * also get here from ip_rput_process_broadcast() or, for
14085 	 * for the slow path through ip_fast_forward(), we perform
14086 	 * the check again for code-reusability
14087 	 */
14088 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14089 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14090 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14091 		if (src_ire != NULL)
14092 			ire_refrele(src_ire);
14093 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14094 		ip2dbg(("ip_rput_process_forward: Received packet with"
14095 		    " bad src/dst address on %s\n", ill->ill_name));
14096 		goto drop_pkt;
14097 	}
14098 
14099 	/*
14100 	 * Check if we want to forward this one at this time.
14101 	 * We allow source routed packets on a host provided that
14102 	 * they go out the same ill or illgrp as they came in on.
14103 	 *
14104 	 * XXX To be quicker, we may wish to not chase pointers to
14105 	 * get the ILLF_ROUTER flag and instead store the
14106 	 * forwarding policy in the ire.  An unfortunate
14107 	 * side-effect of that would be requiring an ire flush
14108 	 * whenever the ILLF_ROUTER flag changes.
14109 	 */
14110 skip:
14111 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14112 
14113 	if (((ill->ill_flags &
14114 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14115 	    !(ip_source_routed(ipha, ipst) &&
14116 	    (ire->ire_rfq == q || same_illgrp))) {
14117 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14118 		if (ip_source_routed(ipha, ipst)) {
14119 			q = WR(q);
14120 			/*
14121 			 * Clear the indication that this may have
14122 			 * hardware checksum as we are not using it.
14123 			 */
14124 			DB_CKSUMFLAGS(mp) = 0;
14125 			/* Sent by forwarding path, and router is global zone */
14126 			icmp_unreachable(q, mp,
14127 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14128 			return;
14129 		}
14130 		goto drop_pkt;
14131 	}
14132 
14133 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14134 
14135 	/* Packet is being forwarded. Turning off hwcksum flag. */
14136 	DB_CKSUMFLAGS(mp) = 0;
14137 	if (ipst->ips_ip_g_send_redirects) {
14138 		/*
14139 		 * Check whether the incoming interface and outgoing
14140 		 * interface is part of the same group. If so,
14141 		 * send redirects.
14142 		 *
14143 		 * Check the source address to see if it originated
14144 		 * on the same logical subnet it is going back out on.
14145 		 * If so, we should be able to send it a redirect.
14146 		 * Avoid sending a redirect if the destination
14147 		 * is directly connected (i.e., ipha_dst is the same
14148 		 * as ire_gateway_addr or the ire_addr of the
14149 		 * nexthop IRE_CACHE ), or if the packet was source
14150 		 * routed out this interface.
14151 		 */
14152 		ipaddr_t src, nhop;
14153 		mblk_t	*mp1;
14154 		ire_t	*nhop_ire = NULL;
14155 
14156 		/*
14157 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14158 		 * If so, send redirects.
14159 		 */
14160 		if ((ire->ire_rfq == q || same_illgrp) &&
14161 		    !ip_source_routed(ipha, ipst)) {
14162 
14163 			nhop = (ire->ire_gateway_addr != 0 ?
14164 			    ire->ire_gateway_addr : ire->ire_addr);
14165 
14166 			if (ipha->ipha_dst == nhop) {
14167 				/*
14168 				 * We avoid sending a redirect if the
14169 				 * destination is directly connected
14170 				 * because it is possible that multiple
14171 				 * IP subnets may have been configured on
14172 				 * the link, and the source may not
14173 				 * be on the same subnet as ip destination,
14174 				 * even though they are on the same
14175 				 * physical link.
14176 				 */
14177 				goto sendit;
14178 			}
14179 
14180 			src = ipha->ipha_src;
14181 
14182 			/*
14183 			 * We look up the interface ire for the nexthop,
14184 			 * to see if ipha_src is in the same subnet
14185 			 * as the nexthop.
14186 			 *
14187 			 * Note that, if, in the future, IRE_CACHE entries
14188 			 * are obsoleted,  this lookup will not be needed,
14189 			 * as the ire passed to this function will be the
14190 			 * same as the nhop_ire computed below.
14191 			 */
14192 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14193 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14194 			    0, NULL, MATCH_IRE_TYPE, ipst);
14195 
14196 			if (nhop_ire != NULL) {
14197 				if ((src & nhop_ire->ire_mask) ==
14198 				    (nhop & nhop_ire->ire_mask)) {
14199 					/*
14200 					 * The source is directly connected.
14201 					 * Just copy the ip header (which is
14202 					 * in the first mblk)
14203 					 */
14204 					mp1 = copyb(mp);
14205 					if (mp1 != NULL) {
14206 						icmp_send_redirect(WR(q), mp1,
14207 						    nhop, ipst);
14208 					}
14209 				}
14210 				ire_refrele(nhop_ire);
14211 			}
14212 		}
14213 	}
14214 sendit:
14215 	dev_q = ire->ire_stq->q_next;
14216 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14217 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14218 		freemsg(mp);
14219 		return;
14220 	}
14221 
14222 	ip_rput_forward(ire, ipha, mp, ill);
14223 	return;
14224 
14225 drop_pkt:
14226 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14227 	freemsg(mp);
14228 }
14229 
14230 ire_t *
14231 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14232     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14233 {
14234 	queue_t		*q;
14235 	uint16_t	hcksumflags;
14236 	ip_stack_t	*ipst = ill->ill_ipst;
14237 
14238 	q = *qp;
14239 
14240 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14241 
14242 	/*
14243 	 * Clear the indication that this may have hardware
14244 	 * checksum as we are not using it for forwarding.
14245 	 */
14246 	hcksumflags = DB_CKSUMFLAGS(mp);
14247 	DB_CKSUMFLAGS(mp) = 0;
14248 
14249 	/*
14250 	 * Directed broadcast forwarding: if the packet came in over a
14251 	 * different interface then it is routed out over we can forward it.
14252 	 */
14253 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14254 		ire_refrele(ire);
14255 		freemsg(mp);
14256 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14257 		return (NULL);
14258 	}
14259 	/*
14260 	 * For multicast we have set dst to be INADDR_BROADCAST
14261 	 * for delivering to all STREAMS.
14262 	 */
14263 	if (!CLASSD(ipha->ipha_dst)) {
14264 		ire_t *new_ire;
14265 		ipif_t *ipif;
14266 
14267 		ipif = ipif_get_next_ipif(NULL, ill);
14268 		if (ipif == NULL) {
14269 discard:		ire_refrele(ire);
14270 			freemsg(mp);
14271 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14272 			return (NULL);
14273 		}
14274 		new_ire = ire_ctable_lookup(dst, 0, 0,
14275 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14276 		ipif_refrele(ipif);
14277 
14278 		if (new_ire != NULL) {
14279 			/*
14280 			 * If the matching IRE_BROADCAST is part of an IPMP
14281 			 * group, then drop the packet unless our ill has been
14282 			 * nominated to receive for the group.
14283 			 */
14284 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14285 			    new_ire->ire_rfq != q) {
14286 				ire_refrele(new_ire);
14287 				goto discard;
14288 			}
14289 
14290 			/*
14291 			 * In the special case of multirouted broadcast
14292 			 * packets, we unconditionally need to "gateway"
14293 			 * them to the appropriate interface here.
14294 			 * In the normal case, this cannot happen, because
14295 			 * there is no broadcast IRE tagged with the
14296 			 * RTF_MULTIRT flag.
14297 			 */
14298 			if (new_ire->ire_flags & RTF_MULTIRT) {
14299 				ire_refrele(new_ire);
14300 				if (ire->ire_rfq != NULL) {
14301 					q = ire->ire_rfq;
14302 					*qp = q;
14303 				}
14304 			} else {
14305 				ire_refrele(ire);
14306 				ire = new_ire;
14307 			}
14308 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14309 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14310 				/*
14311 				 * Free the message if
14312 				 * ip_g_forward_directed_bcast is turned
14313 				 * off for non-local broadcast.
14314 				 */
14315 				ire_refrele(ire);
14316 				freemsg(mp);
14317 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14318 				return (NULL);
14319 			}
14320 		} else {
14321 			/*
14322 			 * This CGTP packet successfully passed the
14323 			 * CGTP filter, but the related CGTP
14324 			 * broadcast IRE has not been found,
14325 			 * meaning that the redundant ipif is
14326 			 * probably down. However, if we discarded
14327 			 * this packet, its duplicate would be
14328 			 * filtered out by the CGTP filter so none
14329 			 * of them would get through. So we keep
14330 			 * going with this one.
14331 			 */
14332 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14333 			if (ire->ire_rfq != NULL) {
14334 				q = ire->ire_rfq;
14335 				*qp = q;
14336 			}
14337 		}
14338 	}
14339 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14340 		/*
14341 		 * Verify that there are not more then one
14342 		 * IRE_BROADCAST with this broadcast address which
14343 		 * has ire_stq set.
14344 		 * TODO: simplify, loop over all IRE's
14345 		 */
14346 		ire_t	*ire1;
14347 		int	num_stq = 0;
14348 		mblk_t	*mp1;
14349 
14350 		/* Find the first one with ire_stq set */
14351 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14352 		for (ire1 = ire; ire1 &&
14353 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14354 		    ire1 = ire1->ire_next)
14355 			;
14356 		if (ire1) {
14357 			ire_refrele(ire);
14358 			ire = ire1;
14359 			IRE_REFHOLD(ire);
14360 		}
14361 
14362 		/* Check if there are additional ones with stq set */
14363 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14364 			if (ire->ire_addr != ire1->ire_addr)
14365 				break;
14366 			if (ire1->ire_stq) {
14367 				num_stq++;
14368 				break;
14369 			}
14370 		}
14371 		rw_exit(&ire->ire_bucket->irb_lock);
14372 		if (num_stq == 1 && ire->ire_stq != NULL) {
14373 			ip1dbg(("ip_rput_process_broadcast: directed "
14374 			    "broadcast to 0x%x\n",
14375 			    ntohl(ire->ire_addr)));
14376 			mp1 = copymsg(mp);
14377 			if (mp1) {
14378 				switch (ipha->ipha_protocol) {
14379 				case IPPROTO_UDP:
14380 					ip_udp_input(q, mp1, ipha, ire, ill);
14381 					break;
14382 				default:
14383 					ip_proto_input(q, mp1, ipha, ire, ill,
14384 					    0);
14385 					break;
14386 				}
14387 			}
14388 			/*
14389 			 * Adjust ttl to 2 (1+1 - the forward engine
14390 			 * will decrement it by one.
14391 			 */
14392 			if (ip_csum_hdr(ipha)) {
14393 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14394 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14395 				freemsg(mp);
14396 				ire_refrele(ire);
14397 				return (NULL);
14398 			}
14399 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14400 			ipha->ipha_hdr_checksum = 0;
14401 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14402 			ip_rput_process_forward(q, mp, ire, ipha,
14403 			    ill, ll_multicast, B_FALSE);
14404 			ire_refrele(ire);
14405 			return (NULL);
14406 		}
14407 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14408 		    ntohl(ire->ire_addr)));
14409 	}
14410 
14411 	/* Restore any hardware checksum flags */
14412 	DB_CKSUMFLAGS(mp) = hcksumflags;
14413 	return (ire);
14414 }
14415 
14416 /* ARGSUSED */
14417 static boolean_t
14418 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14419     int *ll_multicast, ipaddr_t *dstp)
14420 {
14421 	ip_stack_t	*ipst = ill->ill_ipst;
14422 
14423 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14424 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14425 	    ntohs(ipha->ipha_length));
14426 
14427 	/*
14428 	 * So that we don't end up with dups, only one ill in an IPMP group is
14429 	 * nominated to receive multicast traffic.
14430 	 */
14431 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14432 		goto drop_pkt;
14433 
14434 	/*
14435 	 * Forward packets only if we have joined the allmulti
14436 	 * group on this interface.
14437 	 */
14438 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14439 		int retval;
14440 
14441 		/*
14442 		 * Clear the indication that this may have hardware
14443 		 * checksum as we are not using it.
14444 		 */
14445 		DB_CKSUMFLAGS(mp) = 0;
14446 		retval = ip_mforward(ill, ipha, mp);
14447 		/* ip_mforward updates mib variables if needed */
14448 		/* clear b_prev - used by ip_mroute_decap */
14449 		mp->b_prev = NULL;
14450 
14451 		switch (retval) {
14452 		case 0:
14453 			/*
14454 			 * pkt is okay and arrived on phyint.
14455 			 *
14456 			 * If we are running as a multicast router
14457 			 * we need to see all IGMP and/or PIM packets.
14458 			 */
14459 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14460 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14461 				goto done;
14462 			}
14463 			break;
14464 		case -1:
14465 			/* pkt is mal-formed, toss it */
14466 			goto drop_pkt;
14467 		case 1:
14468 			/* pkt is okay and arrived on a tunnel */
14469 			/*
14470 			 * If we are running a multicast router
14471 			 *  we need to see all igmp packets.
14472 			 */
14473 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14474 				*dstp = INADDR_BROADCAST;
14475 				*ll_multicast = 1;
14476 				return (B_FALSE);
14477 			}
14478 
14479 			goto drop_pkt;
14480 		}
14481 	}
14482 
14483 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14484 		/*
14485 		 * This might just be caused by the fact that
14486 		 * multiple IP Multicast addresses map to the same
14487 		 * link layer multicast - no need to increment counter!
14488 		 */
14489 		freemsg(mp);
14490 		return (B_TRUE);
14491 	}
14492 done:
14493 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14494 	/*
14495 	 * This assumes the we deliver to all streams for multicast
14496 	 * and broadcast packets.
14497 	 */
14498 	*dstp = INADDR_BROADCAST;
14499 	*ll_multicast = 1;
14500 	return (B_FALSE);
14501 drop_pkt:
14502 	ip2dbg(("ip_rput: drop pkt\n"));
14503 	freemsg(mp);
14504 	return (B_TRUE);
14505 }
14506 
14507 /*
14508  * This function is used to both return an indication of whether or not
14509  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14510  * and in doing so, determine whether or not it is broadcast vs multicast.
14511  * For it to be a broadcast packet, we must have the appropriate mblk_t
14512  * hanging off the ill_t.  If this is either not present or doesn't match
14513  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14514  * to be multicast.  Thus NICs that have no broadcast address (or no
14515  * capability for one, such as point to point links) cannot return as
14516  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14517  * the return values simplifies the current use of the return value of this
14518  * function, which is to pass through the multicast/broadcast characteristic
14519  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14520  * changing the return value to some other symbol demands the appropriate
14521  * "translation" when hpe_flags is set prior to calling hook_run() for
14522  * packet events.
14523  */
14524 int
14525 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14526 {
14527 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14528 	mblk_t *bmp;
14529 
14530 	if (ind->dl_group_address) {
14531 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14532 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14533 		    MBLKL(mb) &&
14534 		    (bmp = ill->ill_bcast_mp) != NULL) {
14535 			dl_unitdata_req_t *dlur;
14536 			uint8_t *bphys_addr;
14537 
14538 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14539 			if (ill->ill_sap_length < 0)
14540 				bphys_addr = (uchar_t *)dlur +
14541 				    dlur->dl_dest_addr_offset;
14542 			else
14543 				bphys_addr = (uchar_t *)dlur +
14544 				    dlur->dl_dest_addr_offset +
14545 				    ill->ill_sap_length;
14546 
14547 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14548 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14549 				return (HPE_BROADCAST);
14550 			}
14551 			return (HPE_MULTICAST);
14552 		}
14553 		return (HPE_MULTICAST);
14554 	}
14555 	return (0);
14556 }
14557 
14558 static boolean_t
14559 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14560     int *ll_multicast, mblk_t **mpp)
14561 {
14562 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14563 	boolean_t must_copy = B_FALSE;
14564 	struct iocblk   *iocp;
14565 	ipha_t		*ipha;
14566 	ip_stack_t	*ipst = ill->ill_ipst;
14567 
14568 #define	rptr    ((uchar_t *)ipha)
14569 
14570 	first_mp = *first_mpp;
14571 	mp = *mpp;
14572 
14573 	ASSERT(first_mp == mp);
14574 
14575 	/*
14576 	 * if db_ref > 1 then copymsg and free original. Packet may be
14577 	 * changed and do not want other entity who has a reference to this
14578 	 * message to trip over the changes. This is a blind change because
14579 	 * trying to catch all places that might change packet is too
14580 	 * difficult (since it may be a module above this one)
14581 	 *
14582 	 * This corresponds to the non-fast path case. We walk down the full
14583 	 * chain in this case, and check the db_ref count of all the dblks,
14584 	 * and do a copymsg if required. It is possible that the db_ref counts
14585 	 * of the data blocks in the mblk chain can be different.
14586 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14587 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14588 	 * 'snoop' is running.
14589 	 */
14590 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14591 		if (mp1->b_datap->db_ref > 1) {
14592 			must_copy = B_TRUE;
14593 			break;
14594 		}
14595 	}
14596 
14597 	if (must_copy) {
14598 		mp1 = copymsg(mp);
14599 		if (mp1 == NULL) {
14600 			for (mp1 = mp; mp1 != NULL;
14601 			    mp1 = mp1->b_cont) {
14602 				mp1->b_next = NULL;
14603 				mp1->b_prev = NULL;
14604 			}
14605 			freemsg(mp);
14606 			if (ill != NULL) {
14607 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14608 			} else {
14609 				BUMP_MIB(&ipst->ips_ip_mib,
14610 				    ipIfStatsInDiscards);
14611 			}
14612 			return (B_TRUE);
14613 		}
14614 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14615 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14616 			/* Copy b_prev - used by ip_mroute_decap */
14617 			to_mp->b_prev = from_mp->b_prev;
14618 			from_mp->b_prev = NULL;
14619 		}
14620 		*first_mpp = first_mp = mp1;
14621 		freemsg(mp);
14622 		mp = mp1;
14623 		*mpp = mp1;
14624 	}
14625 
14626 	ipha = (ipha_t *)mp->b_rptr;
14627 
14628 	/*
14629 	 * previous code has a case for M_DATA.
14630 	 * We want to check how that happens.
14631 	 */
14632 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14633 	switch (first_mp->b_datap->db_type) {
14634 	case M_PROTO:
14635 	case M_PCPROTO:
14636 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14637 		    DL_UNITDATA_IND) {
14638 			/* Go handle anything other than data elsewhere. */
14639 			ip_rput_dlpi(q, mp);
14640 			return (B_TRUE);
14641 		}
14642 
14643 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14644 		/* Ditch the DLPI header. */
14645 		mp1 = mp->b_cont;
14646 		ASSERT(first_mp == mp);
14647 		*first_mpp = mp1;
14648 		freeb(mp);
14649 		*mpp = mp1;
14650 		return (B_FALSE);
14651 	case M_IOCACK:
14652 		ip1dbg(("got iocack "));
14653 		iocp = (struct iocblk *)mp->b_rptr;
14654 		switch (iocp->ioc_cmd) {
14655 		case DL_IOC_HDR_INFO:
14656 			ill = (ill_t *)q->q_ptr;
14657 			ill_fastpath_ack(ill, mp);
14658 			return (B_TRUE);
14659 		case SIOCSTUNPARAM:
14660 		case OSIOCSTUNPARAM:
14661 			/* Go through qwriter_ip */
14662 			break;
14663 		case SIOCGTUNPARAM:
14664 		case OSIOCGTUNPARAM:
14665 			ip_rput_other(NULL, q, mp, NULL);
14666 			return (B_TRUE);
14667 		default:
14668 			putnext(q, mp);
14669 			return (B_TRUE);
14670 		}
14671 		/* FALLTHRU */
14672 	case M_ERROR:
14673 	case M_HANGUP:
14674 		/*
14675 		 * Since this is on the ill stream we unconditionally
14676 		 * bump up the refcount
14677 		 */
14678 		ill_refhold(ill);
14679 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14680 		return (B_TRUE);
14681 	case M_CTL:
14682 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14683 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14684 		    IPHADA_M_CTL)) {
14685 			/*
14686 			 * It's an IPsec accelerated packet.
14687 			 * Make sure that the ill from which we received the
14688 			 * packet has enabled IPsec hardware acceleration.
14689 			 */
14690 			if (!(ill->ill_capabilities &
14691 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14692 				/* IPsec kstats: bean counter */
14693 				freemsg(mp);
14694 				return (B_TRUE);
14695 			}
14696 
14697 			/*
14698 			 * Make mp point to the mblk following the M_CTL,
14699 			 * then process according to type of mp.
14700 			 * After this processing, first_mp will point to
14701 			 * the data-attributes and mp to the pkt following
14702 			 * the M_CTL.
14703 			 */
14704 			mp = first_mp->b_cont;
14705 			if (mp == NULL) {
14706 				freemsg(first_mp);
14707 				return (B_TRUE);
14708 			}
14709 			/*
14710 			 * A Hardware Accelerated packet can only be M_DATA
14711 			 * ESP or AH packet.
14712 			 */
14713 			if (mp->b_datap->db_type != M_DATA) {
14714 				/* non-M_DATA IPsec accelerated packet */
14715 				IPSECHW_DEBUG(IPSECHW_PKT,
14716 				    ("non-M_DATA IPsec accelerated pkt\n"));
14717 				freemsg(first_mp);
14718 				return (B_TRUE);
14719 			}
14720 			ipha = (ipha_t *)mp->b_rptr;
14721 			if (ipha->ipha_protocol != IPPROTO_AH &&
14722 			    ipha->ipha_protocol != IPPROTO_ESP) {
14723 				IPSECHW_DEBUG(IPSECHW_PKT,
14724 				    ("non-M_DATA IPsec accelerated pkt\n"));
14725 				freemsg(first_mp);
14726 				return (B_TRUE);
14727 			}
14728 			*mpp = mp;
14729 			return (B_FALSE);
14730 		}
14731 		putnext(q, mp);
14732 		return (B_TRUE);
14733 	case M_IOCNAK:
14734 		ip1dbg(("got iocnak "));
14735 		iocp = (struct iocblk *)mp->b_rptr;
14736 		switch (iocp->ioc_cmd) {
14737 		case SIOCSTUNPARAM:
14738 		case OSIOCSTUNPARAM:
14739 			/*
14740 			 * Since this is on the ill stream we unconditionally
14741 			 * bump up the refcount
14742 			 */
14743 			ill_refhold(ill);
14744 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14745 			return (B_TRUE);
14746 		case DL_IOC_HDR_INFO:
14747 		case SIOCGTUNPARAM:
14748 		case OSIOCGTUNPARAM:
14749 			ip_rput_other(NULL, q, mp, NULL);
14750 			return (B_TRUE);
14751 		default:
14752 			break;
14753 		}
14754 		/* FALLTHRU */
14755 	default:
14756 		putnext(q, mp);
14757 		return (B_TRUE);
14758 	}
14759 }
14760 
14761 /* Read side put procedure.  Packets coming from the wire arrive here. */
14762 void
14763 ip_rput(queue_t *q, mblk_t *mp)
14764 {
14765 	ill_t	*ill;
14766 	union DL_primitives *dl;
14767 
14768 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14769 
14770 	ill = (ill_t *)q->q_ptr;
14771 
14772 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14773 		/*
14774 		 * If things are opening or closing, only accept high-priority
14775 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14776 		 * created; on close, things hanging off the ill may have been
14777 		 * freed already.)
14778 		 */
14779 		dl = (union DL_primitives *)mp->b_rptr;
14780 		if (DB_TYPE(mp) != M_PCPROTO ||
14781 		    dl->dl_primitive == DL_UNITDATA_IND) {
14782 			/*
14783 			 * SIOC[GS]TUNPARAM ioctls can come here.
14784 			 */
14785 			inet_freemsg(mp);
14786 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14787 			    "ip_rput_end: q %p (%S)", q, "uninit");
14788 			return;
14789 		}
14790 	}
14791 
14792 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14793 	    "ip_rput_end: q %p (%S)", q, "end");
14794 
14795 	ip_input(ill, NULL, mp, NULL);
14796 }
14797 
14798 static mblk_t *
14799 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14800 {
14801 	mblk_t *mp1;
14802 	boolean_t adjusted = B_FALSE;
14803 	ip_stack_t *ipst = ill->ill_ipst;
14804 
14805 	IP_STAT(ipst, ip_db_ref);
14806 	/*
14807 	 * The IP_RECVSLLA option depends on having the
14808 	 * link layer header. First check that:
14809 	 * a> the underlying device is of type ether,
14810 	 * since this option is currently supported only
14811 	 * over ethernet.
14812 	 * b> there is enough room to copy over the link
14813 	 * layer header.
14814 	 *
14815 	 * Once the checks are done, adjust rptr so that
14816 	 * the link layer header will be copied via
14817 	 * copymsg. Note that, IFT_ETHER may be returned
14818 	 * by some non-ethernet drivers but in this case
14819 	 * the second check will fail.
14820 	 */
14821 	if (ill->ill_type == IFT_ETHER &&
14822 	    (mp->b_rptr - mp->b_datap->db_base) >=
14823 	    sizeof (struct ether_header)) {
14824 		mp->b_rptr -= sizeof (struct ether_header);
14825 		adjusted = B_TRUE;
14826 	}
14827 	mp1 = copymsg(mp);
14828 
14829 	if (mp1 == NULL) {
14830 		mp->b_next = NULL;
14831 		/* clear b_prev - used by ip_mroute_decap */
14832 		mp->b_prev = NULL;
14833 		freemsg(mp);
14834 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14835 		return (NULL);
14836 	}
14837 
14838 	if (adjusted) {
14839 		/*
14840 		 * Copy is done. Restore the pointer in
14841 		 * the _new_ mblk
14842 		 */
14843 		mp1->b_rptr += sizeof (struct ether_header);
14844 	}
14845 
14846 	/* Copy b_prev - used by ip_mroute_decap */
14847 	mp1->b_prev = mp->b_prev;
14848 	mp->b_prev = NULL;
14849 
14850 	/* preserve the hardware checksum flags and data, if present */
14851 	if (DB_CKSUMFLAGS(mp) != 0) {
14852 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14853 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14854 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14855 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14856 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14857 	}
14858 
14859 	freemsg(mp);
14860 	return (mp1);
14861 }
14862 
14863 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14864 	if (tail != NULL)					\
14865 		tail->b_next = mp;				\
14866 	else							\
14867 		head = mp;					\
14868 	tail = mp;						\
14869 	cnt++;							\
14870 }
14871 
14872 /*
14873  * Direct read side procedure capable of dealing with chains. GLDv3 based
14874  * drivers call this function directly with mblk chains while STREAMS
14875  * read side procedure ip_rput() calls this for single packet with ip_ring
14876  * set to NULL to process one packet at a time.
14877  *
14878  * The ill will always be valid if this function is called directly from
14879  * the driver.
14880  *
14881  * If ip_input() is called from GLDv3:
14882  *
14883  *   - This must be a non-VLAN IP stream.
14884  *   - 'mp' is either an untagged or a special priority-tagged packet.
14885  *   - Any VLAN tag that was in the MAC header has been stripped.
14886  *
14887  * If the IP header in packet is not 32-bit aligned, every message in the
14888  * chain will be aligned before further operations. This is required on SPARC
14889  * platform.
14890  */
14891 /* ARGSUSED */
14892 void
14893 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14894     struct mac_header_info_s *mhip)
14895 {
14896 	ipaddr_t		dst = NULL;
14897 	ipaddr_t		prev_dst;
14898 	ire_t			*ire = NULL;
14899 	ipha_t			*ipha;
14900 	uint_t			pkt_len;
14901 	ssize_t			len;
14902 	uint_t			opt_len;
14903 	int			ll_multicast;
14904 	int			cgtp_flt_pkt;
14905 	queue_t			*q = ill->ill_rq;
14906 	squeue_t		*curr_sqp = NULL;
14907 	mblk_t 			*head = NULL;
14908 	mblk_t			*tail = NULL;
14909 	mblk_t			*first_mp;
14910 	int			cnt = 0;
14911 	ip_stack_t		*ipst = ill->ill_ipst;
14912 	mblk_t			*mp;
14913 	mblk_t			*dmp;
14914 	uint8_t			tag;
14915 
14916 	ASSERT(mp_chain != NULL);
14917 	ASSERT(ill != NULL);
14918 
14919 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14920 
14921 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14922 
14923 #define	rptr	((uchar_t *)ipha)
14924 
14925 	while (mp_chain != NULL) {
14926 		mp = mp_chain;
14927 		mp_chain = mp_chain->b_next;
14928 		mp->b_next = NULL;
14929 		ll_multicast = 0;
14930 
14931 		/*
14932 		 * We do ire caching from one iteration to
14933 		 * another. In the event the packet chain contains
14934 		 * all packets from the same dst, this caching saves
14935 		 * an ire_cache_lookup for each of the succeeding
14936 		 * packets in a packet chain.
14937 		 */
14938 		prev_dst = dst;
14939 
14940 		/*
14941 		 * if db_ref > 1 then copymsg and free original. Packet
14942 		 * may be changed and we do not want the other entity
14943 		 * who has a reference to this message to trip over the
14944 		 * changes. This is a blind change because trying to
14945 		 * catch all places that might change the packet is too
14946 		 * difficult.
14947 		 *
14948 		 * This corresponds to the fast path case, where we have
14949 		 * a chain of M_DATA mblks.  We check the db_ref count
14950 		 * of only the 1st data block in the mblk chain. There
14951 		 * doesn't seem to be a reason why a device driver would
14952 		 * send up data with varying db_ref counts in the mblk
14953 		 * chain. In any case the Fast path is a private
14954 		 * interface, and our drivers don't do such a thing.
14955 		 * Given the above assumption, there is no need to walk
14956 		 * down the entire mblk chain (which could have a
14957 		 * potential performance problem)
14958 		 *
14959 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14960 		 * to here because of exclusive ip stacks and vnics.
14961 		 * Packets transmitted from exclusive stack over vnic
14962 		 * can have db_ref > 1 and when it gets looped back to
14963 		 * another vnic in a different zone, you have ip_input()
14964 		 * getting dblks with db_ref > 1. So if someone
14965 		 * complains of TCP performance under this scenario,
14966 		 * take a serious look here on the impact of copymsg().
14967 		 */
14968 
14969 		if (DB_REF(mp) > 1) {
14970 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14971 				continue;
14972 		}
14973 
14974 		/*
14975 		 * Check and align the IP header.
14976 		 */
14977 		first_mp = mp;
14978 		if (DB_TYPE(mp) == M_DATA) {
14979 			dmp = mp;
14980 		} else if (DB_TYPE(mp) == M_PROTO &&
14981 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14982 			dmp = mp->b_cont;
14983 		} else {
14984 			dmp = NULL;
14985 		}
14986 		if (dmp != NULL) {
14987 			/*
14988 			 * IP header ptr not aligned?
14989 			 * OR IP header not complete in first mblk
14990 			 */
14991 			if (!OK_32PTR(dmp->b_rptr) ||
14992 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14993 				if (!ip_check_and_align_header(q, dmp, ipst))
14994 					continue;
14995 			}
14996 		}
14997 
14998 		/*
14999 		 * ip_input fast path
15000 		 */
15001 
15002 		/* mblk type is not M_DATA */
15003 		if (DB_TYPE(mp) != M_DATA) {
15004 			if (ip_rput_process_notdata(q, &first_mp, ill,
15005 			    &ll_multicast, &mp))
15006 				continue;
15007 
15008 			/*
15009 			 * The only way we can get here is if we had a
15010 			 * packet that was either a DL_UNITDATA_IND or
15011 			 * an M_CTL for an IPsec accelerated packet.
15012 			 *
15013 			 * In either case, the first_mp will point to
15014 			 * the leading M_PROTO or M_CTL.
15015 			 */
15016 			ASSERT(first_mp != NULL);
15017 		} else if (mhip != NULL) {
15018 			/*
15019 			 * ll_multicast is set here so that it is ready
15020 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15021 			 * manipulates ll_multicast in the same fashion when
15022 			 * called from ip_rput_process_notdata.
15023 			 */
15024 			switch (mhip->mhi_dsttype) {
15025 			case MAC_ADDRTYPE_MULTICAST :
15026 				ll_multicast = HPE_MULTICAST;
15027 				break;
15028 			case MAC_ADDRTYPE_BROADCAST :
15029 				ll_multicast = HPE_BROADCAST;
15030 				break;
15031 			default :
15032 				break;
15033 			}
15034 		}
15035 
15036 		/* Only M_DATA can come here and it is always aligned */
15037 		ASSERT(DB_TYPE(mp) == M_DATA);
15038 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15039 
15040 		ipha = (ipha_t *)mp->b_rptr;
15041 		len = mp->b_wptr - rptr;
15042 		pkt_len = ntohs(ipha->ipha_length);
15043 
15044 		/*
15045 		 * We must count all incoming packets, even if they end
15046 		 * up being dropped later on.
15047 		 */
15048 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15049 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15050 
15051 		/* multiple mblk or too short */
15052 		len -= pkt_len;
15053 		if (len != 0) {
15054 			/*
15055 			 * Make sure we have data length consistent
15056 			 * with the IP header.
15057 			 */
15058 			if (mp->b_cont == NULL) {
15059 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15060 					BUMP_MIB(ill->ill_ip_mib,
15061 					    ipIfStatsInHdrErrors);
15062 					ip2dbg(("ip_input: drop pkt\n"));
15063 					freemsg(mp);
15064 					continue;
15065 				}
15066 				mp->b_wptr = rptr + pkt_len;
15067 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15068 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15069 					BUMP_MIB(ill->ill_ip_mib,
15070 					    ipIfStatsInHdrErrors);
15071 					ip2dbg(("ip_input: drop pkt\n"));
15072 					freemsg(mp);
15073 					continue;
15074 				}
15075 				(void) adjmsg(mp, -len);
15076 				IP_STAT(ipst, ip_multimblk3);
15077 			}
15078 		}
15079 
15080 		/* Obtain the dst of the current packet */
15081 		dst = ipha->ipha_dst;
15082 
15083 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15084 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15085 		    ipha, ip6_t *, NULL, int, 0);
15086 
15087 		/*
15088 		 * The following test for loopback is faster than
15089 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15090 		 * operations.
15091 		 * Note that these addresses are always in network byte order
15092 		 */
15093 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15094 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15095 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15096 			freemsg(mp);
15097 			continue;
15098 		}
15099 
15100 		/*
15101 		 * The event for packets being received from a 'physical'
15102 		 * interface is placed after validation of the source and/or
15103 		 * destination address as being local so that packets can be
15104 		 * redirected to loopback addresses using ipnat.
15105 		 */
15106 		DTRACE_PROBE4(ip4__physical__in__start,
15107 		    ill_t *, ill, ill_t *, NULL,
15108 		    ipha_t *, ipha, mblk_t *, first_mp);
15109 
15110 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15111 		    ipst->ips_ipv4firewall_physical_in,
15112 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15113 
15114 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15115 
15116 		if (first_mp == NULL) {
15117 			continue;
15118 		}
15119 		dst = ipha->ipha_dst;
15120 		/*
15121 		 * Attach any necessary label information to
15122 		 * this packet
15123 		 */
15124 		if (is_system_labeled() &&
15125 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15126 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15127 			freemsg(mp);
15128 			continue;
15129 		}
15130 
15131 		if (ipst->ips_ipobs_enabled) {
15132 			zoneid_t dzone;
15133 
15134 			/*
15135 			 * On the inbound path the src zone will be unknown as
15136 			 * this packet has come from the wire.
15137 			 */
15138 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15139 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15140 			    ill, IPV4_VERSION, 0, ipst);
15141 		}
15142 
15143 		/*
15144 		 * Reuse the cached ire only if the ipha_dst of the previous
15145 		 * packet is the same as the current packet AND it is not
15146 		 * INADDR_ANY.
15147 		 */
15148 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15149 		    (ire != NULL)) {
15150 			ire_refrele(ire);
15151 			ire = NULL;
15152 		}
15153 
15154 		opt_len = ipha->ipha_version_and_hdr_length -
15155 		    IP_SIMPLE_HDR_VERSION;
15156 
15157 		/*
15158 		 * Check to see if we can take the fastpath.
15159 		 * That is possible if the following conditions are met
15160 		 *	o Tsol disabled
15161 		 *	o CGTP disabled
15162 		 *	o ipp_action_count is 0
15163 		 *	o no options in the packet
15164 		 *	o not a RSVP packet
15165 		 * 	o not a multicast packet
15166 		 *	o ill not in IP_DHCPINIT_IF mode
15167 		 */
15168 		if (!is_system_labeled() &&
15169 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15170 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15171 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15172 			if (ire == NULL)
15173 				ire = ire_cache_lookup_simple(dst, ipst);
15174 			/*
15175 			 * Unless forwarding is enabled, dont call
15176 			 * ip_fast_forward(). Incoming packet is for forwarding
15177 			 */
15178 			if ((ill->ill_flags & ILLF_ROUTER) &&
15179 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15180 				ire = ip_fast_forward(ire, dst, ill, mp);
15181 				continue;
15182 			}
15183 			/* incoming packet is for local consumption */
15184 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15185 				goto local;
15186 		}
15187 
15188 		/*
15189 		 * Disable ire caching for anything more complex
15190 		 * than the simple fast path case we checked for above.
15191 		 */
15192 		if (ire != NULL) {
15193 			ire_refrele(ire);
15194 			ire = NULL;
15195 		}
15196 
15197 		/*
15198 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15199 		 * server to unicast DHCP packets to a DHCP client using the
15200 		 * IP address it is offering to the client.  This can be
15201 		 * disabled through the "broadcast bit", but not all DHCP
15202 		 * servers honor that bit.  Therefore, to interoperate with as
15203 		 * many DHCP servers as possible, the DHCP client allows the
15204 		 * server to unicast, but we treat those packets as broadcast
15205 		 * here.  Note that we don't rewrite the packet itself since
15206 		 * (a) that would mess up the checksums and (b) the DHCP
15207 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15208 		 * hand it the packet regardless.
15209 		 */
15210 		if (ill->ill_dhcpinit != 0 &&
15211 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15212 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15213 			udpha_t *udpha;
15214 
15215 			/*
15216 			 * Reload ipha since pullupmsg() can change b_rptr.
15217 			 */
15218 			ipha = (ipha_t *)mp->b_rptr;
15219 			udpha = (udpha_t *)&ipha[1];
15220 
15221 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15222 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15223 				    mblk_t *, mp);
15224 				dst = INADDR_BROADCAST;
15225 			}
15226 		}
15227 
15228 		/* Full-blown slow path */
15229 		if (opt_len != 0) {
15230 			if (len != 0)
15231 				IP_STAT(ipst, ip_multimblk4);
15232 			else
15233 				IP_STAT(ipst, ip_ipoptions);
15234 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15235 			    &dst, ipst))
15236 				continue;
15237 		}
15238 
15239 		/*
15240 		 * Invoke the CGTP (multirouting) filtering module to process
15241 		 * the incoming packet. Packets identified as duplicates
15242 		 * must be discarded. Filtering is active only if the
15243 		 * the ip_cgtp_filter ndd variable is non-zero.
15244 		 */
15245 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15246 		if (ipst->ips_ip_cgtp_filter &&
15247 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15248 			netstackid_t stackid;
15249 
15250 			stackid = ipst->ips_netstack->netstack_stackid;
15251 			cgtp_flt_pkt =
15252 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15253 			    ill->ill_phyint->phyint_ifindex, mp);
15254 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15255 				freemsg(first_mp);
15256 				continue;
15257 			}
15258 		}
15259 
15260 		/*
15261 		 * If rsvpd is running, let RSVP daemon handle its processing
15262 		 * and forwarding of RSVP multicast/unicast packets.
15263 		 * If rsvpd is not running but mrouted is running, RSVP
15264 		 * multicast packets are forwarded as multicast traffic
15265 		 * and RSVP unicast packets are forwarded by unicast router.
15266 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15267 		 * packets are not forwarded, but the unicast packets are
15268 		 * forwarded like unicast traffic.
15269 		 */
15270 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15271 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15272 		    NULL) {
15273 			/* RSVP packet and rsvpd running. Treat as ours */
15274 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15275 			/*
15276 			 * This assumes that we deliver to all streams for
15277 			 * multicast and broadcast packets.
15278 			 * We have to force ll_multicast to 1 to handle the
15279 			 * M_DATA messages passed in from ip_mroute_decap.
15280 			 */
15281 			dst = INADDR_BROADCAST;
15282 			ll_multicast = 1;
15283 		} else if (CLASSD(dst)) {
15284 			/* packet is multicast */
15285 			mp->b_next = NULL;
15286 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15287 			    &ll_multicast, &dst))
15288 				continue;
15289 		}
15290 
15291 		if (ire == NULL) {
15292 			ire = ire_cache_lookup(dst, ALL_ZONES,
15293 			    msg_getlabel(mp), ipst);
15294 		}
15295 
15296 		if (ire != NULL && ire->ire_stq != NULL &&
15297 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15298 		    ire->ire_zoneid != ALL_ZONES) {
15299 			/*
15300 			 * Should only use IREs that are visible from the
15301 			 * global zone for forwarding.
15302 			 */
15303 			ire_refrele(ire);
15304 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15305 			    msg_getlabel(mp), ipst);
15306 		}
15307 
15308 		if (ire == NULL) {
15309 			/*
15310 			 * No IRE for this destination, so it can't be for us.
15311 			 * Unless we are forwarding, drop the packet.
15312 			 * We have to let source routed packets through
15313 			 * since we don't yet know if they are 'ping -l'
15314 			 * packets i.e. if they will go out over the
15315 			 * same interface as they came in on.
15316 			 */
15317 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15318 			if (ire == NULL)
15319 				continue;
15320 		}
15321 
15322 		/*
15323 		 * Broadcast IRE may indicate either broadcast or
15324 		 * multicast packet
15325 		 */
15326 		if (ire->ire_type == IRE_BROADCAST) {
15327 			/*
15328 			 * Skip broadcast checks if packet is UDP multicast;
15329 			 * we'd rather not enter ip_rput_process_broadcast()
15330 			 * unless the packet is broadcast for real, since
15331 			 * that routine is a no-op for multicast.
15332 			 */
15333 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15334 			    !CLASSD(ipha->ipha_dst)) {
15335 				ire = ip_rput_process_broadcast(&q, mp,
15336 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15337 				    ll_multicast);
15338 				if (ire == NULL)
15339 					continue;
15340 			}
15341 		} else if (ire->ire_stq != NULL) {
15342 			/* fowarding? */
15343 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15344 			    ll_multicast, B_FALSE);
15345 			/* ip_rput_process_forward consumed the packet */
15346 			continue;
15347 		}
15348 
15349 local:
15350 		/*
15351 		 * If the queue in the ire is different to the ingress queue
15352 		 * then we need to check to see if we can accept the packet.
15353 		 * Note that for multicast packets and broadcast packets sent
15354 		 * to a broadcast address which is shared between multiple
15355 		 * interfaces we should not do this since we just got a random
15356 		 * broadcast ire.
15357 		 */
15358 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15359 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15360 			if (ire == NULL) {
15361 				/* Drop packet */
15362 				BUMP_MIB(ill->ill_ip_mib,
15363 				    ipIfStatsForwProhibits);
15364 				freemsg(mp);
15365 				continue;
15366 			}
15367 			if (ire->ire_rfq != NULL)
15368 				q = ire->ire_rfq;
15369 		}
15370 
15371 		switch (ipha->ipha_protocol) {
15372 		case IPPROTO_TCP:
15373 			ASSERT(first_mp == mp);
15374 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15375 			    mp, 0, q, ip_ring)) != NULL) {
15376 				if (curr_sqp == NULL) {
15377 					curr_sqp = GET_SQUEUE(mp);
15378 					ASSERT(cnt == 0);
15379 					cnt++;
15380 					head = tail = mp;
15381 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15382 					ASSERT(tail != NULL);
15383 					cnt++;
15384 					tail->b_next = mp;
15385 					tail = mp;
15386 				} else {
15387 					/*
15388 					 * A different squeue. Send the
15389 					 * chain for the previous squeue on
15390 					 * its way. This shouldn't happen
15391 					 * often unless interrupt binding
15392 					 * changes.
15393 					 */
15394 					IP_STAT(ipst, ip_input_multi_squeue);
15395 					SQUEUE_ENTER(curr_sqp, head,
15396 					    tail, cnt, SQ_PROCESS, tag);
15397 					curr_sqp = GET_SQUEUE(mp);
15398 					head = mp;
15399 					tail = mp;
15400 					cnt = 1;
15401 				}
15402 			}
15403 			continue;
15404 		case IPPROTO_UDP:
15405 			ASSERT(first_mp == mp);
15406 			ip_udp_input(q, mp, ipha, ire, ill);
15407 			continue;
15408 		case IPPROTO_SCTP:
15409 			ASSERT(first_mp == mp);
15410 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15411 			    q, dst);
15412 			/* ire has been released by ip_sctp_input */
15413 			ire = NULL;
15414 			continue;
15415 		default:
15416 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15417 			continue;
15418 		}
15419 	}
15420 
15421 	if (ire != NULL)
15422 		ire_refrele(ire);
15423 
15424 	if (head != NULL)
15425 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15426 
15427 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15428 	    "ip_input_end: q %p (%S)", q, "end");
15429 #undef  rptr
15430 }
15431 
15432 /*
15433  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15434  * a chain of packets in the poll mode. The packets have gone through the
15435  * data link processing but not IP processing. For performance and latency
15436  * reasons, the squeue wants to process the chain in line instead of feeding
15437  * it back via ip_input path.
15438  *
15439  * So this is a light weight function which checks to see if the packets
15440  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15441  * but we still do the paranoid check) meant for local machine and we don't
15442  * have labels etc enabled. Packets that meet the criterion are returned to
15443  * the squeue and processed inline while the rest go via ip_input path.
15444  */
15445 /*ARGSUSED*/
15446 mblk_t *
15447 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15448     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15449 {
15450 	mblk_t 		*mp;
15451 	ipaddr_t	dst = NULL;
15452 	ipaddr_t	prev_dst;
15453 	ire_t		*ire = NULL;
15454 	ipha_t		*ipha;
15455 	uint_t		pkt_len;
15456 	ssize_t		len;
15457 	uint_t		opt_len;
15458 	queue_t		*q = ill->ill_rq;
15459 	squeue_t	*curr_sqp;
15460 	mblk_t 		*ahead = NULL;	/* Accepted head */
15461 	mblk_t		*atail = NULL;	/* Accepted tail */
15462 	uint_t		acnt = 0;	/* Accepted count */
15463 	mblk_t		*utail = NULL;	/* Unaccepted head */
15464 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15465 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15466 	ip_stack_t	*ipst = ill->ill_ipst;
15467 
15468 	*cnt = 0;
15469 
15470 	ASSERT(ill != NULL);
15471 	ASSERT(ip_ring != NULL);
15472 
15473 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15474 
15475 #define	rptr	((uchar_t *)ipha)
15476 
15477 	while (mp_chain != NULL) {
15478 		mp = mp_chain;
15479 		mp_chain = mp_chain->b_next;
15480 		mp->b_next = NULL;
15481 
15482 		/*
15483 		 * We do ire caching from one iteration to
15484 		 * another. In the event the packet chain contains
15485 		 * all packets from the same dst, this caching saves
15486 		 * an ire_cache_lookup for each of the succeeding
15487 		 * packets in a packet chain.
15488 		 */
15489 		prev_dst = dst;
15490 
15491 		ipha = (ipha_t *)mp->b_rptr;
15492 		len = mp->b_wptr - rptr;
15493 
15494 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15495 
15496 		/*
15497 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15498 		 * or doesn't have min len, reject.
15499 		 */
15500 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15501 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15502 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15503 			continue;
15504 		}
15505 
15506 		pkt_len = ntohs(ipha->ipha_length);
15507 		if (len != pkt_len) {
15508 			if (len > pkt_len) {
15509 				mp->b_wptr = rptr + pkt_len;
15510 			} else {
15511 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15512 				continue;
15513 			}
15514 		}
15515 
15516 		opt_len = ipha->ipha_version_and_hdr_length -
15517 		    IP_SIMPLE_HDR_VERSION;
15518 		dst = ipha->ipha_dst;
15519 
15520 		/* IP version bad or there are IP options */
15521 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15522 		    mp, &ipha, &dst, ipst)))
15523 			continue;
15524 
15525 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15526 		    (ipst->ips_ip_cgtp_filter &&
15527 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15528 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15529 			continue;
15530 		}
15531 
15532 		/*
15533 		 * Reuse the cached ire only if the ipha_dst of the previous
15534 		 * packet is the same as the current packet AND it is not
15535 		 * INADDR_ANY.
15536 		 */
15537 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15538 		    (ire != NULL)) {
15539 			ire_refrele(ire);
15540 			ire = NULL;
15541 		}
15542 
15543 		if (ire == NULL)
15544 			ire = ire_cache_lookup_simple(dst, ipst);
15545 
15546 		/*
15547 		 * Unless forwarding is enabled, dont call
15548 		 * ip_fast_forward(). Incoming packet is for forwarding
15549 		 */
15550 		if ((ill->ill_flags & ILLF_ROUTER) &&
15551 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15552 
15553 			DTRACE_PROBE4(ip4__physical__in__start,
15554 			    ill_t *, ill, ill_t *, NULL,
15555 			    ipha_t *, ipha, mblk_t *, mp);
15556 
15557 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15558 			    ipst->ips_ipv4firewall_physical_in,
15559 			    ill, NULL, ipha, mp, mp, 0, ipst);
15560 
15561 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15562 
15563 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15564 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15565 			    pkt_len);
15566 
15567 			if (mp != NULL)
15568 				ire = ip_fast_forward(ire, dst, ill, mp);
15569 			continue;
15570 		}
15571 
15572 		/* incoming packet is for local consumption */
15573 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15574 			goto local_accept;
15575 
15576 		/*
15577 		 * Disable ire caching for anything more complex
15578 		 * than the simple fast path case we checked for above.
15579 		 */
15580 		if (ire != NULL) {
15581 			ire_refrele(ire);
15582 			ire = NULL;
15583 		}
15584 
15585 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15586 		    ipst);
15587 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15588 		    ire->ire_stq != NULL) {
15589 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15590 			if (ire != NULL) {
15591 				ire_refrele(ire);
15592 				ire = NULL;
15593 			}
15594 			continue;
15595 		}
15596 
15597 local_accept:
15598 
15599 		if (ire->ire_rfq != q) {
15600 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15601 			if (ire != NULL) {
15602 				ire_refrele(ire);
15603 				ire = NULL;
15604 			}
15605 			continue;
15606 		}
15607 
15608 		/*
15609 		 * The event for packets being received from a 'physical'
15610 		 * interface is placed after validation of the source and/or
15611 		 * destination address as being local so that packets can be
15612 		 * redirected to loopback addresses using ipnat.
15613 		 */
15614 		DTRACE_PROBE4(ip4__physical__in__start,
15615 		    ill_t *, ill, ill_t *, NULL,
15616 		    ipha_t *, ipha, mblk_t *, mp);
15617 
15618 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15619 		    ipst->ips_ipv4firewall_physical_in,
15620 		    ill, NULL, ipha, mp, mp, 0, ipst);
15621 
15622 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15623 
15624 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15625 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15626 
15627 		if (mp != NULL &&
15628 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15629 		    0, q, ip_ring)) != NULL) {
15630 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15631 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15632 			} else {
15633 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15634 				    SQ_FILL, SQTAG_IP_INPUT);
15635 			}
15636 		}
15637 	}
15638 
15639 	if (ire != NULL)
15640 		ire_refrele(ire);
15641 
15642 	if (uhead != NULL)
15643 		ip_input(ill, ip_ring, uhead, NULL);
15644 
15645 	if (ahead != NULL) {
15646 		*last = atail;
15647 		*cnt = acnt;
15648 		return (ahead);
15649 	}
15650 
15651 	return (NULL);
15652 #undef  rptr
15653 }
15654 
15655 static void
15656 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15657     t_uscalar_t err)
15658 {
15659 	if (dl_err == DL_SYSERR) {
15660 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15661 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15662 		    ill->ill_name, dl_primstr(prim), err);
15663 		return;
15664 	}
15665 
15666 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15667 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15668 	    dl_errstr(dl_err));
15669 }
15670 
15671 /*
15672  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15673  * than DL_UNITDATA_IND messages. If we need to process this message
15674  * exclusively, we call qwriter_ip, in which case we also need to call
15675  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15676  */
15677 void
15678 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15679 {
15680 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15681 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15682 	ill_t		*ill = q->q_ptr;
15683 	t_uscalar_t	prim = dloa->dl_primitive;
15684 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15685 
15686 	ip1dbg(("ip_rput_dlpi"));
15687 
15688 	/*
15689 	 * If we received an ACK but didn't send a request for it, then it
15690 	 * can't be part of any pending operation; discard up-front.
15691 	 */
15692 	switch (prim) {
15693 	case DL_ERROR_ACK:
15694 		reqprim = dlea->dl_error_primitive;
15695 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15696 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15697 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15698 		    dlea->dl_unix_errno));
15699 		break;
15700 	case DL_OK_ACK:
15701 		reqprim = dloa->dl_correct_primitive;
15702 		break;
15703 	case DL_INFO_ACK:
15704 		reqprim = DL_INFO_REQ;
15705 		break;
15706 	case DL_BIND_ACK:
15707 		reqprim = DL_BIND_REQ;
15708 		break;
15709 	case DL_PHYS_ADDR_ACK:
15710 		reqprim = DL_PHYS_ADDR_REQ;
15711 		break;
15712 	case DL_NOTIFY_ACK:
15713 		reqprim = DL_NOTIFY_REQ;
15714 		break;
15715 	case DL_CONTROL_ACK:
15716 		reqprim = DL_CONTROL_REQ;
15717 		break;
15718 	case DL_CAPABILITY_ACK:
15719 		reqprim = DL_CAPABILITY_REQ;
15720 		break;
15721 	}
15722 
15723 	if (prim != DL_NOTIFY_IND) {
15724 		if (reqprim == DL_PRIM_INVAL ||
15725 		    !ill_dlpi_pending(ill, reqprim)) {
15726 			/* Not a DLPI message we support or expected */
15727 			freemsg(mp);
15728 			return;
15729 		}
15730 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15731 		    dl_primstr(reqprim)));
15732 	}
15733 
15734 	switch (reqprim) {
15735 	case DL_UNBIND_REQ:
15736 		/*
15737 		 * NOTE: we mark the unbind as complete even if we got a
15738 		 * DL_ERROR_ACK, since there's not much else we can do.
15739 		 */
15740 		mutex_enter(&ill->ill_lock);
15741 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15742 		cv_signal(&ill->ill_cv);
15743 		mutex_exit(&ill->ill_lock);
15744 		break;
15745 
15746 	case DL_ENABMULTI_REQ:
15747 		if (prim == DL_OK_ACK) {
15748 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15749 				ill->ill_dlpi_multicast_state = IDS_OK;
15750 		}
15751 		break;
15752 	}
15753 
15754 	/*
15755 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15756 	 * need to become writer to continue to process it.  Because an
15757 	 * exclusive operation doesn't complete until replies to all queued
15758 	 * DLPI messages have been received, we know we're in the middle of an
15759 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15760 	 *
15761 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15762 	 * Since this is on the ill stream we unconditionally bump up the
15763 	 * refcount without doing ILL_CAN_LOOKUP().
15764 	 */
15765 	ill_refhold(ill);
15766 	if (prim == DL_NOTIFY_IND)
15767 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15768 	else
15769 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15770 }
15771 
15772 /*
15773  * Handling of DLPI messages that require exclusive access to the ipsq.
15774  *
15775  * Need to do ill_pending_mp_release on ioctl completion, which could
15776  * happen here. (along with mi_copy_done)
15777  */
15778 /* ARGSUSED */
15779 static void
15780 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15781 {
15782 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15783 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15784 	int		err = 0;
15785 	ill_t		*ill;
15786 	ipif_t		*ipif = NULL;
15787 	mblk_t		*mp1 = NULL;
15788 	conn_t		*connp = NULL;
15789 	t_uscalar_t	paddrreq;
15790 	mblk_t		*mp_hw;
15791 	boolean_t	success;
15792 	boolean_t	ioctl_aborted = B_FALSE;
15793 	boolean_t	log = B_TRUE;
15794 	ip_stack_t		*ipst;
15795 
15796 	ip1dbg(("ip_rput_dlpi_writer .."));
15797 	ill = (ill_t *)q->q_ptr;
15798 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15799 	ASSERT(IAM_WRITER_ILL(ill));
15800 
15801 	ipst = ill->ill_ipst;
15802 
15803 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15804 	/*
15805 	 * The current ioctl could have been aborted by the user and a new
15806 	 * ioctl to bring up another ill could have started. We could still
15807 	 * get a response from the driver later.
15808 	 */
15809 	if (ipif != NULL && ipif->ipif_ill != ill)
15810 		ioctl_aborted = B_TRUE;
15811 
15812 	switch (dloa->dl_primitive) {
15813 	case DL_ERROR_ACK:
15814 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15815 		    dl_primstr(dlea->dl_error_primitive)));
15816 
15817 		switch (dlea->dl_error_primitive) {
15818 		case DL_DISABMULTI_REQ:
15819 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15820 			break;
15821 		case DL_PROMISCON_REQ:
15822 		case DL_PROMISCOFF_REQ:
15823 		case DL_UNBIND_REQ:
15824 		case DL_ATTACH_REQ:
15825 		case DL_INFO_REQ:
15826 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15827 			break;
15828 		case DL_NOTIFY_REQ:
15829 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15830 			log = B_FALSE;
15831 			break;
15832 		case DL_PHYS_ADDR_REQ:
15833 			/*
15834 			 * For IPv6 only, there are two additional
15835 			 * phys_addr_req's sent to the driver to get the
15836 			 * IPv6 token and lla. This allows IP to acquire
15837 			 * the hardware address format for a given interface
15838 			 * without having built in knowledge of the hardware
15839 			 * address. ill_phys_addr_pend keeps track of the last
15840 			 * DL_PAR sent so we know which response we are
15841 			 * dealing with. ill_dlpi_done will update
15842 			 * ill_phys_addr_pend when it sends the next req.
15843 			 * We don't complete the IOCTL until all three DL_PARs
15844 			 * have been attempted, so set *_len to 0 and break.
15845 			 */
15846 			paddrreq = ill->ill_phys_addr_pend;
15847 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15848 			if (paddrreq == DL_IPV6_TOKEN) {
15849 				ill->ill_token_length = 0;
15850 				log = B_FALSE;
15851 				break;
15852 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15853 				ill->ill_nd_lla_len = 0;
15854 				log = B_FALSE;
15855 				break;
15856 			}
15857 			/*
15858 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15859 			 * We presumably have an IOCTL hanging out waiting
15860 			 * for completion. Find it and complete the IOCTL
15861 			 * with the error noted.
15862 			 * However, ill_dl_phys was called on an ill queue
15863 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15864 			 * set. But the ioctl is known to be pending on ill_wq.
15865 			 */
15866 			if (!ill->ill_ifname_pending)
15867 				break;
15868 			ill->ill_ifname_pending = 0;
15869 			if (!ioctl_aborted)
15870 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15871 			if (mp1 != NULL) {
15872 				/*
15873 				 * This operation (SIOCSLIFNAME) must have
15874 				 * happened on the ill. Assert there is no conn
15875 				 */
15876 				ASSERT(connp == NULL);
15877 				q = ill->ill_wq;
15878 			}
15879 			break;
15880 		case DL_BIND_REQ:
15881 			ill_dlpi_done(ill, DL_BIND_REQ);
15882 			if (ill->ill_ifname_pending)
15883 				break;
15884 			/*
15885 			 * Something went wrong with the bind.  We presumably
15886 			 * have an IOCTL hanging out waiting for completion.
15887 			 * Find it, take down the interface that was coming
15888 			 * up, and complete the IOCTL with the error noted.
15889 			 */
15890 			if (!ioctl_aborted)
15891 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15892 			if (mp1 != NULL) {
15893 				/*
15894 				 * This might be a result of a DL_NOTE_REPLUMB
15895 				 * notification. In that case, connp is NULL.
15896 				 */
15897 				if (connp != NULL)
15898 					q = CONNP_TO_WQ(connp);
15899 
15900 				(void) ipif_down(ipif, NULL, NULL);
15901 				/* error is set below the switch */
15902 			}
15903 			break;
15904 		case DL_ENABMULTI_REQ:
15905 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15906 
15907 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15908 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15909 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15910 				ipif_t *ipif;
15911 
15912 				printf("ip: joining multicasts failed (%d)"
15913 				    " on %s - will use link layer "
15914 				    "broadcasts for multicast\n",
15915 				    dlea->dl_errno, ill->ill_name);
15916 
15917 				/*
15918 				 * Set up the multicast mapping alone.
15919 				 * writer, so ok to access ill->ill_ipif
15920 				 * without any lock.
15921 				 */
15922 				ipif = ill->ill_ipif;
15923 				mutex_enter(&ill->ill_phyint->phyint_lock);
15924 				ill->ill_phyint->phyint_flags |=
15925 				    PHYI_MULTI_BCAST;
15926 				mutex_exit(&ill->ill_phyint->phyint_lock);
15927 
15928 				if (!ill->ill_isv6) {
15929 					(void) ipif_arp_setup_multicast(ipif,
15930 					    NULL);
15931 				} else {
15932 					(void) ipif_ndp_setup_multicast(ipif,
15933 					    NULL);
15934 				}
15935 			}
15936 			freemsg(mp);	/* Don't want to pass this up */
15937 			return;
15938 		case DL_CONTROL_REQ:
15939 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15940 			    "DL_CONTROL_REQ\n"));
15941 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15942 			freemsg(mp);
15943 			return;
15944 		case DL_CAPABILITY_REQ:
15945 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15946 			    "DL_CAPABILITY REQ\n"));
15947 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15948 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15949 			ill_capability_done(ill);
15950 			freemsg(mp);
15951 			return;
15952 		}
15953 		/*
15954 		 * Note the error for IOCTL completion (mp1 is set when
15955 		 * ready to complete ioctl). If ill_ifname_pending_err is
15956 		 * set, an error occured during plumbing (ill_ifname_pending),
15957 		 * so we want to report that error.
15958 		 *
15959 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15960 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15961 		 * expected to get errack'd if the driver doesn't support
15962 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15963 		 * if these error conditions are encountered.
15964 		 */
15965 		if (mp1 != NULL) {
15966 			if (ill->ill_ifname_pending_err != 0)  {
15967 				err = ill->ill_ifname_pending_err;
15968 				ill->ill_ifname_pending_err = 0;
15969 			} else {
15970 				err = dlea->dl_unix_errno ?
15971 				    dlea->dl_unix_errno : ENXIO;
15972 			}
15973 		/*
15974 		 * If we're plumbing an interface and an error hasn't already
15975 		 * been saved, set ill_ifname_pending_err to the error passed
15976 		 * up. Ignore the error if log is B_FALSE (see comment above).
15977 		 */
15978 		} else if (log && ill->ill_ifname_pending &&
15979 		    ill->ill_ifname_pending_err == 0) {
15980 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15981 			    dlea->dl_unix_errno : ENXIO;
15982 		}
15983 
15984 		if (log)
15985 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15986 			    dlea->dl_errno, dlea->dl_unix_errno);
15987 		break;
15988 	case DL_CAPABILITY_ACK:
15989 		ill_capability_ack(ill, mp);
15990 		/*
15991 		 * The message has been handed off to ill_capability_ack
15992 		 * and must not be freed below
15993 		 */
15994 		mp = NULL;
15995 		break;
15996 
15997 	case DL_CONTROL_ACK:
15998 		/* We treat all of these as "fire and forget" */
15999 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16000 		break;
16001 	case DL_INFO_ACK:
16002 		/* Call a routine to handle this one. */
16003 		ill_dlpi_done(ill, DL_INFO_REQ);
16004 		ip_ll_subnet_defaults(ill, mp);
16005 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16006 		return;
16007 	case DL_BIND_ACK:
16008 		/*
16009 		 * We should have an IOCTL waiting on this unless
16010 		 * sent by ill_dl_phys, in which case just return
16011 		 */
16012 		ill_dlpi_done(ill, DL_BIND_REQ);
16013 		if (ill->ill_ifname_pending)
16014 			break;
16015 
16016 		if (!ioctl_aborted)
16017 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16018 		if (mp1 == NULL)
16019 			break;
16020 		/*
16021 		 * mp1 was added by ill_dl_up(). if that is a result of
16022 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16023 		 */
16024 		if (connp != NULL)
16025 			q = CONNP_TO_WQ(connp);
16026 
16027 		/*
16028 		 * We are exclusive. So nothing can change even after
16029 		 * we get the pending mp. If need be we can put it back
16030 		 * and restart, as in calling ipif_arp_up()  below.
16031 		 */
16032 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16033 
16034 		mutex_enter(&ill->ill_lock);
16035 		ill->ill_dl_up = 1;
16036 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16037 		mutex_exit(&ill->ill_lock);
16038 
16039 		/*
16040 		 * Now bring up the resolver; when that is complete, we'll
16041 		 * create IREs.  Note that we intentionally mirror what
16042 		 * ipif_up() would have done, because we got here by way of
16043 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16044 		 */
16045 		if (ill->ill_isv6) {
16046 			if (ill->ill_flags & ILLF_XRESOLV) {
16047 				if (connp != NULL)
16048 					mutex_enter(&connp->conn_lock);
16049 				mutex_enter(&ill->ill_lock);
16050 				success = ipsq_pending_mp_add(connp, ipif, q,
16051 				    mp1, 0);
16052 				mutex_exit(&ill->ill_lock);
16053 				if (connp != NULL)
16054 					mutex_exit(&connp->conn_lock);
16055 				if (success) {
16056 					err = ipif_resolver_up(ipif,
16057 					    Res_act_initial);
16058 					if (err == EINPROGRESS) {
16059 						freemsg(mp);
16060 						return;
16061 					}
16062 					ASSERT(err != 0);
16063 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16064 					ASSERT(mp1 != NULL);
16065 				} else {
16066 					/* conn has started closing */
16067 					err = EINTR;
16068 				}
16069 			} else { /* Non XRESOLV interface */
16070 				(void) ipif_resolver_up(ipif, Res_act_initial);
16071 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16072 					err = ipif_up_done_v6(ipif);
16073 			}
16074 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16075 			/*
16076 			 * ARP and other v4 external resolvers.
16077 			 * Leave the pending mblk intact so that
16078 			 * the ioctl completes in ip_rput().
16079 			 */
16080 			if (connp != NULL)
16081 				mutex_enter(&connp->conn_lock);
16082 			mutex_enter(&ill->ill_lock);
16083 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16084 			mutex_exit(&ill->ill_lock);
16085 			if (connp != NULL)
16086 				mutex_exit(&connp->conn_lock);
16087 			if (success) {
16088 				err = ipif_resolver_up(ipif, Res_act_initial);
16089 				if (err == EINPROGRESS) {
16090 					freemsg(mp);
16091 					return;
16092 				}
16093 				ASSERT(err != 0);
16094 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16095 			} else {
16096 				/* The conn has started closing */
16097 				err = EINTR;
16098 			}
16099 		} else {
16100 			/*
16101 			 * This one is complete. Reply to pending ioctl.
16102 			 */
16103 			(void) ipif_resolver_up(ipif, Res_act_initial);
16104 			err = ipif_up_done(ipif);
16105 		}
16106 
16107 		if ((err == 0) && (ill->ill_up_ipifs)) {
16108 			err = ill_up_ipifs(ill, q, mp1);
16109 			if (err == EINPROGRESS) {
16110 				freemsg(mp);
16111 				return;
16112 			}
16113 		}
16114 
16115 		/*
16116 		 * If we have a moved ipif to bring up, and everything has
16117 		 * succeeded to this point, bring it up on the IPMP ill.
16118 		 * Otherwise, leave it down -- the admin can try to bring it
16119 		 * up by hand if need be.
16120 		 */
16121 		if (ill->ill_move_ipif != NULL) {
16122 			if (err != 0) {
16123 				ill->ill_move_ipif = NULL;
16124 			} else {
16125 				ipif = ill->ill_move_ipif;
16126 				ill->ill_move_ipif = NULL;
16127 				err = ipif_up(ipif, q, mp1);
16128 				if (err == EINPROGRESS) {
16129 					freemsg(mp);
16130 					return;
16131 				}
16132 			}
16133 		}
16134 		break;
16135 
16136 	case DL_NOTIFY_IND: {
16137 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16138 		ire_t *ire;
16139 		uint_t orig_mtu;
16140 		boolean_t need_ire_walk_v4 = B_FALSE;
16141 		boolean_t need_ire_walk_v6 = B_FALSE;
16142 
16143 		switch (notify->dl_notification) {
16144 		case DL_NOTE_PHYS_ADDR:
16145 			err = ill_set_phys_addr(ill, mp);
16146 			break;
16147 
16148 		case DL_NOTE_REPLUMB:
16149 			/*
16150 			 * Directly return after calling ill_replumb().
16151 			 * Note that we should not free mp as it is reused
16152 			 * in the ill_replumb() function.
16153 			 */
16154 			err = ill_replumb(ill, mp);
16155 			return;
16156 
16157 		case DL_NOTE_FASTPATH_FLUSH:
16158 			ill_fastpath_flush(ill);
16159 			break;
16160 
16161 		case DL_NOTE_SDU_SIZE:
16162 			/*
16163 			 * Change the MTU size of the interface, of all
16164 			 * attached ipif's, and of all relevant ire's.  The
16165 			 * new value's a uint32_t at notify->dl_data.
16166 			 * Mtu change Vs. new ire creation - protocol below.
16167 			 *
16168 			 * a Mark the ipif as IPIF_CHANGING.
16169 			 * b Set the new mtu in the ipif.
16170 			 * c Change the ire_max_frag on all affected ires
16171 			 * d Unmark the IPIF_CHANGING
16172 			 *
16173 			 * To see how the protocol works, assume an interface
16174 			 * route is also being added simultaneously by
16175 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16176 			 * the ire. If the ire is created before step a,
16177 			 * it will be cleaned up by step c. If the ire is
16178 			 * created after step d, it will see the new value of
16179 			 * ipif_mtu. Any attempt to create the ire between
16180 			 * steps a to d will fail because of the IPIF_CHANGING
16181 			 * flag. Note that ire_create() is passed a pointer to
16182 			 * the ipif_mtu, and not the value. During ire_add
16183 			 * under the bucket lock, the ire_max_frag of the
16184 			 * new ire being created is set from the ipif/ire from
16185 			 * which it is being derived.
16186 			 */
16187 			mutex_enter(&ill->ill_lock);
16188 
16189 			orig_mtu = ill->ill_max_mtu;
16190 			ill->ill_max_frag = (uint_t)notify->dl_data;
16191 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16192 
16193 			/*
16194 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16195 			 * clamp ill_max_mtu at it.
16196 			 */
16197 			if (ill->ill_user_mtu != 0 &&
16198 			    ill->ill_user_mtu < ill->ill_max_mtu)
16199 				ill->ill_max_mtu = ill->ill_user_mtu;
16200 
16201 			/*
16202 			 * If the MTU is unchanged, we're done.
16203 			 */
16204 			if (orig_mtu == ill->ill_max_mtu) {
16205 				mutex_exit(&ill->ill_lock);
16206 				break;
16207 			}
16208 
16209 			if (ill->ill_isv6) {
16210 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16211 					ill->ill_max_mtu = IPV6_MIN_MTU;
16212 			} else {
16213 				if (ill->ill_max_mtu < IP_MIN_MTU)
16214 					ill->ill_max_mtu = IP_MIN_MTU;
16215 			}
16216 			for (ipif = ill->ill_ipif; ipif != NULL;
16217 			    ipif = ipif->ipif_next) {
16218 				/*
16219 				 * Don't override the mtu if the user
16220 				 * has explicitly set it.
16221 				 */
16222 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16223 					continue;
16224 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16225 				if (ipif->ipif_isv6)
16226 					ire = ipif_to_ire_v6(ipif);
16227 				else
16228 					ire = ipif_to_ire(ipif);
16229 				if (ire != NULL) {
16230 					ire->ire_max_frag = ipif->ipif_mtu;
16231 					ire_refrele(ire);
16232 				}
16233 				if (ipif->ipif_flags & IPIF_UP) {
16234 					if (ill->ill_isv6)
16235 						need_ire_walk_v6 = B_TRUE;
16236 					else
16237 						need_ire_walk_v4 = B_TRUE;
16238 				}
16239 			}
16240 			mutex_exit(&ill->ill_lock);
16241 			if (need_ire_walk_v4)
16242 				ire_walk_v4(ill_mtu_change, (char *)ill,
16243 				    ALL_ZONES, ipst);
16244 			if (need_ire_walk_v6)
16245 				ire_walk_v6(ill_mtu_change, (char *)ill,
16246 				    ALL_ZONES, ipst);
16247 
16248 			/*
16249 			 * Refresh IPMP meta-interface MTU if necessary.
16250 			 */
16251 			if (IS_UNDER_IPMP(ill))
16252 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16253 			break;
16254 
16255 		case DL_NOTE_LINK_UP:
16256 		case DL_NOTE_LINK_DOWN: {
16257 			/*
16258 			 * We are writer. ill / phyint / ipsq assocs stable.
16259 			 * The RUNNING flag reflects the state of the link.
16260 			 */
16261 			phyint_t *phyint = ill->ill_phyint;
16262 			uint64_t new_phyint_flags;
16263 			boolean_t changed = B_FALSE;
16264 			boolean_t went_up;
16265 
16266 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16267 			mutex_enter(&phyint->phyint_lock);
16268 
16269 			new_phyint_flags = went_up ?
16270 			    phyint->phyint_flags | PHYI_RUNNING :
16271 			    phyint->phyint_flags & ~PHYI_RUNNING;
16272 
16273 			if (IS_IPMP(ill)) {
16274 				new_phyint_flags = went_up ?
16275 				    new_phyint_flags & ~PHYI_FAILED :
16276 				    new_phyint_flags | PHYI_FAILED;
16277 			}
16278 
16279 			if (new_phyint_flags != phyint->phyint_flags) {
16280 				phyint->phyint_flags = new_phyint_flags;
16281 				changed = B_TRUE;
16282 			}
16283 			mutex_exit(&phyint->phyint_lock);
16284 			/*
16285 			 * ill_restart_dad handles the DAD restart and routing
16286 			 * socket notification logic.
16287 			 */
16288 			if (changed) {
16289 				ill_restart_dad(phyint->phyint_illv4, went_up);
16290 				ill_restart_dad(phyint->phyint_illv6, went_up);
16291 			}
16292 			break;
16293 		}
16294 		case DL_NOTE_PROMISC_ON_PHYS:
16295 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16296 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16297 			mutex_enter(&ill->ill_lock);
16298 			ill->ill_promisc_on_phys = B_TRUE;
16299 			mutex_exit(&ill->ill_lock);
16300 			break;
16301 		case DL_NOTE_PROMISC_OFF_PHYS:
16302 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16303 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16304 			mutex_enter(&ill->ill_lock);
16305 			ill->ill_promisc_on_phys = B_FALSE;
16306 			mutex_exit(&ill->ill_lock);
16307 			break;
16308 		case DL_NOTE_CAPAB_RENEG:
16309 			/*
16310 			 * Something changed on the driver side.
16311 			 * It wants us to renegotiate the capabilities
16312 			 * on this ill. One possible cause is the aggregation
16313 			 * interface under us where a port got added or
16314 			 * went away.
16315 			 *
16316 			 * If the capability negotiation is already done
16317 			 * or is in progress, reset the capabilities and
16318 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16319 			 * so that when the ack comes back, we can start
16320 			 * the renegotiation process.
16321 			 *
16322 			 * Note that if ill_capab_reneg is already B_TRUE
16323 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16324 			 * the capability resetting request has been sent
16325 			 * and the renegotiation has not been started yet;
16326 			 * nothing needs to be done in this case.
16327 			 */
16328 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16329 			ill_capability_reset(ill, B_TRUE);
16330 			ipsq_current_finish(ipsq);
16331 			break;
16332 		default:
16333 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16334 			    "type 0x%x for DL_NOTIFY_IND\n",
16335 			    notify->dl_notification));
16336 			break;
16337 		}
16338 
16339 		/*
16340 		 * As this is an asynchronous operation, we
16341 		 * should not call ill_dlpi_done
16342 		 */
16343 		break;
16344 	}
16345 	case DL_NOTIFY_ACK: {
16346 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16347 
16348 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16349 			ill->ill_note_link = 1;
16350 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16351 		break;
16352 	}
16353 	case DL_PHYS_ADDR_ACK: {
16354 		/*
16355 		 * As part of plumbing the interface via SIOCSLIFNAME,
16356 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16357 		 * whose answers we receive here.  As each answer is received,
16358 		 * we call ill_dlpi_done() to dispatch the next request as
16359 		 * we're processing the current one.  Once all answers have
16360 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16361 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16362 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16363 		 * available, but we know the ioctl is pending on ill_wq.)
16364 		 */
16365 		uint_t	paddrlen, paddroff;
16366 
16367 		paddrreq = ill->ill_phys_addr_pend;
16368 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16369 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16370 
16371 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16372 		if (paddrreq == DL_IPV6_TOKEN) {
16373 			/*
16374 			 * bcopy to low-order bits of ill_token
16375 			 *
16376 			 * XXX Temporary hack - currently, all known tokens
16377 			 * are 64 bits, so I'll cheat for the moment.
16378 			 */
16379 			bcopy(mp->b_rptr + paddroff,
16380 			    &ill->ill_token.s6_addr32[2], paddrlen);
16381 			ill->ill_token_length = paddrlen;
16382 			break;
16383 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16384 			ASSERT(ill->ill_nd_lla_mp == NULL);
16385 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16386 			mp = NULL;
16387 			break;
16388 		}
16389 
16390 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16391 		ASSERT(ill->ill_phys_addr_mp == NULL);
16392 		if (!ill->ill_ifname_pending)
16393 			break;
16394 		ill->ill_ifname_pending = 0;
16395 		if (!ioctl_aborted)
16396 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16397 		if (mp1 != NULL) {
16398 			ASSERT(connp == NULL);
16399 			q = ill->ill_wq;
16400 		}
16401 		/*
16402 		 * If any error acks received during the plumbing sequence,
16403 		 * ill_ifname_pending_err will be set. Break out and send up
16404 		 * the error to the pending ioctl.
16405 		 */
16406 		if (ill->ill_ifname_pending_err != 0) {
16407 			err = ill->ill_ifname_pending_err;
16408 			ill->ill_ifname_pending_err = 0;
16409 			break;
16410 		}
16411 
16412 		ill->ill_phys_addr_mp = mp;
16413 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16414 		mp = NULL;
16415 
16416 		/*
16417 		 * If paddrlen is zero, the DLPI provider doesn't support
16418 		 * physical addresses.  The other two tests were historical
16419 		 * workarounds for bugs in our former PPP implementation, but
16420 		 * now other things have grown dependencies on them -- e.g.,
16421 		 * the tun module specifies a dl_addr_length of zero in its
16422 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16423 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16424 		 * but only after careful testing ensures that all dependent
16425 		 * broken DLPI providers have been fixed.
16426 		 */
16427 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16428 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16429 			ill->ill_phys_addr = NULL;
16430 		} else if (paddrlen != ill->ill_phys_addr_length) {
16431 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16432 			    paddrlen, ill->ill_phys_addr_length));
16433 			err = EINVAL;
16434 			break;
16435 		}
16436 
16437 		if (ill->ill_nd_lla_mp == NULL) {
16438 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16439 				err = ENOMEM;
16440 				break;
16441 			}
16442 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16443 		}
16444 
16445 		/*
16446 		 * Set the interface token.  If the zeroth interface address
16447 		 * is unspecified, then set it to the link local address.
16448 		 */
16449 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16450 			(void) ill_setdefaulttoken(ill);
16451 
16452 		ASSERT(ill->ill_ipif->ipif_id == 0);
16453 		if (ipif != NULL &&
16454 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16455 			(void) ipif_setlinklocal(ipif);
16456 		}
16457 		break;
16458 	}
16459 	case DL_OK_ACK:
16460 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16461 		    dl_primstr((int)dloa->dl_correct_primitive),
16462 		    dloa->dl_correct_primitive));
16463 		switch (dloa->dl_correct_primitive) {
16464 		case DL_ENABMULTI_REQ:
16465 		case DL_DISABMULTI_REQ:
16466 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16467 			break;
16468 		case DL_PROMISCON_REQ:
16469 		case DL_PROMISCOFF_REQ:
16470 		case DL_UNBIND_REQ:
16471 		case DL_ATTACH_REQ:
16472 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16473 			break;
16474 		}
16475 		break;
16476 	default:
16477 		break;
16478 	}
16479 
16480 	freemsg(mp);
16481 	if (mp1 == NULL)
16482 		return;
16483 
16484 	/*
16485 	 * The operation must complete without EINPROGRESS since
16486 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16487 	 * the operation will be stuck forever inside the IPSQ.
16488 	 */
16489 	ASSERT(err != EINPROGRESS);
16490 
16491 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16492 	case 0:
16493 		ipsq_current_finish(ipsq);
16494 		break;
16495 
16496 	case SIOCSLIFNAME:
16497 	case IF_UNITSEL: {
16498 		ill_t *ill_other = ILL_OTHER(ill);
16499 
16500 		/*
16501 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16502 		 * ill has a peer which is in an IPMP group, then place ill
16503 		 * into the same group.  One catch: although ifconfig plumbs
16504 		 * the appropriate IPMP meta-interface prior to plumbing this
16505 		 * ill, it is possible for multiple ifconfig applications to
16506 		 * race (or for another application to adjust plumbing), in
16507 		 * which case the IPMP meta-interface we need will be missing.
16508 		 * If so, kick the phyint out of the group.
16509 		 */
16510 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16511 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16512 			ipmp_illgrp_t	*illg;
16513 
16514 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16515 			if (illg == NULL)
16516 				ipmp_phyint_leave_grp(ill->ill_phyint);
16517 			else
16518 				ipmp_ill_join_illgrp(ill, illg);
16519 		}
16520 
16521 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16522 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16523 		else
16524 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16525 		break;
16526 	}
16527 	case SIOCLIFADDIF:
16528 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16529 		break;
16530 
16531 	default:
16532 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16533 		break;
16534 	}
16535 }
16536 
16537 /*
16538  * ip_rput_other is called by ip_rput to handle messages modifying the global
16539  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16540  */
16541 /* ARGSUSED */
16542 void
16543 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16544 {
16545 	ill_t		*ill = q->q_ptr;
16546 	struct iocblk	*iocp;
16547 	mblk_t		*mp1;
16548 	conn_t		*connp = NULL;
16549 
16550 	ip1dbg(("ip_rput_other "));
16551 	if (ipsq != NULL) {
16552 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16553 		ASSERT(ipsq->ipsq_xop ==
16554 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16555 	}
16556 
16557 	switch (mp->b_datap->db_type) {
16558 	case M_ERROR:
16559 	case M_HANGUP:
16560 		/*
16561 		 * The device has a problem.  We force the ILL down.  It can
16562 		 * be brought up again manually using SIOCSIFFLAGS (via
16563 		 * ifconfig or equivalent).
16564 		 */
16565 		ASSERT(ipsq != NULL);
16566 		if (mp->b_rptr < mp->b_wptr)
16567 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16568 		if (ill->ill_error == 0)
16569 			ill->ill_error = ENXIO;
16570 		if (!ill_down_start(q, mp))
16571 			return;
16572 		ipif_all_down_tail(ipsq, q, mp, NULL);
16573 		break;
16574 	case M_IOCACK:
16575 		iocp = (struct iocblk *)mp->b_rptr;
16576 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16577 		switch (iocp->ioc_cmd) {
16578 		case SIOCSTUNPARAM:
16579 		case OSIOCSTUNPARAM:
16580 			ASSERT(ipsq != NULL);
16581 			/*
16582 			 * Finish socket ioctl passed through to tun.
16583 			 * We should have an IOCTL waiting on this.
16584 			 */
16585 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16586 			if (ill->ill_isv6) {
16587 				struct iftun_req *ta;
16588 
16589 				/*
16590 				 * if a source or destination is
16591 				 * being set, try and set the link
16592 				 * local address for the tunnel
16593 				 */
16594 				ta = (struct iftun_req *)mp->b_cont->
16595 				    b_cont->b_rptr;
16596 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16597 					ipif_set_tun_llink(ill, ta);
16598 				}
16599 
16600 			}
16601 			if (mp1 != NULL) {
16602 				/*
16603 				 * Now copy back the b_next/b_prev used by
16604 				 * mi code for the mi_copy* functions.
16605 				 * See ip_sioctl_tunparam() for the reason.
16606 				 * Also protect against missing b_cont.
16607 				 */
16608 				if (mp->b_cont != NULL) {
16609 					mp->b_cont->b_next =
16610 					    mp1->b_cont->b_next;
16611 					mp->b_cont->b_prev =
16612 					    mp1->b_cont->b_prev;
16613 				}
16614 				inet_freemsg(mp1);
16615 				ASSERT(connp != NULL);
16616 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16617 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16618 			} else {
16619 				ASSERT(connp == NULL);
16620 				putnext(q, mp);
16621 			}
16622 			break;
16623 		case SIOCGTUNPARAM:
16624 		case OSIOCGTUNPARAM:
16625 			/*
16626 			 * This is really M_IOCDATA from the tunnel driver.
16627 			 * convert back and complete the ioctl.
16628 			 * We should have an IOCTL waiting on this.
16629 			 */
16630 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16631 			if (mp1) {
16632 				/*
16633 				 * Now copy back the b_next/b_prev used by
16634 				 * mi code for the mi_copy* functions.
16635 				 * See ip_sioctl_tunparam() for the reason.
16636 				 * Also protect against missing b_cont.
16637 				 */
16638 				if (mp->b_cont != NULL) {
16639 					mp->b_cont->b_next =
16640 					    mp1->b_cont->b_next;
16641 					mp->b_cont->b_prev =
16642 					    mp1->b_cont->b_prev;
16643 				}
16644 				inet_freemsg(mp1);
16645 				if (iocp->ioc_error == 0)
16646 					mp->b_datap->db_type = M_IOCDATA;
16647 				ASSERT(connp != NULL);
16648 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16649 				    iocp->ioc_error, COPYOUT, NULL);
16650 			} else {
16651 				ASSERT(connp == NULL);
16652 				putnext(q, mp);
16653 			}
16654 			break;
16655 		default:
16656 			break;
16657 		}
16658 		break;
16659 	case M_IOCNAK:
16660 		iocp = (struct iocblk *)mp->b_rptr;
16661 
16662 		switch (iocp->ioc_cmd) {
16663 			int mode;
16664 
16665 		case DL_IOC_HDR_INFO:
16666 			/*
16667 			 * If this was the first attempt, turn off the
16668 			 * fastpath probing.
16669 			 */
16670 			mutex_enter(&ill->ill_lock);
16671 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16672 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16673 				mutex_exit(&ill->ill_lock);
16674 				ill_fastpath_nack(ill);
16675 				ip1dbg(("ip_rput: DLPI fastpath off on "
16676 				    "interface %s\n",
16677 				    ill->ill_name));
16678 			} else {
16679 				mutex_exit(&ill->ill_lock);
16680 			}
16681 			freemsg(mp);
16682 			break;
16683 			case SIOCSTUNPARAM:
16684 		case OSIOCSTUNPARAM:
16685 			ASSERT(ipsq != NULL);
16686 			/*
16687 			 * Finish socket ioctl passed through to tun
16688 			 * We should have an IOCTL waiting on this.
16689 			 */
16690 			/* FALLTHRU */
16691 		case SIOCGTUNPARAM:
16692 		case OSIOCGTUNPARAM:
16693 			/*
16694 			 * This is really M_IOCDATA from the tunnel driver.
16695 			 * convert back and complete the ioctl.
16696 			 * We should have an IOCTL waiting on this.
16697 			 */
16698 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16699 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16700 				mp1 = ill_pending_mp_get(ill, &connp,
16701 				    iocp->ioc_id);
16702 				mode = COPYOUT;
16703 				ipsq = NULL;
16704 			} else {
16705 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16706 				mode = NO_COPYOUT;
16707 			}
16708 			if (mp1 != NULL) {
16709 				/*
16710 				 * Now copy back the b_next/b_prev used by
16711 				 * mi code for the mi_copy* functions.
16712 				 * See ip_sioctl_tunparam() for the reason.
16713 				 * Also protect against missing b_cont.
16714 				 */
16715 				if (mp->b_cont != NULL) {
16716 					mp->b_cont->b_next =
16717 					    mp1->b_cont->b_next;
16718 					mp->b_cont->b_prev =
16719 					    mp1->b_cont->b_prev;
16720 				}
16721 				inet_freemsg(mp1);
16722 				if (iocp->ioc_error == 0)
16723 					iocp->ioc_error = EINVAL;
16724 				ASSERT(connp != NULL);
16725 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16726 				    iocp->ioc_error, mode, ipsq);
16727 			} else {
16728 				ASSERT(connp == NULL);
16729 				putnext(q, mp);
16730 			}
16731 			break;
16732 		default:
16733 			break;
16734 		}
16735 	default:
16736 		break;
16737 	}
16738 }
16739 
16740 /*
16741  * NOTE : This function does not ire_refrele the ire argument passed in.
16742  *
16743  * IPQoS notes
16744  * IP policy is invoked twice for a forwarded packet, once on the read side
16745  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16746  * enabled. An additional parameter, in_ill, has been added for this purpose.
16747  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16748  * because ip_mroute drops this information.
16749  *
16750  */
16751 void
16752 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16753 {
16754 	uint32_t	old_pkt_len;
16755 	uint32_t	pkt_len;
16756 	queue_t	*q;
16757 	uint32_t	sum;
16758 #define	rptr	((uchar_t *)ipha)
16759 	uint32_t	max_frag;
16760 	uint32_t	ill_index;
16761 	ill_t		*out_ill;
16762 	mib2_ipIfStatsEntry_t *mibptr;
16763 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16764 
16765 	/* Get the ill_index of the incoming ILL */
16766 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16767 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16768 
16769 	/* Initiate Read side IPPF processing */
16770 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16771 		ip_process(IPP_FWD_IN, &mp, ill_index);
16772 		if (mp == NULL) {
16773 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16774 			    "during IPPF processing\n"));
16775 			return;
16776 		}
16777 	}
16778 
16779 	/* Adjust the checksum to reflect the ttl decrement. */
16780 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16781 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16782 
16783 	if (ipha->ipha_ttl-- <= 1) {
16784 		if (ip_csum_hdr(ipha)) {
16785 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16786 			goto drop_pkt;
16787 		}
16788 		/*
16789 		 * Note: ire_stq this will be NULL for multicast
16790 		 * datagrams using the long path through arp (the IRE
16791 		 * is not an IRE_CACHE). This should not cause
16792 		 * problems since we don't generate ICMP errors for
16793 		 * multicast packets.
16794 		 */
16795 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16796 		q = ire->ire_stq;
16797 		if (q != NULL) {
16798 			/* Sent by forwarding path, and router is global zone */
16799 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16800 			    GLOBAL_ZONEID, ipst);
16801 		} else
16802 			freemsg(mp);
16803 		return;
16804 	}
16805 
16806 	/*
16807 	 * Don't forward if the interface is down
16808 	 */
16809 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16810 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16811 		ip2dbg(("ip_rput_forward:interface is down\n"));
16812 		goto drop_pkt;
16813 	}
16814 
16815 	/* Get the ill_index of the outgoing ILL */
16816 	out_ill = ire_to_ill(ire);
16817 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16818 
16819 	DTRACE_PROBE4(ip4__forwarding__start,
16820 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16821 
16822 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16823 	    ipst->ips_ipv4firewall_forwarding,
16824 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16825 
16826 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16827 
16828 	if (mp == NULL)
16829 		return;
16830 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16831 
16832 	if (is_system_labeled()) {
16833 		mblk_t *mp1;
16834 
16835 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16836 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16837 			goto drop_pkt;
16838 		}
16839 		/* Size may have changed */
16840 		mp = mp1;
16841 		ipha = (ipha_t *)mp->b_rptr;
16842 		pkt_len = ntohs(ipha->ipha_length);
16843 	}
16844 
16845 	/* Check if there are options to update */
16846 	if (!IS_SIMPLE_IPH(ipha)) {
16847 		if (ip_csum_hdr(ipha)) {
16848 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16849 			goto drop_pkt;
16850 		}
16851 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16852 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16853 			return;
16854 		}
16855 
16856 		ipha->ipha_hdr_checksum = 0;
16857 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16858 	}
16859 	max_frag = ire->ire_max_frag;
16860 	if (pkt_len > max_frag) {
16861 		/*
16862 		 * It needs fragging on its way out.  We haven't
16863 		 * verified the header checksum yet.  Since we
16864 		 * are going to put a surely good checksum in the
16865 		 * outgoing header, we have to make sure that it
16866 		 * was good coming in.
16867 		 */
16868 		if (ip_csum_hdr(ipha)) {
16869 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16870 			goto drop_pkt;
16871 		}
16872 		/* Initiate Write side IPPF processing */
16873 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16874 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16875 			if (mp == NULL) {
16876 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16877 				    " during IPPF processing\n"));
16878 				return;
16879 			}
16880 		}
16881 		/*
16882 		 * Handle labeled packet resizing.
16883 		 *
16884 		 * If we have added a label, inform ip_wput_frag() of its
16885 		 * effect on the MTU for ICMP messages.
16886 		 */
16887 		if (pkt_len > old_pkt_len) {
16888 			uint32_t secopt_size;
16889 
16890 			secopt_size = pkt_len - old_pkt_len;
16891 			if (secopt_size < max_frag)
16892 				max_frag -= secopt_size;
16893 		}
16894 
16895 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16896 		    GLOBAL_ZONEID, ipst, NULL);
16897 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16898 		return;
16899 	}
16900 
16901 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16902 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16903 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16904 	    ipst->ips_ipv4firewall_physical_out,
16905 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16906 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16907 	if (mp == NULL)
16908 		return;
16909 
16910 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16911 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16912 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16913 	/* ip_xmit_v4 always consumes the packet */
16914 	return;
16915 
16916 drop_pkt:;
16917 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16918 	freemsg(mp);
16919 #undef	rptr
16920 }
16921 
16922 void
16923 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16924 {
16925 	ire_t	*ire;
16926 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16927 
16928 	ASSERT(!ipif->ipif_isv6);
16929 	/*
16930 	 * Find an IRE which matches the destination and the outgoing
16931 	 * queue in the cache table. All we need is an IRE_CACHE which
16932 	 * is pointing at ipif->ipif_ill.
16933 	 */
16934 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16935 		dst = ipif->ipif_pp_dst_addr;
16936 
16937 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16938 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16939 	if (ire == NULL) {
16940 		/*
16941 		 * Mark this packet to make it be delivered to
16942 		 * ip_rput_forward after the new ire has been
16943 		 * created.
16944 		 */
16945 		mp->b_prev = NULL;
16946 		mp->b_next = mp;
16947 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16948 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16949 	} else {
16950 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16951 		IRE_REFRELE(ire);
16952 	}
16953 }
16954 
16955 /* Update any source route, record route or timestamp options */
16956 static int
16957 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16958 {
16959 	ipoptp_t	opts;
16960 	uchar_t		*opt;
16961 	uint8_t		optval;
16962 	uint8_t		optlen;
16963 	ipaddr_t	dst;
16964 	uint32_t	ts;
16965 	ire_t		*dst_ire = NULL;
16966 	ire_t		*tmp_ire = NULL;
16967 	timestruc_t	now;
16968 
16969 	ip2dbg(("ip_rput_forward_options\n"));
16970 	dst = ipha->ipha_dst;
16971 	for (optval = ipoptp_first(&opts, ipha);
16972 	    optval != IPOPT_EOL;
16973 	    optval = ipoptp_next(&opts)) {
16974 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16975 		opt = opts.ipoptp_cur;
16976 		optlen = opts.ipoptp_len;
16977 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16978 		    optval, opts.ipoptp_len));
16979 		switch (optval) {
16980 			uint32_t off;
16981 		case IPOPT_SSRR:
16982 		case IPOPT_LSRR:
16983 			/* Check if adminstratively disabled */
16984 			if (!ipst->ips_ip_forward_src_routed) {
16985 				if (ire->ire_stq != NULL) {
16986 					/*
16987 					 * Sent by forwarding path, and router
16988 					 * is global zone
16989 					 */
16990 					icmp_unreachable(ire->ire_stq, mp,
16991 					    ICMP_SOURCE_ROUTE_FAILED,
16992 					    GLOBAL_ZONEID, ipst);
16993 				} else {
16994 					ip0dbg(("ip_rput_forward_options: "
16995 					    "unable to send unreach\n"));
16996 					freemsg(mp);
16997 				}
16998 				return (-1);
16999 			}
17000 
17001 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17002 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17003 			if (dst_ire == NULL) {
17004 				/*
17005 				 * Must be partial since ip_rput_options
17006 				 * checked for strict.
17007 				 */
17008 				break;
17009 			}
17010 			off = opt[IPOPT_OFFSET];
17011 			off--;
17012 		redo_srr:
17013 			if (optlen < IP_ADDR_LEN ||
17014 			    off > optlen - IP_ADDR_LEN) {
17015 				/* End of source route */
17016 				ip1dbg((
17017 				    "ip_rput_forward_options: end of SR\n"));
17018 				ire_refrele(dst_ire);
17019 				break;
17020 			}
17021 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17022 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17023 			    IP_ADDR_LEN);
17024 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17025 			    ntohl(dst)));
17026 
17027 			/*
17028 			 * Check if our address is present more than
17029 			 * once as consecutive hops in source route.
17030 			 */
17031 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17032 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17033 			if (tmp_ire != NULL) {
17034 				ire_refrele(tmp_ire);
17035 				off += IP_ADDR_LEN;
17036 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17037 				goto redo_srr;
17038 			}
17039 			ipha->ipha_dst = dst;
17040 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17041 			ire_refrele(dst_ire);
17042 			break;
17043 		case IPOPT_RR:
17044 			off = opt[IPOPT_OFFSET];
17045 			off--;
17046 			if (optlen < IP_ADDR_LEN ||
17047 			    off > optlen - IP_ADDR_LEN) {
17048 				/* No more room - ignore */
17049 				ip1dbg((
17050 				    "ip_rput_forward_options: end of RR\n"));
17051 				break;
17052 			}
17053 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17054 			    IP_ADDR_LEN);
17055 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17056 			break;
17057 		case IPOPT_TS:
17058 			/* Insert timestamp if there is room */
17059 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17060 			case IPOPT_TS_TSONLY:
17061 				off = IPOPT_TS_TIMELEN;
17062 				break;
17063 			case IPOPT_TS_PRESPEC:
17064 			case IPOPT_TS_PRESPEC_RFC791:
17065 				/* Verify that the address matched */
17066 				off = opt[IPOPT_OFFSET] - 1;
17067 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17068 				dst_ire = ire_ctable_lookup(dst, 0,
17069 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17070 				    MATCH_IRE_TYPE, ipst);
17071 				if (dst_ire == NULL) {
17072 					/* Not for us */
17073 					break;
17074 				}
17075 				ire_refrele(dst_ire);
17076 				/* FALLTHRU */
17077 			case IPOPT_TS_TSANDADDR:
17078 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17079 				break;
17080 			default:
17081 				/*
17082 				 * ip_*put_options should have already
17083 				 * dropped this packet.
17084 				 */
17085 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17086 				    "unknown IT - bug in ip_rput_options?\n");
17087 				return (0);	/* Keep "lint" happy */
17088 			}
17089 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17090 				/* Increase overflow counter */
17091 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17092 				opt[IPOPT_POS_OV_FLG] =
17093 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17094 				    (off << 4));
17095 				break;
17096 			}
17097 			off = opt[IPOPT_OFFSET] - 1;
17098 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17099 			case IPOPT_TS_PRESPEC:
17100 			case IPOPT_TS_PRESPEC_RFC791:
17101 			case IPOPT_TS_TSANDADDR:
17102 				bcopy(&ire->ire_src_addr,
17103 				    (char *)opt + off, IP_ADDR_LEN);
17104 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17105 				/* FALLTHRU */
17106 			case IPOPT_TS_TSONLY:
17107 				off = opt[IPOPT_OFFSET] - 1;
17108 				/* Compute # of milliseconds since midnight */
17109 				gethrestime(&now);
17110 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17111 				    now.tv_nsec / (NANOSEC / MILLISEC);
17112 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17113 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17114 				break;
17115 			}
17116 			break;
17117 		}
17118 	}
17119 	return (0);
17120 }
17121 
17122 /*
17123  * This is called after processing at least one of AH/ESP headers.
17124  *
17125  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17126  * the actual, physical interface on which the packet was received,
17127  * but, when ip_strict_dst_multihoming is set to 1, could be the
17128  * interface which had the ipha_dst configured when the packet went
17129  * through ip_rput. The ill_index corresponding to the recv_ill
17130  * is saved in ipsec_in_rill_index
17131  *
17132  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17133  * cannot assume "ire" points to valid data for any IPv6 cases.
17134  */
17135 void
17136 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17137 {
17138 	mblk_t *mp;
17139 	ipaddr_t dst;
17140 	in6_addr_t *v6dstp;
17141 	ipha_t *ipha;
17142 	ip6_t *ip6h;
17143 	ipsec_in_t *ii;
17144 	boolean_t ill_need_rele = B_FALSE;
17145 	boolean_t rill_need_rele = B_FALSE;
17146 	boolean_t ire_need_rele = B_FALSE;
17147 	netstack_t	*ns;
17148 	ip_stack_t	*ipst;
17149 
17150 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17151 	ASSERT(ii->ipsec_in_ill_index != 0);
17152 	ns = ii->ipsec_in_ns;
17153 	ASSERT(ii->ipsec_in_ns != NULL);
17154 	ipst = ns->netstack_ip;
17155 
17156 	mp = ipsec_mp->b_cont;
17157 	ASSERT(mp != NULL);
17158 
17159 	if (ill == NULL) {
17160 		ASSERT(recv_ill == NULL);
17161 		/*
17162 		 * We need to get the original queue on which ip_rput_local
17163 		 * or ip_rput_data_v6 was called.
17164 		 */
17165 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17166 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17167 		ill_need_rele = B_TRUE;
17168 
17169 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17170 			recv_ill = ill_lookup_on_ifindex(
17171 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17172 			    NULL, NULL, NULL, NULL, ipst);
17173 			rill_need_rele = B_TRUE;
17174 		} else {
17175 			recv_ill = ill;
17176 		}
17177 
17178 		if ((ill == NULL) || (recv_ill == NULL)) {
17179 			ip0dbg(("ip_fanout_proto_again: interface "
17180 			    "disappeared\n"));
17181 			if (ill != NULL)
17182 				ill_refrele(ill);
17183 			if (recv_ill != NULL)
17184 				ill_refrele(recv_ill);
17185 			freemsg(ipsec_mp);
17186 			return;
17187 		}
17188 	}
17189 
17190 	ASSERT(ill != NULL && recv_ill != NULL);
17191 
17192 	if (mp->b_datap->db_type == M_CTL) {
17193 		/*
17194 		 * AH/ESP is returning the ICMP message after
17195 		 * removing their headers. Fanout again till
17196 		 * it gets to the right protocol.
17197 		 */
17198 		if (ii->ipsec_in_v4) {
17199 			icmph_t *icmph;
17200 			int iph_hdr_length;
17201 			int hdr_length;
17202 
17203 			ipha = (ipha_t *)mp->b_rptr;
17204 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17205 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17206 			ipha = (ipha_t *)&icmph[1];
17207 			hdr_length = IPH_HDR_LENGTH(ipha);
17208 			/*
17209 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17210 			 * Reset the type to M_DATA.
17211 			 */
17212 			mp->b_datap->db_type = M_DATA;
17213 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17214 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17215 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17216 		} else {
17217 			icmp6_t *icmp6;
17218 			int hdr_length;
17219 
17220 			ip6h = (ip6_t *)mp->b_rptr;
17221 			/* Don't call hdr_length_v6() unless you have to. */
17222 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17223 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17224 			else
17225 				hdr_length = IPV6_HDR_LEN;
17226 
17227 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17228 			/*
17229 			 * icmp_inbound_error_fanout_v6 may need to do
17230 			 * pullupmsg.  Reset the type to M_DATA.
17231 			 */
17232 			mp->b_datap->db_type = M_DATA;
17233 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17234 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17235 			    ii->ipsec_in_zoneid);
17236 		}
17237 		if (ill_need_rele)
17238 			ill_refrele(ill);
17239 		if (rill_need_rele)
17240 			ill_refrele(recv_ill);
17241 		return;
17242 	}
17243 
17244 	if (ii->ipsec_in_v4) {
17245 		ipha = (ipha_t *)mp->b_rptr;
17246 		dst = ipha->ipha_dst;
17247 		if (CLASSD(dst)) {
17248 			/*
17249 			 * Multicast has to be delivered to all streams.
17250 			 */
17251 			dst = INADDR_BROADCAST;
17252 		}
17253 
17254 		if (ire == NULL) {
17255 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17256 			    msg_getlabel(mp), ipst);
17257 			if (ire == NULL) {
17258 				if (ill_need_rele)
17259 					ill_refrele(ill);
17260 				if (rill_need_rele)
17261 					ill_refrele(recv_ill);
17262 				ip1dbg(("ip_fanout_proto_again: "
17263 				    "IRE not found"));
17264 				freemsg(ipsec_mp);
17265 				return;
17266 			}
17267 			ire_need_rele = B_TRUE;
17268 		}
17269 
17270 		switch (ipha->ipha_protocol) {
17271 		case IPPROTO_UDP:
17272 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17273 			    recv_ill);
17274 			if (ire_need_rele)
17275 				ire_refrele(ire);
17276 			break;
17277 		case IPPROTO_TCP:
17278 			if (!ire_need_rele)
17279 				IRE_REFHOLD(ire);
17280 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17281 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17282 			IRE_REFRELE(ire);
17283 			if (mp != NULL) {
17284 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17285 				    mp, 1, SQ_PROCESS,
17286 				    SQTAG_IP_PROTO_AGAIN);
17287 			}
17288 			break;
17289 		case IPPROTO_SCTP:
17290 			if (!ire_need_rele)
17291 				IRE_REFHOLD(ire);
17292 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17293 			    ipsec_mp, 0, ill->ill_rq, dst);
17294 			break;
17295 		default:
17296 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17297 			    recv_ill, 0);
17298 			if (ire_need_rele)
17299 				ire_refrele(ire);
17300 			break;
17301 		}
17302 	} else {
17303 		uint32_t rput_flags = 0;
17304 
17305 		ip6h = (ip6_t *)mp->b_rptr;
17306 		v6dstp = &ip6h->ip6_dst;
17307 		/*
17308 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17309 		 * address.
17310 		 *
17311 		 * Currently, we don't store that state in the IPSEC_IN
17312 		 * message, and we may need to.
17313 		 */
17314 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17315 		    IP6_IN_LLMCAST : 0);
17316 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17317 		    NULL, NULL);
17318 	}
17319 	if (ill_need_rele)
17320 		ill_refrele(ill);
17321 	if (rill_need_rele)
17322 		ill_refrele(recv_ill);
17323 }
17324 
17325 /*
17326  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17327  * returns 'true' if there are still fragments left on the queue, in
17328  * which case we restart the timer.
17329  */
17330 void
17331 ill_frag_timer(void *arg)
17332 {
17333 	ill_t	*ill = (ill_t *)arg;
17334 	boolean_t frag_pending;
17335 	ip_stack_t	*ipst = ill->ill_ipst;
17336 	time_t	timeout;
17337 
17338 	mutex_enter(&ill->ill_lock);
17339 	ASSERT(!ill->ill_fragtimer_executing);
17340 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17341 		ill->ill_frag_timer_id = 0;
17342 		mutex_exit(&ill->ill_lock);
17343 		return;
17344 	}
17345 	ill->ill_fragtimer_executing = 1;
17346 	mutex_exit(&ill->ill_lock);
17347 
17348 	if (ill->ill_isv6)
17349 		timeout = ipst->ips_ipv6_frag_timeout;
17350 	else
17351 		timeout = ipst->ips_ip_g_frag_timeout;
17352 
17353 	frag_pending = ill_frag_timeout(ill, timeout);
17354 
17355 	/*
17356 	 * Restart the timer, if we have fragments pending or if someone
17357 	 * wanted us to be scheduled again.
17358 	 */
17359 	mutex_enter(&ill->ill_lock);
17360 	ill->ill_fragtimer_executing = 0;
17361 	ill->ill_frag_timer_id = 0;
17362 	if (frag_pending || ill->ill_fragtimer_needrestart)
17363 		ill_frag_timer_start(ill);
17364 	mutex_exit(&ill->ill_lock);
17365 }
17366 
17367 void
17368 ill_frag_timer_start(ill_t *ill)
17369 {
17370 	ip_stack_t	*ipst = ill->ill_ipst;
17371 	clock_t	timeo_ms;
17372 
17373 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17374 
17375 	/* If the ill is closing or opening don't proceed */
17376 	if (ill->ill_state_flags & ILL_CONDEMNED)
17377 		return;
17378 
17379 	if (ill->ill_fragtimer_executing) {
17380 		/*
17381 		 * ill_frag_timer is currently executing. Just record the
17382 		 * the fact that we want the timer to be restarted.
17383 		 * ill_frag_timer will post a timeout before it returns,
17384 		 * ensuring it will be called again.
17385 		 */
17386 		ill->ill_fragtimer_needrestart = 1;
17387 		return;
17388 	}
17389 
17390 	if (ill->ill_frag_timer_id == 0) {
17391 		if (ill->ill_isv6)
17392 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17393 		else
17394 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17395 		/*
17396 		 * The timer is neither running nor is the timeout handler
17397 		 * executing. Post a timeout so that ill_frag_timer will be
17398 		 * called
17399 		 */
17400 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17401 		    MSEC_TO_TICK(timeo_ms >> 1));
17402 		ill->ill_fragtimer_needrestart = 0;
17403 	}
17404 }
17405 
17406 /*
17407  * This routine is needed for loopback when forwarding multicasts.
17408  *
17409  * IPQoS Notes:
17410  * IPPF processing is done in fanout routines.
17411  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17412  * processing for IPsec packets is done when it comes back in clear.
17413  * NOTE : The callers of this function need to do the ire_refrele for the
17414  *	  ire that is being passed in.
17415  */
17416 void
17417 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17418     ill_t *recv_ill, uint32_t esp_udp_ports)
17419 {
17420 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17421 	ill_t	*ill = (ill_t *)q->q_ptr;
17422 	uint32_t	sum;
17423 	uint32_t	u1;
17424 	uint32_t	u2;
17425 	int		hdr_length;
17426 	boolean_t	mctl_present;
17427 	mblk_t		*first_mp = mp;
17428 	mblk_t		*hada_mp = NULL;
17429 	ipha_t		*inner_ipha;
17430 	ip_stack_t	*ipst;
17431 
17432 	ASSERT(recv_ill != NULL);
17433 	ipst = recv_ill->ill_ipst;
17434 
17435 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17436 	    "ip_rput_locl_start: q %p", q);
17437 
17438 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17439 	ASSERT(ill != NULL);
17440 
17441 #define	rptr	((uchar_t *)ipha)
17442 #define	iphs	((uint16_t *)ipha)
17443 
17444 	/*
17445 	 * no UDP or TCP packet should come here anymore.
17446 	 */
17447 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17448 	    ipha->ipha_protocol != IPPROTO_UDP);
17449 
17450 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17451 	if (mctl_present &&
17452 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17453 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17454 
17455 		/*
17456 		 * It's an IPsec accelerated packet.
17457 		 * Keep a pointer to the data attributes around until
17458 		 * we allocate the ipsec_info_t.
17459 		 */
17460 		IPSECHW_DEBUG(IPSECHW_PKT,
17461 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17462 		hada_mp = first_mp;
17463 		hada_mp->b_cont = NULL;
17464 		/*
17465 		 * Since it is accelerated, it comes directly from
17466 		 * the ill and the data attributes is followed by
17467 		 * the packet data.
17468 		 */
17469 		ASSERT(mp->b_datap->db_type != M_CTL);
17470 		first_mp = mp;
17471 		mctl_present = B_FALSE;
17472 	}
17473 
17474 	/*
17475 	 * IF M_CTL is not present, then ipsec_in_is_secure
17476 	 * should return B_TRUE. There is a case where loopback
17477 	 * packets has an M_CTL in the front with all the
17478 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17479 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17480 	 * packets never comes here, it is safe to ASSERT the
17481 	 * following.
17482 	 */
17483 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17484 
17485 	/*
17486 	 * Also, we should never have an mctl_present if this is an
17487 	 * ESP-in-UDP packet.
17488 	 */
17489 	ASSERT(!mctl_present || !esp_in_udp_packet);
17490 
17491 	/* u1 is # words of IP options */
17492 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17493 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17494 
17495 	/*
17496 	 * Don't verify header checksum if we just removed UDP header or
17497 	 * packet is coming back from AH/ESP.
17498 	 */
17499 	if (!esp_in_udp_packet && !mctl_present) {
17500 		if (u1) {
17501 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17502 				if (hada_mp != NULL)
17503 					freemsg(hada_mp);
17504 				return;
17505 			}
17506 		} else {
17507 			/* Check the IP header checksum.  */
17508 #define	uph	((uint16_t *)ipha)
17509 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17510 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17511 #undef  uph
17512 			/* finish doing IP checksum */
17513 			sum = (sum & 0xFFFF) + (sum >> 16);
17514 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17515 			if (sum && sum != 0xFFFF) {
17516 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17517 				goto drop_pkt;
17518 			}
17519 		}
17520 	}
17521 
17522 	/*
17523 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17524 	 * might be called more than once for secure packets, count only
17525 	 * the first time.
17526 	 */
17527 	if (!mctl_present) {
17528 		UPDATE_IB_PKT_COUNT(ire);
17529 		ire->ire_last_used_time = lbolt;
17530 	}
17531 
17532 	/* Check for fragmentation offset. */
17533 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17534 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17535 	if (u1) {
17536 		/*
17537 		 * We re-assemble fragments before we do the AH/ESP
17538 		 * processing. Thus, M_CTL should not be present
17539 		 * while we are re-assembling.
17540 		 */
17541 		ASSERT(!mctl_present);
17542 		ASSERT(first_mp == mp);
17543 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17544 			return;
17545 
17546 		/*
17547 		 * Make sure that first_mp points back to mp as
17548 		 * the mp we came in with could have changed in
17549 		 * ip_rput_fragment().
17550 		 */
17551 		ipha = (ipha_t *)mp->b_rptr;
17552 		first_mp = mp;
17553 	}
17554 
17555 	/*
17556 	 * Clear hardware checksumming flag as it is currently only
17557 	 * used by TCP and UDP.
17558 	 */
17559 	DB_CKSUMFLAGS(mp) = 0;
17560 
17561 	/* Now we have a complete datagram, destined for this machine. */
17562 	u1 = IPH_HDR_LENGTH(ipha);
17563 	switch (ipha->ipha_protocol) {
17564 	case IPPROTO_ICMP: {
17565 		ire_t		*ire_zone;
17566 		ilm_t		*ilm;
17567 		mblk_t		*mp1;
17568 		zoneid_t	last_zoneid;
17569 		ilm_walker_t	ilw;
17570 
17571 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17572 			ASSERT(ire->ire_type == IRE_BROADCAST);
17573 
17574 			/*
17575 			 * In the multicast case, applications may have joined
17576 			 * the group from different zones, so we need to deliver
17577 			 * the packet to each of them. Loop through the
17578 			 * multicast memberships structures (ilm) on the receive
17579 			 * ill and send a copy of the packet up each matching
17580 			 * one. However, we don't do this for multicasts sent on
17581 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17582 			 * they must stay in the sender's zone.
17583 			 *
17584 			 * ilm_add_v6() ensures that ilms in the same zone are
17585 			 * contiguous in the ill_ilm list. We use this property
17586 			 * to avoid sending duplicates needed when two
17587 			 * applications in the same zone join the same group on
17588 			 * different logical interfaces: we ignore the ilm if
17589 			 * its zoneid is the same as the last matching one.
17590 			 * In addition, the sending of the packet for
17591 			 * ire_zoneid is delayed until all of the other ilms
17592 			 * have been exhausted.
17593 			 */
17594 			last_zoneid = -1;
17595 			ilm = ilm_walker_start(&ilw, recv_ill);
17596 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17597 				if (ipha->ipha_dst != ilm->ilm_addr ||
17598 				    ilm->ilm_zoneid == last_zoneid ||
17599 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17600 				    ilm->ilm_zoneid == ALL_ZONES ||
17601 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17602 					continue;
17603 				mp1 = ip_copymsg(first_mp);
17604 				if (mp1 == NULL)
17605 					continue;
17606 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17607 				    0, sum, mctl_present, B_TRUE,
17608 				    recv_ill, ilm->ilm_zoneid);
17609 				last_zoneid = ilm->ilm_zoneid;
17610 			}
17611 			ilm_walker_finish(&ilw);
17612 		} else if (ire->ire_type == IRE_BROADCAST) {
17613 			/*
17614 			 * In the broadcast case, there may be many zones
17615 			 * which need a copy of the packet delivered to them.
17616 			 * There is one IRE_BROADCAST per broadcast address
17617 			 * and per zone; we walk those using a helper function.
17618 			 * In addition, the sending of the packet for ire is
17619 			 * delayed until all of the other ires have been
17620 			 * processed.
17621 			 */
17622 			IRB_REFHOLD(ire->ire_bucket);
17623 			ire_zone = NULL;
17624 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17625 			    ire)) != NULL) {
17626 				mp1 = ip_copymsg(first_mp);
17627 				if (mp1 == NULL)
17628 					continue;
17629 
17630 				UPDATE_IB_PKT_COUNT(ire_zone);
17631 				ire_zone->ire_last_used_time = lbolt;
17632 				icmp_inbound(q, mp1, B_TRUE, ill,
17633 				    0, sum, mctl_present, B_TRUE,
17634 				    recv_ill, ire_zone->ire_zoneid);
17635 			}
17636 			IRB_REFRELE(ire->ire_bucket);
17637 		}
17638 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17639 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17640 		    ire->ire_zoneid);
17641 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17642 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17643 		return;
17644 	}
17645 	case IPPROTO_IGMP:
17646 		/*
17647 		 * If we are not willing to accept IGMP packets in clear,
17648 		 * then check with global policy.
17649 		 */
17650 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17651 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17652 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17653 			if (first_mp == NULL)
17654 				return;
17655 		}
17656 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17657 			freemsg(first_mp);
17658 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17659 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17660 			return;
17661 		}
17662 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17663 			/* Bad packet - discarded by igmp_input */
17664 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17665 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17666 			if (mctl_present)
17667 				freeb(first_mp);
17668 			return;
17669 		}
17670 		/*
17671 		 * igmp_input() may have returned the pulled up message.
17672 		 * So first_mp and ipha need to be reinitialized.
17673 		 */
17674 		ipha = (ipha_t *)mp->b_rptr;
17675 		if (mctl_present)
17676 			first_mp->b_cont = mp;
17677 		else
17678 			first_mp = mp;
17679 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17680 		    connf_head != NULL) {
17681 			/* No user-level listener for IGMP packets */
17682 			goto drop_pkt;
17683 		}
17684 		/* deliver to local raw users */
17685 		break;
17686 	case IPPROTO_PIM:
17687 		/*
17688 		 * If we are not willing to accept PIM packets in clear,
17689 		 * then check with global policy.
17690 		 */
17691 		if (ipst->ips_pim_accept_clear_messages == 0) {
17692 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17693 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17694 			if (first_mp == NULL)
17695 				return;
17696 		}
17697 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17698 			freemsg(first_mp);
17699 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17700 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17701 			return;
17702 		}
17703 		if (pim_input(q, mp, ill) != 0) {
17704 			/* Bad packet - discarded by pim_input */
17705 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17706 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17707 			if (mctl_present)
17708 				freeb(first_mp);
17709 			return;
17710 		}
17711 
17712 		/*
17713 		 * pim_input() may have pulled up the message so ipha needs to
17714 		 * be reinitialized.
17715 		 */
17716 		ipha = (ipha_t *)mp->b_rptr;
17717 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17718 		    connf_head != NULL) {
17719 			/* No user-level listener for PIM packets */
17720 			goto drop_pkt;
17721 		}
17722 		/* deliver to local raw users */
17723 		break;
17724 	case IPPROTO_ENCAP:
17725 		/*
17726 		 * Handle self-encapsulated packets (IP-in-IP where
17727 		 * the inner addresses == the outer addresses).
17728 		 */
17729 		hdr_length = IPH_HDR_LENGTH(ipha);
17730 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17731 		    mp->b_wptr) {
17732 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17733 			    sizeof (ipha_t) - mp->b_rptr)) {
17734 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17735 				freemsg(first_mp);
17736 				return;
17737 			}
17738 			ipha = (ipha_t *)mp->b_rptr;
17739 		}
17740 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17741 		/*
17742 		 * Check the sanity of the inner IP header.
17743 		 */
17744 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17745 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17746 			freemsg(first_mp);
17747 			return;
17748 		}
17749 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17750 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17751 			freemsg(first_mp);
17752 			return;
17753 		}
17754 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17755 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17756 			ipsec_in_t *ii;
17757 
17758 			/*
17759 			 * Self-encapsulated tunnel packet. Remove
17760 			 * the outer IP header and fanout again.
17761 			 * We also need to make sure that the inner
17762 			 * header is pulled up until options.
17763 			 */
17764 			mp->b_rptr = (uchar_t *)inner_ipha;
17765 			ipha = inner_ipha;
17766 			hdr_length = IPH_HDR_LENGTH(ipha);
17767 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17768 				if (!pullupmsg(mp, (uchar_t *)ipha +
17769 				    + hdr_length - mp->b_rptr)) {
17770 					freemsg(first_mp);
17771 					return;
17772 				}
17773 				ipha = (ipha_t *)mp->b_rptr;
17774 			}
17775 			if (hdr_length > sizeof (ipha_t)) {
17776 				/* We got options on the inner packet. */
17777 				ipaddr_t dst = ipha->ipha_dst;
17778 
17779 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17780 				    -1) {
17781 					/* Bad options! */
17782 					return;
17783 				}
17784 				if (dst != ipha->ipha_dst) {
17785 					/*
17786 					 * Someone put a source-route in
17787 					 * the inside header of a self-
17788 					 * encapsulated packet.  Drop it
17789 					 * with extreme prejudice and let
17790 					 * the sender know.
17791 					 */
17792 					icmp_unreachable(q, first_mp,
17793 					    ICMP_SOURCE_ROUTE_FAILED,
17794 					    recv_ill->ill_zoneid, ipst);
17795 					return;
17796 				}
17797 			}
17798 			if (!mctl_present) {
17799 				ASSERT(first_mp == mp);
17800 				/*
17801 				 * This means that somebody is sending
17802 				 * Self-encapsualted packets without AH/ESP.
17803 				 * If AH/ESP was present, we would have already
17804 				 * allocated the first_mp.
17805 				 *
17806 				 * Send this packet to find a tunnel endpoint.
17807 				 * if I can't find one, an ICMP
17808 				 * PROTOCOL_UNREACHABLE will get sent.
17809 				 */
17810 				goto fanout;
17811 			}
17812 			/*
17813 			 * We generally store the ill_index if we need to
17814 			 * do IPsec processing as we lose the ill queue when
17815 			 * we come back. But in this case, we never should
17816 			 * have to store the ill_index here as it should have
17817 			 * been stored previously when we processed the
17818 			 * AH/ESP header in this routine or for non-ipsec
17819 			 * cases, we still have the queue. But for some bad
17820 			 * packets from the wire, we can get to IPsec after
17821 			 * this and we better store the index for that case.
17822 			 */
17823 			ill = (ill_t *)q->q_ptr;
17824 			ii = (ipsec_in_t *)first_mp->b_rptr;
17825 			ii->ipsec_in_ill_index =
17826 			    ill->ill_phyint->phyint_ifindex;
17827 			ii->ipsec_in_rill_index =
17828 			    recv_ill->ill_phyint->phyint_ifindex;
17829 			if (ii->ipsec_in_decaps) {
17830 				/*
17831 				 * This packet is self-encapsulated multiple
17832 				 * times. We don't want to recurse infinitely.
17833 				 * To keep it simple, drop the packet.
17834 				 */
17835 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17836 				freemsg(first_mp);
17837 				return;
17838 			}
17839 			ii->ipsec_in_decaps = B_TRUE;
17840 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17841 			    ire);
17842 			return;
17843 		}
17844 		break;
17845 	case IPPROTO_AH:
17846 	case IPPROTO_ESP: {
17847 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17848 
17849 		/*
17850 		 * Fast path for AH/ESP. If this is the first time
17851 		 * we are sending a datagram to AH/ESP, allocate
17852 		 * a IPSEC_IN message and prepend it. Otherwise,
17853 		 * just fanout.
17854 		 */
17855 
17856 		int ipsec_rc;
17857 		ipsec_in_t *ii;
17858 		netstack_t *ns = ipst->ips_netstack;
17859 
17860 		IP_STAT(ipst, ipsec_proto_ahesp);
17861 		if (!mctl_present) {
17862 			ASSERT(first_mp == mp);
17863 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17864 			if (first_mp == NULL) {
17865 				ip1dbg(("ip_proto_input: IPSEC_IN "
17866 				    "allocation failure.\n"));
17867 				freemsg(hada_mp); /* okay ifnull */
17868 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17869 				freemsg(mp);
17870 				return;
17871 			}
17872 			/*
17873 			 * Store the ill_index so that when we come back
17874 			 * from IPsec we ride on the same queue.
17875 			 */
17876 			ill = (ill_t *)q->q_ptr;
17877 			ii = (ipsec_in_t *)first_mp->b_rptr;
17878 			ii->ipsec_in_ill_index =
17879 			    ill->ill_phyint->phyint_ifindex;
17880 			ii->ipsec_in_rill_index =
17881 			    recv_ill->ill_phyint->phyint_ifindex;
17882 			first_mp->b_cont = mp;
17883 			/*
17884 			 * Cache hardware acceleration info.
17885 			 */
17886 			if (hada_mp != NULL) {
17887 				IPSECHW_DEBUG(IPSECHW_PKT,
17888 				    ("ip_rput_local: caching data attr.\n"));
17889 				ii->ipsec_in_accelerated = B_TRUE;
17890 				ii->ipsec_in_da = hada_mp;
17891 				hada_mp = NULL;
17892 			}
17893 		} else {
17894 			ii = (ipsec_in_t *)first_mp->b_rptr;
17895 		}
17896 
17897 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17898 
17899 		if (!ipsec_loaded(ipss)) {
17900 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17901 			    ire->ire_zoneid, ipst);
17902 			return;
17903 		}
17904 
17905 		ns = ipst->ips_netstack;
17906 		/* select inbound SA and have IPsec process the pkt */
17907 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17908 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17909 			boolean_t esp_in_udp_sa;
17910 			if (esph == NULL)
17911 				return;
17912 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17913 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17914 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17915 			    IPSA_F_NATT) != 0);
17916 			/*
17917 			 * The following is a fancy, but quick, way of saying:
17918 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17919 			 *    OR
17920 			 * ESP SA and ESP-in-UDP packet --> drop
17921 			 */
17922 			if (esp_in_udp_sa != esp_in_udp_packet) {
17923 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17924 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17925 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17926 				    &ns->netstack_ipsec->ipsec_dropper);
17927 				return;
17928 			}
17929 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17930 			    first_mp, esph);
17931 		} else {
17932 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17933 			if (ah == NULL)
17934 				return;
17935 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17936 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17937 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17938 			    first_mp, ah);
17939 		}
17940 
17941 		switch (ipsec_rc) {
17942 		case IPSEC_STATUS_SUCCESS:
17943 			break;
17944 		case IPSEC_STATUS_FAILED:
17945 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17946 			/* FALLTHRU */
17947 		case IPSEC_STATUS_PENDING:
17948 			return;
17949 		}
17950 		/* we're done with IPsec processing, send it up */
17951 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17952 		return;
17953 	}
17954 	default:
17955 		break;
17956 	}
17957 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17958 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17959 		    ire->ire_zoneid));
17960 		goto drop_pkt;
17961 	}
17962 	/*
17963 	 * Handle protocols with which IP is less intimate.  There
17964 	 * can be more than one stream bound to a particular
17965 	 * protocol.  When this is the case, each one gets a copy
17966 	 * of any incoming packets.
17967 	 */
17968 fanout:
17969 	ip_fanout_proto(q, first_mp, ill, ipha,
17970 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17971 	    B_TRUE, recv_ill, ire->ire_zoneid);
17972 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17973 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17974 	return;
17975 
17976 drop_pkt:
17977 	freemsg(first_mp);
17978 	if (hada_mp != NULL)
17979 		freeb(hada_mp);
17980 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17981 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17982 #undef	rptr
17983 #undef  iphs
17984 
17985 }
17986 
17987 /*
17988  * Update any source route, record route or timestamp options.
17989  * Check that we are at end of strict source route.
17990  * The options have already been checked for sanity in ip_rput_options().
17991  */
17992 static boolean_t
17993 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17994     ip_stack_t *ipst)
17995 {
17996 	ipoptp_t	opts;
17997 	uchar_t		*opt;
17998 	uint8_t		optval;
17999 	uint8_t		optlen;
18000 	ipaddr_t	dst;
18001 	uint32_t	ts;
18002 	ire_t		*dst_ire;
18003 	timestruc_t	now;
18004 	zoneid_t	zoneid;
18005 	ill_t		*ill;
18006 
18007 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18008 
18009 	ip2dbg(("ip_rput_local_options\n"));
18010 
18011 	for (optval = ipoptp_first(&opts, ipha);
18012 	    optval != IPOPT_EOL;
18013 	    optval = ipoptp_next(&opts)) {
18014 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18015 		opt = opts.ipoptp_cur;
18016 		optlen = opts.ipoptp_len;
18017 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18018 		    optval, optlen));
18019 		switch (optval) {
18020 			uint32_t off;
18021 		case IPOPT_SSRR:
18022 		case IPOPT_LSRR:
18023 			off = opt[IPOPT_OFFSET];
18024 			off--;
18025 			if (optlen < IP_ADDR_LEN ||
18026 			    off > optlen - IP_ADDR_LEN) {
18027 				/* End of source route */
18028 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18029 				break;
18030 			}
18031 			/*
18032 			 * This will only happen if two consecutive entries
18033 			 * in the source route contains our address or if
18034 			 * it is a packet with a loose source route which
18035 			 * reaches us before consuming the whole source route
18036 			 */
18037 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18038 			if (optval == IPOPT_SSRR) {
18039 				goto bad_src_route;
18040 			}
18041 			/*
18042 			 * Hack: instead of dropping the packet truncate the
18043 			 * source route to what has been used by filling the
18044 			 * rest with IPOPT_NOP.
18045 			 */
18046 			opt[IPOPT_OLEN] = (uint8_t)off;
18047 			while (off < optlen) {
18048 				opt[off++] = IPOPT_NOP;
18049 			}
18050 			break;
18051 		case IPOPT_RR:
18052 			off = opt[IPOPT_OFFSET];
18053 			off--;
18054 			if (optlen < IP_ADDR_LEN ||
18055 			    off > optlen - IP_ADDR_LEN) {
18056 				/* No more room - ignore */
18057 				ip1dbg((
18058 				    "ip_rput_local_options: end of RR\n"));
18059 				break;
18060 			}
18061 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18062 			    IP_ADDR_LEN);
18063 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18064 			break;
18065 		case IPOPT_TS:
18066 			/* Insert timestamp if there is romm */
18067 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18068 			case IPOPT_TS_TSONLY:
18069 				off = IPOPT_TS_TIMELEN;
18070 				break;
18071 			case IPOPT_TS_PRESPEC:
18072 			case IPOPT_TS_PRESPEC_RFC791:
18073 				/* Verify that the address matched */
18074 				off = opt[IPOPT_OFFSET] - 1;
18075 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18076 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18077 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18078 				    ipst);
18079 				if (dst_ire == NULL) {
18080 					/* Not for us */
18081 					break;
18082 				}
18083 				ire_refrele(dst_ire);
18084 				/* FALLTHRU */
18085 			case IPOPT_TS_TSANDADDR:
18086 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18087 				break;
18088 			default:
18089 				/*
18090 				 * ip_*put_options should have already
18091 				 * dropped this packet.
18092 				 */
18093 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18094 				    "unknown IT - bug in ip_rput_options?\n");
18095 				return (B_TRUE);	/* Keep "lint" happy */
18096 			}
18097 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18098 				/* Increase overflow counter */
18099 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18100 				opt[IPOPT_POS_OV_FLG] =
18101 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18102 				    (off << 4));
18103 				break;
18104 			}
18105 			off = opt[IPOPT_OFFSET] - 1;
18106 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18107 			case IPOPT_TS_PRESPEC:
18108 			case IPOPT_TS_PRESPEC_RFC791:
18109 			case IPOPT_TS_TSANDADDR:
18110 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18111 				    IP_ADDR_LEN);
18112 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18113 				/* FALLTHRU */
18114 			case IPOPT_TS_TSONLY:
18115 				off = opt[IPOPT_OFFSET] - 1;
18116 				/* Compute # of milliseconds since midnight */
18117 				gethrestime(&now);
18118 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18119 				    now.tv_nsec / (NANOSEC / MILLISEC);
18120 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18121 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18122 				break;
18123 			}
18124 			break;
18125 		}
18126 	}
18127 	return (B_TRUE);
18128 
18129 bad_src_route:
18130 	q = WR(q);
18131 	if (q->q_next != NULL)
18132 		ill = q->q_ptr;
18133 	else
18134 		ill = NULL;
18135 
18136 	/* make sure we clear any indication of a hardware checksum */
18137 	DB_CKSUMFLAGS(mp) = 0;
18138 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18139 	if (zoneid == ALL_ZONES)
18140 		freemsg(mp);
18141 	else
18142 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18143 	return (B_FALSE);
18144 
18145 }
18146 
18147 /*
18148  * Process IP options in an inbound packet.  If an option affects the
18149  * effective destination address, return the next hop address via dstp.
18150  * Returns -1 if something fails in which case an ICMP error has been sent
18151  * and mp freed.
18152  */
18153 static int
18154 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18155     ip_stack_t *ipst)
18156 {
18157 	ipoptp_t	opts;
18158 	uchar_t		*opt;
18159 	uint8_t		optval;
18160 	uint8_t		optlen;
18161 	ipaddr_t	dst;
18162 	intptr_t	code = 0;
18163 	ire_t		*ire = NULL;
18164 	zoneid_t	zoneid;
18165 	ill_t		*ill;
18166 
18167 	ip2dbg(("ip_rput_options\n"));
18168 	dst = ipha->ipha_dst;
18169 	for (optval = ipoptp_first(&opts, ipha);
18170 	    optval != IPOPT_EOL;
18171 	    optval = ipoptp_next(&opts)) {
18172 		opt = opts.ipoptp_cur;
18173 		optlen = opts.ipoptp_len;
18174 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18175 		    optval, optlen));
18176 		/*
18177 		 * Note: we need to verify the checksum before we
18178 		 * modify anything thus this routine only extracts the next
18179 		 * hop dst from any source route.
18180 		 */
18181 		switch (optval) {
18182 			uint32_t off;
18183 		case IPOPT_SSRR:
18184 		case IPOPT_LSRR:
18185 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18186 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18187 			if (ire == NULL) {
18188 				if (optval == IPOPT_SSRR) {
18189 					ip1dbg(("ip_rput_options: not next"
18190 					    " strict source route 0x%x\n",
18191 					    ntohl(dst)));
18192 					code = (char *)&ipha->ipha_dst -
18193 					    (char *)ipha;
18194 					goto param_prob; /* RouterReq's */
18195 				}
18196 				ip2dbg(("ip_rput_options: "
18197 				    "not next source route 0x%x\n",
18198 				    ntohl(dst)));
18199 				break;
18200 			}
18201 			ire_refrele(ire);
18202 
18203 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18204 				ip1dbg((
18205 				    "ip_rput_options: bad option offset\n"));
18206 				code = (char *)&opt[IPOPT_OLEN] -
18207 				    (char *)ipha;
18208 				goto param_prob;
18209 			}
18210 			off = opt[IPOPT_OFFSET];
18211 			off--;
18212 		redo_srr:
18213 			if (optlen < IP_ADDR_LEN ||
18214 			    off > optlen - IP_ADDR_LEN) {
18215 				/* End of source route */
18216 				ip1dbg(("ip_rput_options: end of SR\n"));
18217 				break;
18218 			}
18219 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18220 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18221 			    ntohl(dst)));
18222 
18223 			/*
18224 			 * Check if our address is present more than
18225 			 * once as consecutive hops in source route.
18226 			 * XXX verify per-interface ip_forwarding
18227 			 * for source route?
18228 			 */
18229 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18230 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18231 
18232 			if (ire != NULL) {
18233 				ire_refrele(ire);
18234 				off += IP_ADDR_LEN;
18235 				goto redo_srr;
18236 			}
18237 
18238 			if (dst == htonl(INADDR_LOOPBACK)) {
18239 				ip1dbg(("ip_rput_options: loopback addr in "
18240 				    "source route!\n"));
18241 				goto bad_src_route;
18242 			}
18243 			/*
18244 			 * For strict: verify that dst is directly
18245 			 * reachable.
18246 			 */
18247 			if (optval == IPOPT_SSRR) {
18248 				ire = ire_ftable_lookup(dst, 0, 0,
18249 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18250 				    msg_getlabel(mp),
18251 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18252 				if (ire == NULL) {
18253 					ip1dbg(("ip_rput_options: SSRR not "
18254 					    "directly reachable: 0x%x\n",
18255 					    ntohl(dst)));
18256 					goto bad_src_route;
18257 				}
18258 				ire_refrele(ire);
18259 			}
18260 			/*
18261 			 * Defer update of the offset and the record route
18262 			 * until the packet is forwarded.
18263 			 */
18264 			break;
18265 		case IPOPT_RR:
18266 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18267 				ip1dbg((
18268 				    "ip_rput_options: bad option offset\n"));
18269 				code = (char *)&opt[IPOPT_OLEN] -
18270 				    (char *)ipha;
18271 				goto param_prob;
18272 			}
18273 			break;
18274 		case IPOPT_TS:
18275 			/*
18276 			 * Verify that length >= 5 and that there is either
18277 			 * room for another timestamp or that the overflow
18278 			 * counter is not maxed out.
18279 			 */
18280 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18281 			if (optlen < IPOPT_MINLEN_IT) {
18282 				goto param_prob;
18283 			}
18284 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18285 				ip1dbg((
18286 				    "ip_rput_options: bad option offset\n"));
18287 				code = (char *)&opt[IPOPT_OFFSET] -
18288 				    (char *)ipha;
18289 				goto param_prob;
18290 			}
18291 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18292 			case IPOPT_TS_TSONLY:
18293 				off = IPOPT_TS_TIMELEN;
18294 				break;
18295 			case IPOPT_TS_TSANDADDR:
18296 			case IPOPT_TS_PRESPEC:
18297 			case IPOPT_TS_PRESPEC_RFC791:
18298 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18299 				break;
18300 			default:
18301 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18302 				    (char *)ipha;
18303 				goto param_prob;
18304 			}
18305 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18306 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18307 				/*
18308 				 * No room and the overflow counter is 15
18309 				 * already.
18310 				 */
18311 				goto param_prob;
18312 			}
18313 			break;
18314 		}
18315 	}
18316 
18317 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18318 		*dstp = dst;
18319 		return (0);
18320 	}
18321 
18322 	ip1dbg(("ip_rput_options: error processing IP options."));
18323 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18324 
18325 param_prob:
18326 	q = WR(q);
18327 	if (q->q_next != NULL)
18328 		ill = q->q_ptr;
18329 	else
18330 		ill = NULL;
18331 
18332 	/* make sure we clear any indication of a hardware checksum */
18333 	DB_CKSUMFLAGS(mp) = 0;
18334 	/* Don't know whether this is for non-global or global/forwarding */
18335 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18336 	if (zoneid == ALL_ZONES)
18337 		freemsg(mp);
18338 	else
18339 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18340 	return (-1);
18341 
18342 bad_src_route:
18343 	q = WR(q);
18344 	if (q->q_next != NULL)
18345 		ill = q->q_ptr;
18346 	else
18347 		ill = NULL;
18348 
18349 	/* make sure we clear any indication of a hardware checksum */
18350 	DB_CKSUMFLAGS(mp) = 0;
18351 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18352 	if (zoneid == ALL_ZONES)
18353 		freemsg(mp);
18354 	else
18355 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18356 	return (-1);
18357 }
18358 
18359 /*
18360  * IP & ICMP info in >=14 msg's ...
18361  *  - ip fixed part (mib2_ip_t)
18362  *  - icmp fixed part (mib2_icmp_t)
18363  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18364  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18365  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18366  *  - ipRouteAttributeTable (ip 102)	labeled routes
18367  *  - ip multicast membership (ip_member_t)
18368  *  - ip multicast source filtering (ip_grpsrc_t)
18369  *  - igmp fixed part (struct igmpstat)
18370  *  - multicast routing stats (struct mrtstat)
18371  *  - multicast routing vifs (array of struct vifctl)
18372  *  - multicast routing routes (array of struct mfcctl)
18373  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18374  *					One per ill plus one generic
18375  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18376  *					One per ill plus one generic
18377  *  - ipv6RouteEntry			all IPv6 IREs
18378  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18379  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18380  *  - ipv6AddrEntry			all IPv6 ipifs
18381  *  - ipv6 multicast membership (ipv6_member_t)
18382  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18383  *
18384  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18385  *
18386  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18387  * already filled in by the caller.
18388  * Return value of 0 indicates that no messages were sent and caller
18389  * should free mpctl.
18390  */
18391 int
18392 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18393 {
18394 	ip_stack_t *ipst;
18395 	sctp_stack_t *sctps;
18396 
18397 	if (q->q_next != NULL) {
18398 		ipst = ILLQ_TO_IPST(q);
18399 	} else {
18400 		ipst = CONNQ_TO_IPST(q);
18401 	}
18402 	ASSERT(ipst != NULL);
18403 	sctps = ipst->ips_netstack->netstack_sctp;
18404 
18405 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18406 		return (0);
18407 	}
18408 
18409 	/*
18410 	 * For the purposes of the (broken) packet shell use
18411 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18412 	 * to make TCP and UDP appear first in the list of mib items.
18413 	 * TBD: We could expand this and use it in netstat so that
18414 	 * the kernel doesn't have to produce large tables (connections,
18415 	 * routes, etc) when netstat only wants the statistics or a particular
18416 	 * table.
18417 	 */
18418 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18419 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18420 			return (1);
18421 		}
18422 	}
18423 
18424 	if (level != MIB2_TCP) {
18425 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18426 			return (1);
18427 		}
18428 	}
18429 
18430 	if (level != MIB2_UDP) {
18431 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18432 			return (1);
18433 		}
18434 	}
18435 
18436 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18437 	    ipst)) == NULL) {
18438 		return (1);
18439 	}
18440 
18441 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18442 		return (1);
18443 	}
18444 
18445 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18446 		return (1);
18447 	}
18448 
18449 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18450 		return (1);
18451 	}
18452 
18453 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18454 		return (1);
18455 	}
18456 
18457 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18458 		return (1);
18459 	}
18460 
18461 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18462 		return (1);
18463 	}
18464 
18465 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18466 		return (1);
18467 	}
18468 
18469 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18470 		return (1);
18471 	}
18472 
18473 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18474 		return (1);
18475 	}
18476 
18477 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18478 		return (1);
18479 	}
18480 
18481 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18482 		return (1);
18483 	}
18484 
18485 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18486 		return (1);
18487 	}
18488 
18489 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18490 		return (1);
18491 	}
18492 
18493 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18494 	if (mpctl == NULL)
18495 		return (1);
18496 
18497 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18498 	if (mpctl == NULL)
18499 		return (1);
18500 
18501 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18502 		return (1);
18503 	}
18504 	freemsg(mpctl);
18505 	return (1);
18506 }
18507 
18508 /* Get global (legacy) IPv4 statistics */
18509 static mblk_t *
18510 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18511     ip_stack_t *ipst)
18512 {
18513 	mib2_ip_t		old_ip_mib;
18514 	struct opthdr		*optp;
18515 	mblk_t			*mp2ctl;
18516 
18517 	/*
18518 	 * make a copy of the original message
18519 	 */
18520 	mp2ctl = copymsg(mpctl);
18521 
18522 	/* fixed length IP structure... */
18523 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18524 	optp->level = MIB2_IP;
18525 	optp->name = 0;
18526 	SET_MIB(old_ip_mib.ipForwarding,
18527 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18528 	SET_MIB(old_ip_mib.ipDefaultTTL,
18529 	    (uint32_t)ipst->ips_ip_def_ttl);
18530 	SET_MIB(old_ip_mib.ipReasmTimeout,
18531 	    ipst->ips_ip_g_frag_timeout);
18532 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18533 	    sizeof (mib2_ipAddrEntry_t));
18534 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18535 	    sizeof (mib2_ipRouteEntry_t));
18536 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18537 	    sizeof (mib2_ipNetToMediaEntry_t));
18538 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18539 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18540 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18541 	    sizeof (mib2_ipAttributeEntry_t));
18542 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18543 
18544 	/*
18545 	 * Grab the statistics from the new IP MIB
18546 	 */
18547 	SET_MIB(old_ip_mib.ipInReceives,
18548 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18549 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18550 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18551 	SET_MIB(old_ip_mib.ipForwDatagrams,
18552 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18553 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18554 	    ipmib->ipIfStatsInUnknownProtos);
18555 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18556 	SET_MIB(old_ip_mib.ipInDelivers,
18557 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18558 	SET_MIB(old_ip_mib.ipOutRequests,
18559 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18560 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18561 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18562 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18563 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18564 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18565 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18566 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18567 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18568 
18569 	/* ipRoutingDiscards is not being used */
18570 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18571 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18572 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18573 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18574 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18575 	    ipmib->ipIfStatsReasmDuplicates);
18576 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18577 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18578 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18579 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18580 	SET_MIB(old_ip_mib.rawipInOverflows,
18581 	    ipmib->rawipIfStatsInOverflows);
18582 
18583 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18584 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18585 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18586 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18587 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18588 	    ipmib->ipIfStatsOutSwitchIPVersion);
18589 
18590 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18591 	    (int)sizeof (old_ip_mib))) {
18592 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18593 		    (uint_t)sizeof (old_ip_mib)));
18594 	}
18595 
18596 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18597 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18598 	    (int)optp->level, (int)optp->name, (int)optp->len));
18599 	qreply(q, mpctl);
18600 	return (mp2ctl);
18601 }
18602 
18603 /* Per interface IPv4 statistics */
18604 static mblk_t *
18605 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18606 {
18607 	struct opthdr		*optp;
18608 	mblk_t			*mp2ctl;
18609 	ill_t			*ill;
18610 	ill_walk_context_t	ctx;
18611 	mblk_t			*mp_tail = NULL;
18612 	mib2_ipIfStatsEntry_t	global_ip_mib;
18613 
18614 	/*
18615 	 * Make a copy of the original message
18616 	 */
18617 	mp2ctl = copymsg(mpctl);
18618 
18619 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18620 	optp->level = MIB2_IP;
18621 	optp->name = MIB2_IP_TRAFFIC_STATS;
18622 	/* Include "unknown interface" ip_mib */
18623 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18624 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18625 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18626 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18627 	    (ipst->ips_ip_g_forward ? 1 : 2));
18628 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18629 	    (uint32_t)ipst->ips_ip_def_ttl);
18630 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18631 	    sizeof (mib2_ipIfStatsEntry_t));
18632 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18633 	    sizeof (mib2_ipAddrEntry_t));
18634 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18635 	    sizeof (mib2_ipRouteEntry_t));
18636 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18637 	    sizeof (mib2_ipNetToMediaEntry_t));
18638 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18639 	    sizeof (ip_member_t));
18640 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18641 	    sizeof (ip_grpsrc_t));
18642 
18643 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18644 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18645 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18646 		    "failed to allocate %u bytes\n",
18647 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18648 	}
18649 
18650 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18651 
18652 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18653 	ill = ILL_START_WALK_V4(&ctx, ipst);
18654 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18655 		ill->ill_ip_mib->ipIfStatsIfIndex =
18656 		    ill->ill_phyint->phyint_ifindex;
18657 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18658 		    (ipst->ips_ip_g_forward ? 1 : 2));
18659 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18660 		    (uint32_t)ipst->ips_ip_def_ttl);
18661 
18662 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18663 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18664 		    (char *)ill->ill_ip_mib,
18665 		    (int)sizeof (*ill->ill_ip_mib))) {
18666 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18667 			    "failed to allocate %u bytes\n",
18668 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18669 		}
18670 	}
18671 	rw_exit(&ipst->ips_ill_g_lock);
18672 
18673 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18674 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18675 	    "level %d, name %d, len %d\n",
18676 	    (int)optp->level, (int)optp->name, (int)optp->len));
18677 	qreply(q, mpctl);
18678 
18679 	if (mp2ctl == NULL)
18680 		return (NULL);
18681 
18682 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18683 }
18684 
18685 /* Global IPv4 ICMP statistics */
18686 static mblk_t *
18687 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18688 {
18689 	struct opthdr		*optp;
18690 	mblk_t			*mp2ctl;
18691 
18692 	/*
18693 	 * Make a copy of the original message
18694 	 */
18695 	mp2ctl = copymsg(mpctl);
18696 
18697 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18698 	optp->level = MIB2_ICMP;
18699 	optp->name = 0;
18700 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18701 	    (int)sizeof (ipst->ips_icmp_mib))) {
18702 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18703 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18704 	}
18705 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18706 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18707 	    (int)optp->level, (int)optp->name, (int)optp->len));
18708 	qreply(q, mpctl);
18709 	return (mp2ctl);
18710 }
18711 
18712 /* Global IPv4 IGMP statistics */
18713 static mblk_t *
18714 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18715 {
18716 	struct opthdr		*optp;
18717 	mblk_t			*mp2ctl;
18718 
18719 	/*
18720 	 * make a copy of the original message
18721 	 */
18722 	mp2ctl = copymsg(mpctl);
18723 
18724 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18725 	optp->level = EXPER_IGMP;
18726 	optp->name = 0;
18727 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18728 	    (int)sizeof (ipst->ips_igmpstat))) {
18729 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18730 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18731 	}
18732 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18733 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18734 	    (int)optp->level, (int)optp->name, (int)optp->len));
18735 	qreply(q, mpctl);
18736 	return (mp2ctl);
18737 }
18738 
18739 /* Global IPv4 Multicast Routing statistics */
18740 static mblk_t *
18741 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18742 {
18743 	struct opthdr		*optp;
18744 	mblk_t			*mp2ctl;
18745 
18746 	/*
18747 	 * make a copy of the original message
18748 	 */
18749 	mp2ctl = copymsg(mpctl);
18750 
18751 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18752 	optp->level = EXPER_DVMRP;
18753 	optp->name = 0;
18754 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18755 		ip0dbg(("ip_mroute_stats: failed\n"));
18756 	}
18757 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18758 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18759 	    (int)optp->level, (int)optp->name, (int)optp->len));
18760 	qreply(q, mpctl);
18761 	return (mp2ctl);
18762 }
18763 
18764 /* IPv4 address information */
18765 static mblk_t *
18766 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18767 {
18768 	struct opthdr		*optp;
18769 	mblk_t			*mp2ctl;
18770 	mblk_t			*mp_tail = NULL;
18771 	ill_t			*ill;
18772 	ipif_t			*ipif;
18773 	uint_t			bitval;
18774 	mib2_ipAddrEntry_t	mae;
18775 	zoneid_t		zoneid;
18776 	ill_walk_context_t ctx;
18777 
18778 	/*
18779 	 * make a copy of the original message
18780 	 */
18781 	mp2ctl = copymsg(mpctl);
18782 
18783 	/* ipAddrEntryTable */
18784 
18785 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18786 	optp->level = MIB2_IP;
18787 	optp->name = MIB2_IP_ADDR;
18788 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18789 
18790 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18791 	ill = ILL_START_WALK_V4(&ctx, ipst);
18792 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18793 		for (ipif = ill->ill_ipif; ipif != NULL;
18794 		    ipif = ipif->ipif_next) {
18795 			if (ipif->ipif_zoneid != zoneid &&
18796 			    ipif->ipif_zoneid != ALL_ZONES)
18797 				continue;
18798 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18799 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18800 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18801 
18802 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18803 			    OCTET_LENGTH);
18804 			mae.ipAdEntIfIndex.o_length =
18805 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18806 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18807 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18808 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18809 			mae.ipAdEntInfo.ae_subnet_len =
18810 			    ip_mask_to_plen(ipif->ipif_net_mask);
18811 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18812 			for (bitval = 1;
18813 			    bitval &&
18814 			    !(bitval & ipif->ipif_brd_addr);
18815 			    bitval <<= 1)
18816 				noop;
18817 			mae.ipAdEntBcastAddr = bitval;
18818 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18819 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18820 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18821 			mae.ipAdEntInfo.ae_broadcast_addr =
18822 			    ipif->ipif_brd_addr;
18823 			mae.ipAdEntInfo.ae_pp_dst_addr =
18824 			    ipif->ipif_pp_dst_addr;
18825 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18826 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18827 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18828 
18829 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18830 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18831 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18832 				    "allocate %u bytes\n",
18833 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18834 			}
18835 		}
18836 	}
18837 	rw_exit(&ipst->ips_ill_g_lock);
18838 
18839 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18840 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18841 	    (int)optp->level, (int)optp->name, (int)optp->len));
18842 	qreply(q, mpctl);
18843 	return (mp2ctl);
18844 }
18845 
18846 /* IPv6 address information */
18847 static mblk_t *
18848 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18849 {
18850 	struct opthdr		*optp;
18851 	mblk_t			*mp2ctl;
18852 	mblk_t			*mp_tail = NULL;
18853 	ill_t			*ill;
18854 	ipif_t			*ipif;
18855 	mib2_ipv6AddrEntry_t	mae6;
18856 	zoneid_t		zoneid;
18857 	ill_walk_context_t	ctx;
18858 
18859 	/*
18860 	 * make a copy of the original message
18861 	 */
18862 	mp2ctl = copymsg(mpctl);
18863 
18864 	/* ipv6AddrEntryTable */
18865 
18866 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18867 	optp->level = MIB2_IP6;
18868 	optp->name = MIB2_IP6_ADDR;
18869 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18870 
18871 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18872 	ill = ILL_START_WALK_V6(&ctx, ipst);
18873 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18874 		for (ipif = ill->ill_ipif; ipif != NULL;
18875 		    ipif = ipif->ipif_next) {
18876 			if (ipif->ipif_zoneid != zoneid &&
18877 			    ipif->ipif_zoneid != ALL_ZONES)
18878 				continue;
18879 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18880 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18881 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18882 
18883 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18884 			    OCTET_LENGTH);
18885 			mae6.ipv6AddrIfIndex.o_length =
18886 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18887 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18888 			mae6.ipv6AddrPfxLength =
18889 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18890 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18891 			mae6.ipv6AddrInfo.ae_subnet_len =
18892 			    mae6.ipv6AddrPfxLength;
18893 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18894 
18895 			/* Type: stateless(1), stateful(2), unknown(3) */
18896 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18897 				mae6.ipv6AddrType = 1;
18898 			else
18899 				mae6.ipv6AddrType = 2;
18900 			/* Anycast: true(1), false(2) */
18901 			if (ipif->ipif_flags & IPIF_ANYCAST)
18902 				mae6.ipv6AddrAnycastFlag = 1;
18903 			else
18904 				mae6.ipv6AddrAnycastFlag = 2;
18905 
18906 			/*
18907 			 * Address status: preferred(1), deprecated(2),
18908 			 * invalid(3), inaccessible(4), unknown(5)
18909 			 */
18910 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18911 				mae6.ipv6AddrStatus = 3;
18912 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18913 				mae6.ipv6AddrStatus = 2;
18914 			else
18915 				mae6.ipv6AddrStatus = 1;
18916 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18917 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18918 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18919 			    ipif->ipif_v6pp_dst_addr;
18920 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18921 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18922 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18923 			mae6.ipv6AddrIdentifier = ill->ill_token;
18924 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18925 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18926 			mae6.ipv6AddrRetransmitTime =
18927 			    ill->ill_reachable_retrans_time;
18928 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18929 			    (char *)&mae6,
18930 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18931 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18932 				    "allocate %u bytes\n",
18933 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18934 			}
18935 		}
18936 	}
18937 	rw_exit(&ipst->ips_ill_g_lock);
18938 
18939 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18940 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18941 	    (int)optp->level, (int)optp->name, (int)optp->len));
18942 	qreply(q, mpctl);
18943 	return (mp2ctl);
18944 }
18945 
18946 /* IPv4 multicast group membership. */
18947 static mblk_t *
18948 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18949 {
18950 	struct opthdr		*optp;
18951 	mblk_t			*mp2ctl;
18952 	ill_t			*ill;
18953 	ipif_t			*ipif;
18954 	ilm_t			*ilm;
18955 	ip_member_t		ipm;
18956 	mblk_t			*mp_tail = NULL;
18957 	ill_walk_context_t	ctx;
18958 	zoneid_t		zoneid;
18959 	ilm_walker_t		ilw;
18960 
18961 	/*
18962 	 * make a copy of the original message
18963 	 */
18964 	mp2ctl = copymsg(mpctl);
18965 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18966 
18967 	/* ipGroupMember table */
18968 	optp = (struct opthdr *)&mpctl->b_rptr[
18969 	    sizeof (struct T_optmgmt_ack)];
18970 	optp->level = MIB2_IP;
18971 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18972 
18973 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18974 	ill = ILL_START_WALK_V4(&ctx, ipst);
18975 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18976 		if (IS_UNDER_IPMP(ill))
18977 			continue;
18978 
18979 		ilm = ilm_walker_start(&ilw, ill);
18980 		for (ipif = ill->ill_ipif; ipif != NULL;
18981 		    ipif = ipif->ipif_next) {
18982 			if (ipif->ipif_zoneid != zoneid &&
18983 			    ipif->ipif_zoneid != ALL_ZONES)
18984 				continue;	/* not this zone */
18985 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18986 			    OCTET_LENGTH);
18987 			ipm.ipGroupMemberIfIndex.o_length =
18988 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18989 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18990 				ASSERT(ilm->ilm_ipif != NULL);
18991 				ASSERT(ilm->ilm_ill == NULL);
18992 				if (ilm->ilm_ipif != ipif)
18993 					continue;
18994 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18995 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18996 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18997 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18998 				    (char *)&ipm, (int)sizeof (ipm))) {
18999 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
19000 					    "failed to allocate %u bytes\n",
19001 					    (uint_t)sizeof (ipm)));
19002 				}
19003 			}
19004 		}
19005 		ilm_walker_finish(&ilw);
19006 	}
19007 	rw_exit(&ipst->ips_ill_g_lock);
19008 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19009 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19010 	    (int)optp->level, (int)optp->name, (int)optp->len));
19011 	qreply(q, mpctl);
19012 	return (mp2ctl);
19013 }
19014 
19015 /* IPv6 multicast group membership. */
19016 static mblk_t *
19017 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19018 {
19019 	struct opthdr		*optp;
19020 	mblk_t			*mp2ctl;
19021 	ill_t			*ill;
19022 	ilm_t			*ilm;
19023 	ipv6_member_t		ipm6;
19024 	mblk_t			*mp_tail = NULL;
19025 	ill_walk_context_t	ctx;
19026 	zoneid_t		zoneid;
19027 	ilm_walker_t		ilw;
19028 
19029 	/*
19030 	 * make a copy of the original message
19031 	 */
19032 	mp2ctl = copymsg(mpctl);
19033 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19034 
19035 	/* ip6GroupMember table */
19036 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19037 	optp->level = MIB2_IP6;
19038 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19039 
19040 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19041 	ill = ILL_START_WALK_V6(&ctx, ipst);
19042 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19043 		if (IS_UNDER_IPMP(ill))
19044 			continue;
19045 
19046 		ilm = ilm_walker_start(&ilw, ill);
19047 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19048 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19049 			ASSERT(ilm->ilm_ipif == NULL);
19050 			ASSERT(ilm->ilm_ill != NULL);
19051 			if (ilm->ilm_zoneid != zoneid)
19052 				continue;	/* not this zone */
19053 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19054 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19055 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19056 			if (!snmp_append_data2(mpctl->b_cont,
19057 			    &mp_tail,
19058 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19059 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19060 				    "failed to allocate %u bytes\n",
19061 				    (uint_t)sizeof (ipm6)));
19062 			}
19063 		}
19064 		ilm_walker_finish(&ilw);
19065 	}
19066 	rw_exit(&ipst->ips_ill_g_lock);
19067 
19068 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19069 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19070 	    (int)optp->level, (int)optp->name, (int)optp->len));
19071 	qreply(q, mpctl);
19072 	return (mp2ctl);
19073 }
19074 
19075 /* IP multicast filtered sources */
19076 static mblk_t *
19077 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19078 {
19079 	struct opthdr		*optp;
19080 	mblk_t			*mp2ctl;
19081 	ill_t			*ill;
19082 	ipif_t			*ipif;
19083 	ilm_t			*ilm;
19084 	ip_grpsrc_t		ips;
19085 	mblk_t			*mp_tail = NULL;
19086 	ill_walk_context_t	ctx;
19087 	zoneid_t		zoneid;
19088 	int			i;
19089 	slist_t			*sl;
19090 	ilm_walker_t		ilw;
19091 
19092 	/*
19093 	 * make a copy of the original message
19094 	 */
19095 	mp2ctl = copymsg(mpctl);
19096 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19097 
19098 	/* ipGroupSource table */
19099 	optp = (struct opthdr *)&mpctl->b_rptr[
19100 	    sizeof (struct T_optmgmt_ack)];
19101 	optp->level = MIB2_IP;
19102 	optp->name = EXPER_IP_GROUP_SOURCES;
19103 
19104 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19105 	ill = ILL_START_WALK_V4(&ctx, ipst);
19106 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19107 		if (IS_UNDER_IPMP(ill))
19108 			continue;
19109 
19110 		ilm = ilm_walker_start(&ilw, ill);
19111 		for (ipif = ill->ill_ipif; ipif != NULL;
19112 		    ipif = ipif->ipif_next) {
19113 			if (ipif->ipif_zoneid != zoneid)
19114 				continue;	/* not this zone */
19115 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19116 			    OCTET_LENGTH);
19117 			ips.ipGroupSourceIfIndex.o_length =
19118 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19119 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19120 				ASSERT(ilm->ilm_ipif != NULL);
19121 				ASSERT(ilm->ilm_ill == NULL);
19122 				sl = ilm->ilm_filter;
19123 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19124 					continue;
19125 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19126 				for (i = 0; i < sl->sl_numsrc; i++) {
19127 					if (!IN6_IS_ADDR_V4MAPPED(
19128 					    &sl->sl_addr[i]))
19129 						continue;
19130 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19131 					    ips.ipGroupSourceAddress);
19132 					if (snmp_append_data2(mpctl->b_cont,
19133 					    &mp_tail, (char *)&ips,
19134 					    (int)sizeof (ips)) == 0) {
19135 						ip1dbg(("ip_snmp_get_mib2_"
19136 						    "ip_group_src: failed to "
19137 						    "allocate %u bytes\n",
19138 						    (uint_t)sizeof (ips)));
19139 					}
19140 				}
19141 			}
19142 		}
19143 		ilm_walker_finish(&ilw);
19144 	}
19145 	rw_exit(&ipst->ips_ill_g_lock);
19146 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19147 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19148 	    (int)optp->level, (int)optp->name, (int)optp->len));
19149 	qreply(q, mpctl);
19150 	return (mp2ctl);
19151 }
19152 
19153 /* IPv6 multicast filtered sources. */
19154 static mblk_t *
19155 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19156 {
19157 	struct opthdr		*optp;
19158 	mblk_t			*mp2ctl;
19159 	ill_t			*ill;
19160 	ilm_t			*ilm;
19161 	ipv6_grpsrc_t		ips6;
19162 	mblk_t			*mp_tail = NULL;
19163 	ill_walk_context_t	ctx;
19164 	zoneid_t		zoneid;
19165 	int			i;
19166 	slist_t			*sl;
19167 	ilm_walker_t		ilw;
19168 
19169 	/*
19170 	 * make a copy of the original message
19171 	 */
19172 	mp2ctl = copymsg(mpctl);
19173 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19174 
19175 	/* ip6GroupMember table */
19176 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19177 	optp->level = MIB2_IP6;
19178 	optp->name = EXPER_IP6_GROUP_SOURCES;
19179 
19180 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19181 	ill = ILL_START_WALK_V6(&ctx, ipst);
19182 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19183 		if (IS_UNDER_IPMP(ill))
19184 			continue;
19185 
19186 		ilm = ilm_walker_start(&ilw, ill);
19187 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19188 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19189 			ASSERT(ilm->ilm_ipif == NULL);
19190 			ASSERT(ilm->ilm_ill != NULL);
19191 			sl = ilm->ilm_filter;
19192 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19193 				continue;
19194 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19195 			for (i = 0; i < sl->sl_numsrc; i++) {
19196 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19197 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19198 				    (char *)&ips6, (int)sizeof (ips6))) {
19199 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19200 					    "group_src: failed to allocate "
19201 					    "%u bytes\n",
19202 					    (uint_t)sizeof (ips6)));
19203 				}
19204 			}
19205 		}
19206 		ilm_walker_finish(&ilw);
19207 	}
19208 	rw_exit(&ipst->ips_ill_g_lock);
19209 
19210 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19211 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19212 	    (int)optp->level, (int)optp->name, (int)optp->len));
19213 	qreply(q, mpctl);
19214 	return (mp2ctl);
19215 }
19216 
19217 /* Multicast routing virtual interface table. */
19218 static mblk_t *
19219 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19220 {
19221 	struct opthdr		*optp;
19222 	mblk_t			*mp2ctl;
19223 
19224 	/*
19225 	 * make a copy of the original message
19226 	 */
19227 	mp2ctl = copymsg(mpctl);
19228 
19229 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19230 	optp->level = EXPER_DVMRP;
19231 	optp->name = EXPER_DVMRP_VIF;
19232 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19233 		ip0dbg(("ip_mroute_vif: failed\n"));
19234 	}
19235 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19236 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19237 	    (int)optp->level, (int)optp->name, (int)optp->len));
19238 	qreply(q, mpctl);
19239 	return (mp2ctl);
19240 }
19241 
19242 /* Multicast routing table. */
19243 static mblk_t *
19244 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19245 {
19246 	struct opthdr		*optp;
19247 	mblk_t			*mp2ctl;
19248 
19249 	/*
19250 	 * make a copy of the original message
19251 	 */
19252 	mp2ctl = copymsg(mpctl);
19253 
19254 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19255 	optp->level = EXPER_DVMRP;
19256 	optp->name = EXPER_DVMRP_MRT;
19257 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19258 		ip0dbg(("ip_mroute_mrt: failed\n"));
19259 	}
19260 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19261 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19262 	    (int)optp->level, (int)optp->name, (int)optp->len));
19263 	qreply(q, mpctl);
19264 	return (mp2ctl);
19265 }
19266 
19267 /*
19268  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19269  * in one IRE walk.
19270  */
19271 static mblk_t *
19272 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19273     ip_stack_t *ipst)
19274 {
19275 	struct opthdr	*optp;
19276 	mblk_t		*mp2ctl;	/* Returned */
19277 	mblk_t		*mp3ctl;	/* nettomedia */
19278 	mblk_t		*mp4ctl;	/* routeattrs */
19279 	iproutedata_t	ird;
19280 	zoneid_t	zoneid;
19281 
19282 	/*
19283 	 * make copies of the original message
19284 	 *	- mp2ctl is returned unchanged to the caller for his use
19285 	 *	- mpctl is sent upstream as ipRouteEntryTable
19286 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19287 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19288 	 */
19289 	mp2ctl = copymsg(mpctl);
19290 	mp3ctl = copymsg(mpctl);
19291 	mp4ctl = copymsg(mpctl);
19292 	if (mp3ctl == NULL || mp4ctl == NULL) {
19293 		freemsg(mp4ctl);
19294 		freemsg(mp3ctl);
19295 		freemsg(mp2ctl);
19296 		freemsg(mpctl);
19297 		return (NULL);
19298 	}
19299 
19300 	bzero(&ird, sizeof (ird));
19301 
19302 	ird.ird_route.lp_head = mpctl->b_cont;
19303 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19304 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19305 	/*
19306 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19307 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19308 	 * intended a temporary solution until a proper MIB API is provided
19309 	 * that provides complete filtering/caller-opt-in.
19310 	 */
19311 	if (level == EXPER_IP_AND_TESTHIDDEN)
19312 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19313 
19314 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19315 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19316 
19317 	/* ipRouteEntryTable in mpctl */
19318 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19319 	optp->level = MIB2_IP;
19320 	optp->name = MIB2_IP_ROUTE;
19321 	optp->len = msgdsize(ird.ird_route.lp_head);
19322 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19323 	    (int)optp->level, (int)optp->name, (int)optp->len));
19324 	qreply(q, mpctl);
19325 
19326 	/* ipNetToMediaEntryTable in mp3ctl */
19327 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19328 	optp->level = MIB2_IP;
19329 	optp->name = MIB2_IP_MEDIA;
19330 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19331 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19332 	    (int)optp->level, (int)optp->name, (int)optp->len));
19333 	qreply(q, mp3ctl);
19334 
19335 	/* ipRouteAttributeTable in mp4ctl */
19336 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19337 	optp->level = MIB2_IP;
19338 	optp->name = EXPER_IP_RTATTR;
19339 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19340 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19341 	    (int)optp->level, (int)optp->name, (int)optp->len));
19342 	if (optp->len == 0)
19343 		freemsg(mp4ctl);
19344 	else
19345 		qreply(q, mp4ctl);
19346 
19347 	return (mp2ctl);
19348 }
19349 
19350 /*
19351  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19352  * ipv6NetToMediaEntryTable in an NDP walk.
19353  */
19354 static mblk_t *
19355 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19356     ip_stack_t *ipst)
19357 {
19358 	struct opthdr	*optp;
19359 	mblk_t		*mp2ctl;	/* Returned */
19360 	mblk_t		*mp3ctl;	/* nettomedia */
19361 	mblk_t		*mp4ctl;	/* routeattrs */
19362 	iproutedata_t	ird;
19363 	zoneid_t	zoneid;
19364 
19365 	/*
19366 	 * make copies of the original message
19367 	 *	- mp2ctl is returned unchanged to the caller for his use
19368 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19369 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19370 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19371 	 */
19372 	mp2ctl = copymsg(mpctl);
19373 	mp3ctl = copymsg(mpctl);
19374 	mp4ctl = copymsg(mpctl);
19375 	if (mp3ctl == NULL || mp4ctl == NULL) {
19376 		freemsg(mp4ctl);
19377 		freemsg(mp3ctl);
19378 		freemsg(mp2ctl);
19379 		freemsg(mpctl);
19380 		return (NULL);
19381 	}
19382 
19383 	bzero(&ird, sizeof (ird));
19384 
19385 	ird.ird_route.lp_head = mpctl->b_cont;
19386 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19387 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19388 	/*
19389 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19390 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19391 	 * intended a temporary solution until a proper MIB API is provided
19392 	 * that provides complete filtering/caller-opt-in.
19393 	 */
19394 	if (level == EXPER_IP_AND_TESTHIDDEN)
19395 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19396 
19397 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19398 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19399 
19400 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19401 	optp->level = MIB2_IP6;
19402 	optp->name = MIB2_IP6_ROUTE;
19403 	optp->len = msgdsize(ird.ird_route.lp_head);
19404 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19405 	    (int)optp->level, (int)optp->name, (int)optp->len));
19406 	qreply(q, mpctl);
19407 
19408 	/* ipv6NetToMediaEntryTable in mp3ctl */
19409 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19410 
19411 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19412 	optp->level = MIB2_IP6;
19413 	optp->name = MIB2_IP6_MEDIA;
19414 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19415 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19416 	    (int)optp->level, (int)optp->name, (int)optp->len));
19417 	qreply(q, mp3ctl);
19418 
19419 	/* ipv6RouteAttributeTable in mp4ctl */
19420 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19421 	optp->level = MIB2_IP6;
19422 	optp->name = EXPER_IP_RTATTR;
19423 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19424 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19425 	    (int)optp->level, (int)optp->name, (int)optp->len));
19426 	if (optp->len == 0)
19427 		freemsg(mp4ctl);
19428 	else
19429 		qreply(q, mp4ctl);
19430 
19431 	return (mp2ctl);
19432 }
19433 
19434 /*
19435  * IPv6 mib: One per ill
19436  */
19437 static mblk_t *
19438 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19439 {
19440 	struct opthdr		*optp;
19441 	mblk_t			*mp2ctl;
19442 	ill_t			*ill;
19443 	ill_walk_context_t	ctx;
19444 	mblk_t			*mp_tail = NULL;
19445 
19446 	/*
19447 	 * Make a copy of the original message
19448 	 */
19449 	mp2ctl = copymsg(mpctl);
19450 
19451 	/* fixed length IPv6 structure ... */
19452 
19453 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19454 	optp->level = MIB2_IP6;
19455 	optp->name = 0;
19456 	/* Include "unknown interface" ip6_mib */
19457 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19458 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19459 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19460 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19461 	    ipst->ips_ipv6_forward ? 1 : 2);
19462 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19463 	    ipst->ips_ipv6_def_hops);
19464 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19465 	    sizeof (mib2_ipIfStatsEntry_t));
19466 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19467 	    sizeof (mib2_ipv6AddrEntry_t));
19468 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19469 	    sizeof (mib2_ipv6RouteEntry_t));
19470 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19471 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19472 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19473 	    sizeof (ipv6_member_t));
19474 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19475 	    sizeof (ipv6_grpsrc_t));
19476 
19477 	/*
19478 	 * Synchronize 64- and 32-bit counters
19479 	 */
19480 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19481 	    ipIfStatsHCInReceives);
19482 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19483 	    ipIfStatsHCInDelivers);
19484 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19485 	    ipIfStatsHCOutRequests);
19486 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19487 	    ipIfStatsHCOutForwDatagrams);
19488 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19489 	    ipIfStatsHCOutMcastPkts);
19490 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19491 	    ipIfStatsHCInMcastPkts);
19492 
19493 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19494 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19495 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19496 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19497 	}
19498 
19499 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19500 	ill = ILL_START_WALK_V6(&ctx, ipst);
19501 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19502 		ill->ill_ip_mib->ipIfStatsIfIndex =
19503 		    ill->ill_phyint->phyint_ifindex;
19504 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19505 		    ipst->ips_ipv6_forward ? 1 : 2);
19506 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19507 		    ill->ill_max_hops);
19508 
19509 		/*
19510 		 * Synchronize 64- and 32-bit counters
19511 		 */
19512 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19513 		    ipIfStatsHCInReceives);
19514 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19515 		    ipIfStatsHCInDelivers);
19516 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19517 		    ipIfStatsHCOutRequests);
19518 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19519 		    ipIfStatsHCOutForwDatagrams);
19520 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19521 		    ipIfStatsHCOutMcastPkts);
19522 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19523 		    ipIfStatsHCInMcastPkts);
19524 
19525 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19526 		    (char *)ill->ill_ip_mib,
19527 		    (int)sizeof (*ill->ill_ip_mib))) {
19528 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19529 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19530 		}
19531 	}
19532 	rw_exit(&ipst->ips_ill_g_lock);
19533 
19534 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19535 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19536 	    (int)optp->level, (int)optp->name, (int)optp->len));
19537 	qreply(q, mpctl);
19538 	return (mp2ctl);
19539 }
19540 
19541 /*
19542  * ICMPv6 mib: One per ill
19543  */
19544 static mblk_t *
19545 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19546 {
19547 	struct opthdr		*optp;
19548 	mblk_t			*mp2ctl;
19549 	ill_t			*ill;
19550 	ill_walk_context_t	ctx;
19551 	mblk_t			*mp_tail = NULL;
19552 	/*
19553 	 * Make a copy of the original message
19554 	 */
19555 	mp2ctl = copymsg(mpctl);
19556 
19557 	/* fixed length ICMPv6 structure ... */
19558 
19559 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19560 	optp->level = MIB2_ICMP6;
19561 	optp->name = 0;
19562 	/* Include "unknown interface" icmp6_mib */
19563 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19564 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19565 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19566 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19567 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19568 	    (char *)&ipst->ips_icmp6_mib,
19569 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19570 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19571 		    (uint_t)sizeof (ipst->ips_icmp6_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_icmp6_mib->ipv6IfIcmpIfIndex =
19578 		    ill->ill_phyint->phyint_ifindex;
19579 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19580 		    (char *)ill->ill_icmp6_mib,
19581 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19582 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19583 			    "%u bytes\n",
19584 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19585 		}
19586 	}
19587 	rw_exit(&ipst->ips_ill_g_lock);
19588 
19589 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19590 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19591 	    (int)optp->level, (int)optp->name, (int)optp->len));
19592 	qreply(q, mpctl);
19593 	return (mp2ctl);
19594 }
19595 
19596 /*
19597  * ire_walk routine to create both ipRouteEntryTable and
19598  * ipRouteAttributeTable in one IRE walk
19599  */
19600 static void
19601 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19602 {
19603 	ill_t				*ill;
19604 	ipif_t				*ipif;
19605 	mib2_ipRouteEntry_t		*re;
19606 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19607 	ipaddr_t			gw_addr;
19608 	tsol_ire_gw_secattr_t		*attrp;
19609 	tsol_gc_t			*gc = NULL;
19610 	tsol_gcgrp_t			*gcgrp = NULL;
19611 	uint_t				sacnt = 0;
19612 	int				i;
19613 
19614 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19615 
19616 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19617 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19618 		return;
19619 	}
19620 
19621 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19622 		return;
19623 
19624 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19625 		mutex_enter(&attrp->igsa_lock);
19626 		if ((gc = attrp->igsa_gc) != NULL) {
19627 			gcgrp = gc->gc_grp;
19628 			ASSERT(gcgrp != NULL);
19629 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19630 			sacnt = 1;
19631 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19632 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19633 			gc = gcgrp->gcgrp_head;
19634 			sacnt = gcgrp->gcgrp_count;
19635 		}
19636 		mutex_exit(&attrp->igsa_lock);
19637 
19638 		/* do nothing if there's no gc to report */
19639 		if (gc == NULL) {
19640 			ASSERT(sacnt == 0);
19641 			if (gcgrp != NULL) {
19642 				/* we might as well drop the lock now */
19643 				rw_exit(&gcgrp->gcgrp_rwlock);
19644 				gcgrp = NULL;
19645 			}
19646 			attrp = NULL;
19647 		}
19648 
19649 		ASSERT(gc == NULL || (gcgrp != NULL &&
19650 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19651 	}
19652 	ASSERT(sacnt == 0 || gc != NULL);
19653 
19654 	if (sacnt != 0 &&
19655 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19656 		kmem_free(re, sizeof (*re));
19657 		rw_exit(&gcgrp->gcgrp_rwlock);
19658 		return;
19659 	}
19660 
19661 	/*
19662 	 * Return all IRE types for route table... let caller pick and choose
19663 	 */
19664 	re->ipRouteDest = ire->ire_addr;
19665 	ipif = ire->ire_ipif;
19666 	re->ipRouteIfIndex.o_length = 0;
19667 	if (ire->ire_type == IRE_CACHE) {
19668 		ill = (ill_t *)ire->ire_stq->q_ptr;
19669 		re->ipRouteIfIndex.o_length =
19670 		    ill->ill_name_length == 0 ? 0 :
19671 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19672 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19673 		    re->ipRouteIfIndex.o_length);
19674 	} else if (ipif != NULL) {
19675 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19676 		re->ipRouteIfIndex.o_length =
19677 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19678 	}
19679 	re->ipRouteMetric1 = -1;
19680 	re->ipRouteMetric2 = -1;
19681 	re->ipRouteMetric3 = -1;
19682 	re->ipRouteMetric4 = -1;
19683 
19684 	gw_addr = ire->ire_gateway_addr;
19685 
19686 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19687 		re->ipRouteNextHop = ire->ire_src_addr;
19688 	else
19689 		re->ipRouteNextHop = gw_addr;
19690 	/* indirect(4), direct(3), or invalid(2) */
19691 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19692 		re->ipRouteType = 2;
19693 	else
19694 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19695 	re->ipRouteProto = -1;
19696 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19697 	re->ipRouteMask = ire->ire_mask;
19698 	re->ipRouteMetric5 = -1;
19699 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19700 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19701 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19702 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19703 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19704 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19705 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19706 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19707 
19708 	if (ire->ire_flags & RTF_DYNAMIC) {
19709 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19710 	} else {
19711 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19712 	}
19713 
19714 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19715 	    (char *)re, (int)sizeof (*re))) {
19716 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19717 		    (uint_t)sizeof (*re)));
19718 	}
19719 
19720 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19721 		iaeptr->iae_routeidx = ird->ird_idx;
19722 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19723 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19724 	}
19725 
19726 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19727 	    (char *)iae, sacnt * sizeof (*iae))) {
19728 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19729 		    (unsigned)(sacnt * sizeof (*iae))));
19730 	}
19731 
19732 	/* bump route index for next pass */
19733 	ird->ird_idx++;
19734 
19735 	kmem_free(re, sizeof (*re));
19736 	if (sacnt != 0)
19737 		kmem_free(iae, sacnt * sizeof (*iae));
19738 
19739 	if (gcgrp != NULL)
19740 		rw_exit(&gcgrp->gcgrp_rwlock);
19741 }
19742 
19743 /*
19744  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19745  */
19746 static void
19747 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19748 {
19749 	ill_t				*ill;
19750 	ipif_t				*ipif;
19751 	mib2_ipv6RouteEntry_t		*re;
19752 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19753 	in6_addr_t			gw_addr_v6;
19754 	tsol_ire_gw_secattr_t		*attrp;
19755 	tsol_gc_t			*gc = NULL;
19756 	tsol_gcgrp_t			*gcgrp = NULL;
19757 	uint_t				sacnt = 0;
19758 	int				i;
19759 
19760 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19761 
19762 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19763 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19764 		return;
19765 	}
19766 
19767 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19768 		return;
19769 
19770 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19771 		mutex_enter(&attrp->igsa_lock);
19772 		if ((gc = attrp->igsa_gc) != NULL) {
19773 			gcgrp = gc->gc_grp;
19774 			ASSERT(gcgrp != NULL);
19775 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19776 			sacnt = 1;
19777 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19778 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19779 			gc = gcgrp->gcgrp_head;
19780 			sacnt = gcgrp->gcgrp_count;
19781 		}
19782 		mutex_exit(&attrp->igsa_lock);
19783 
19784 		/* do nothing if there's no gc to report */
19785 		if (gc == NULL) {
19786 			ASSERT(sacnt == 0);
19787 			if (gcgrp != NULL) {
19788 				/* we might as well drop the lock now */
19789 				rw_exit(&gcgrp->gcgrp_rwlock);
19790 				gcgrp = NULL;
19791 			}
19792 			attrp = NULL;
19793 		}
19794 
19795 		ASSERT(gc == NULL || (gcgrp != NULL &&
19796 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19797 	}
19798 	ASSERT(sacnt == 0 || gc != NULL);
19799 
19800 	if (sacnt != 0 &&
19801 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19802 		kmem_free(re, sizeof (*re));
19803 		rw_exit(&gcgrp->gcgrp_rwlock);
19804 		return;
19805 	}
19806 
19807 	/*
19808 	 * Return all IRE types for route table... let caller pick and choose
19809 	 */
19810 	re->ipv6RouteDest = ire->ire_addr_v6;
19811 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19812 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19813 	re->ipv6RouteIfIndex.o_length = 0;
19814 	ipif = ire->ire_ipif;
19815 	if (ire->ire_type == IRE_CACHE) {
19816 		ill = (ill_t *)ire->ire_stq->q_ptr;
19817 		re->ipv6RouteIfIndex.o_length =
19818 		    ill->ill_name_length == 0 ? 0 :
19819 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19820 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19821 		    re->ipv6RouteIfIndex.o_length);
19822 	} else if (ipif != NULL) {
19823 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19824 		re->ipv6RouteIfIndex.o_length =
19825 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19826 	}
19827 
19828 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19829 
19830 	mutex_enter(&ire->ire_lock);
19831 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19832 	mutex_exit(&ire->ire_lock);
19833 
19834 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19835 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19836 	else
19837 		re->ipv6RouteNextHop = gw_addr_v6;
19838 
19839 	/* remote(4), local(3), or discard(2) */
19840 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19841 		re->ipv6RouteType = 2;
19842 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19843 		re->ipv6RouteType = 3;
19844 	else
19845 		re->ipv6RouteType = 4;
19846 
19847 	re->ipv6RouteProtocol	= -1;
19848 	re->ipv6RoutePolicy	= 0;
19849 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19850 	re->ipv6RouteNextHopRDI	= 0;
19851 	re->ipv6RouteWeight	= 0;
19852 	re->ipv6RouteMetric	= 0;
19853 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19854 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19855 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19856 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19857 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19858 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19859 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19860 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19861 
19862 	if (ire->ire_flags & RTF_DYNAMIC) {
19863 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19864 	} else {
19865 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19866 	}
19867 
19868 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19869 	    (char *)re, (int)sizeof (*re))) {
19870 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19871 		    (uint_t)sizeof (*re)));
19872 	}
19873 
19874 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19875 		iaeptr->iae_routeidx = ird->ird_idx;
19876 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19877 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19878 	}
19879 
19880 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19881 	    (char *)iae, sacnt * sizeof (*iae))) {
19882 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19883 		    (unsigned)(sacnt * sizeof (*iae))));
19884 	}
19885 
19886 	/* bump route index for next pass */
19887 	ird->ird_idx++;
19888 
19889 	kmem_free(re, sizeof (*re));
19890 	if (sacnt != 0)
19891 		kmem_free(iae, sacnt * sizeof (*iae));
19892 
19893 	if (gcgrp != NULL)
19894 		rw_exit(&gcgrp->gcgrp_rwlock);
19895 }
19896 
19897 /*
19898  * ndp_walk routine to create ipv6NetToMediaEntryTable
19899  */
19900 static int
19901 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19902 {
19903 	ill_t				*ill;
19904 	mib2_ipv6NetToMediaEntry_t	ntme;
19905 	dl_unitdata_req_t		*dl;
19906 
19907 	ill = nce->nce_ill;
19908 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19909 		return (0);
19910 
19911 	/*
19912 	 * Neighbor cache entry attached to IRE with on-link
19913 	 * destination.
19914 	 */
19915 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19916 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19917 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19918 	    (nce->nce_res_mp != NULL)) {
19919 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19920 		ntme.ipv6NetToMediaPhysAddress.o_length =
19921 		    dl->dl_dest_addr_length;
19922 	} else {
19923 		ntme.ipv6NetToMediaPhysAddress.o_length =
19924 		    ill->ill_phys_addr_length;
19925 	}
19926 	if (nce->nce_res_mp != NULL) {
19927 		bcopy((char *)nce->nce_res_mp->b_rptr +
19928 		    NCE_LL_ADDR_OFFSET(ill),
19929 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19930 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19931 	} else {
19932 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19933 		    ill->ill_phys_addr_length);
19934 	}
19935 	/*
19936 	 * Note: Returns ND_* states. Should be:
19937 	 * reachable(1), stale(2), delay(3), probe(4),
19938 	 * invalid(5), unknown(6)
19939 	 */
19940 	ntme.ipv6NetToMediaState = nce->nce_state;
19941 	ntme.ipv6NetToMediaLastUpdated = 0;
19942 
19943 	/* other(1), dynamic(2), static(3), local(4) */
19944 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19945 		ntme.ipv6NetToMediaType = 4;
19946 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19947 		ntme.ipv6NetToMediaType = 1;
19948 	} else {
19949 		ntme.ipv6NetToMediaType = 2;
19950 	}
19951 
19952 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19953 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19954 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19955 		    (uint_t)sizeof (ntme)));
19956 	}
19957 	return (0);
19958 }
19959 
19960 /*
19961  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19962  */
19963 /* ARGSUSED */
19964 int
19965 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19966 {
19967 	switch (level) {
19968 	case MIB2_IP:
19969 	case MIB2_ICMP:
19970 		switch (name) {
19971 		default:
19972 			break;
19973 		}
19974 		return (1);
19975 	default:
19976 		return (1);
19977 	}
19978 }
19979 
19980 /*
19981  * When there exists both a 64- and 32-bit counter of a particular type
19982  * (i.e., InReceives), only the 64-bit counters are added.
19983  */
19984 void
19985 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19986 {
19987 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19988 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19989 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19990 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19991 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19992 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19993 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19994 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19995 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19996 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19997 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19998 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19999 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
20000 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
20001 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
20002 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
20003 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
20004 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
20005 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
20006 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
20007 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20008 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20009 	    o2->ipIfStatsInWrongIPVersion);
20010 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20011 	    o2->ipIfStatsInWrongIPVersion);
20012 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20013 	    o2->ipIfStatsOutSwitchIPVersion);
20014 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20015 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20016 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20017 	    o2->ipIfStatsHCInForwDatagrams);
20018 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20019 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20020 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20021 	    o2->ipIfStatsHCOutForwDatagrams);
20022 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20023 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20024 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20025 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20026 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20027 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20028 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20029 	    o2->ipIfStatsHCOutMcastOctets);
20030 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20031 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20032 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20033 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20034 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20035 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20036 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20037 }
20038 
20039 void
20040 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20041 {
20042 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20043 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20044 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20045 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20046 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20047 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20048 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20049 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20050 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20051 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20052 	    o2->ipv6IfIcmpInRouterSolicits);
20053 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20054 	    o2->ipv6IfIcmpInRouterAdvertisements);
20055 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20056 	    o2->ipv6IfIcmpInNeighborSolicits);
20057 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20058 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20059 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20060 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20061 	    o2->ipv6IfIcmpInGroupMembQueries);
20062 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20063 	    o2->ipv6IfIcmpInGroupMembResponses);
20064 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20065 	    o2->ipv6IfIcmpInGroupMembReductions);
20066 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20067 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20068 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20069 	    o2->ipv6IfIcmpOutDestUnreachs);
20070 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20071 	    o2->ipv6IfIcmpOutAdminProhibs);
20072 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20073 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20074 	    o2->ipv6IfIcmpOutParmProblems);
20075 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20076 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20077 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20078 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20079 	    o2->ipv6IfIcmpOutRouterSolicits);
20080 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20081 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20082 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20083 	    o2->ipv6IfIcmpOutNeighborSolicits);
20084 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20085 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20086 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20087 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20088 	    o2->ipv6IfIcmpOutGroupMembQueries);
20089 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20090 	    o2->ipv6IfIcmpOutGroupMembResponses);
20091 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20092 	    o2->ipv6IfIcmpOutGroupMembReductions);
20093 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20094 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20095 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20096 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20097 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20098 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20099 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20100 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20101 	    o2->ipv6IfIcmpInGroupMembTotal);
20102 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20103 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20104 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20105 	    o2->ipv6IfIcmpInGroupMembBadReports);
20106 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20107 	    o2->ipv6IfIcmpInGroupMembOurReports);
20108 }
20109 
20110 /*
20111  * Called before the options are updated to check if this packet will
20112  * be source routed from here.
20113  * This routine assumes that the options are well formed i.e. that they
20114  * have already been checked.
20115  */
20116 static boolean_t
20117 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20118 {
20119 	ipoptp_t	opts;
20120 	uchar_t		*opt;
20121 	uint8_t		optval;
20122 	uint8_t		optlen;
20123 	ipaddr_t	dst;
20124 	ire_t		*ire;
20125 
20126 	if (IS_SIMPLE_IPH(ipha)) {
20127 		ip2dbg(("not source routed\n"));
20128 		return (B_FALSE);
20129 	}
20130 	dst = ipha->ipha_dst;
20131 	for (optval = ipoptp_first(&opts, ipha);
20132 	    optval != IPOPT_EOL;
20133 	    optval = ipoptp_next(&opts)) {
20134 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20135 		opt = opts.ipoptp_cur;
20136 		optlen = opts.ipoptp_len;
20137 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20138 		    optval, optlen));
20139 		switch (optval) {
20140 			uint32_t off;
20141 		case IPOPT_SSRR:
20142 		case IPOPT_LSRR:
20143 			/*
20144 			 * If dst is one of our addresses and there are some
20145 			 * entries left in the source route return (true).
20146 			 */
20147 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20148 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20149 			if (ire == NULL) {
20150 				ip2dbg(("ip_source_routed: not next"
20151 				    " source route 0x%x\n",
20152 				    ntohl(dst)));
20153 				return (B_FALSE);
20154 			}
20155 			ire_refrele(ire);
20156 			off = opt[IPOPT_OFFSET];
20157 			off--;
20158 			if (optlen < IP_ADDR_LEN ||
20159 			    off > optlen - IP_ADDR_LEN) {
20160 				/* End of source route */
20161 				ip1dbg(("ip_source_routed: end of SR\n"));
20162 				return (B_FALSE);
20163 			}
20164 			return (B_TRUE);
20165 		}
20166 	}
20167 	ip2dbg(("not source routed\n"));
20168 	return (B_FALSE);
20169 }
20170 
20171 /*
20172  * Check if the packet contains any source route.
20173  */
20174 static boolean_t
20175 ip_source_route_included(ipha_t *ipha)
20176 {
20177 	ipoptp_t	opts;
20178 	uint8_t		optval;
20179 
20180 	if (IS_SIMPLE_IPH(ipha))
20181 		return (B_FALSE);
20182 	for (optval = ipoptp_first(&opts, ipha);
20183 	    optval != IPOPT_EOL;
20184 	    optval = ipoptp_next(&opts)) {
20185 		switch (optval) {
20186 		case IPOPT_SSRR:
20187 		case IPOPT_LSRR:
20188 			return (B_TRUE);
20189 		}
20190 	}
20191 	return (B_FALSE);
20192 }
20193 
20194 /*
20195  * Called when the IRE expiration timer fires.
20196  */
20197 void
20198 ip_trash_timer_expire(void *args)
20199 {
20200 	int			flush_flag = 0;
20201 	ire_expire_arg_t	iea;
20202 	ip_stack_t		*ipst = (ip_stack_t *)args;
20203 
20204 	iea.iea_ipst = ipst;	/* No netstack_hold */
20205 
20206 	/*
20207 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20208 	 * This lock makes sure that a new invocation of this function
20209 	 * that occurs due to an almost immediate timer firing will not
20210 	 * progress beyond this point until the current invocation is done
20211 	 */
20212 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20213 	ipst->ips_ip_ire_expire_id = 0;
20214 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20215 
20216 	/* Periodic timer */
20217 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20218 	    ipst->ips_ip_ire_arp_interval) {
20219 		/*
20220 		 * Remove all IRE_CACHE entries since they might
20221 		 * contain arp information.
20222 		 */
20223 		flush_flag |= FLUSH_ARP_TIME;
20224 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20225 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20226 	}
20227 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20228 	    ipst->ips_ip_ire_redir_interval) {
20229 		/* Remove all redirects */
20230 		flush_flag |= FLUSH_REDIRECT_TIME;
20231 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20232 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20233 	}
20234 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20235 	    ipst->ips_ip_ire_pathmtu_interval) {
20236 		/* Increase path mtu */
20237 		flush_flag |= FLUSH_MTU_TIME;
20238 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20239 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20240 	}
20241 
20242 	/*
20243 	 * Optimize for the case when there are no redirects in the
20244 	 * ftable, that is, no need to walk the ftable in that case.
20245 	 */
20246 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20247 		iea.iea_flush_flag = flush_flag;
20248 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20249 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20250 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20251 		    NULL, ALL_ZONES, ipst);
20252 	}
20253 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20254 	    ipst->ips_ip_redirect_cnt > 0) {
20255 		iea.iea_flush_flag = flush_flag;
20256 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20257 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20258 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20259 	}
20260 	if (flush_flag & FLUSH_MTU_TIME) {
20261 		/*
20262 		 * Walk all IPv6 IRE's and update them
20263 		 * Note that ARP and redirect timers are not
20264 		 * needed since NUD handles stale entries.
20265 		 */
20266 		flush_flag = FLUSH_MTU_TIME;
20267 		iea.iea_flush_flag = flush_flag;
20268 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20269 		    ALL_ZONES, ipst);
20270 	}
20271 
20272 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20273 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20274 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20275 
20276 	/*
20277 	 * Hold the lock to serialize timeout calls and prevent
20278 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20279 	 * for the timer to fire and a new invocation of this function
20280 	 * to start before the return value of timeout has been stored
20281 	 * in ip_ire_expire_id by the current invocation.
20282 	 */
20283 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20284 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20285 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20286 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20287 }
20288 
20289 /*
20290  * Called by the memory allocator subsystem directly, when the system
20291  * is running low on memory.
20292  */
20293 /* ARGSUSED */
20294 void
20295 ip_trash_ire_reclaim(void *args)
20296 {
20297 	netstack_handle_t nh;
20298 	netstack_t *ns;
20299 
20300 	netstack_next_init(&nh);
20301 	while ((ns = netstack_next(&nh)) != NULL) {
20302 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20303 		netstack_rele(ns);
20304 	}
20305 	netstack_next_fini(&nh);
20306 }
20307 
20308 static void
20309 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20310 {
20311 	ire_cache_count_t icc;
20312 	ire_cache_reclaim_t icr;
20313 	ncc_cache_count_t ncc;
20314 	nce_cache_reclaim_t ncr;
20315 	uint_t delete_cnt;
20316 	/*
20317 	 * Memory reclaim call back.
20318 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20319 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20320 	 * entries, determine what fraction to free for
20321 	 * each category of IRE_CACHE entries giving absolute priority
20322 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20323 	 * entry will be freed unless all offlink entries are freed).
20324 	 */
20325 	icc.icc_total = 0;
20326 	icc.icc_unused = 0;
20327 	icc.icc_offlink = 0;
20328 	icc.icc_pmtu = 0;
20329 	icc.icc_onlink = 0;
20330 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20331 
20332 	/*
20333 	 * Free NCEs for IPv6 like the onlink ires.
20334 	 */
20335 	ncc.ncc_total = 0;
20336 	ncc.ncc_host = 0;
20337 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20338 
20339 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20340 	    icc.icc_pmtu + icc.icc_onlink);
20341 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20342 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20343 	if (delete_cnt == 0)
20344 		return;
20345 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20346 	/* Always delete all unused offlink entries */
20347 	icr.icr_ipst = ipst;
20348 	icr.icr_unused = 1;
20349 	if (delete_cnt <= icc.icc_unused) {
20350 		/*
20351 		 * Only need to free unused entries.  In other words,
20352 		 * there are enough unused entries to free to meet our
20353 		 * target number of freed ire cache entries.
20354 		 */
20355 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20356 		ncr.ncr_host = 0;
20357 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20358 		/*
20359 		 * Only need to free unused entries, plus a fraction of offlink
20360 		 * entries.  It follows from the first if statement that
20361 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20362 		 */
20363 		delete_cnt -= icc.icc_unused;
20364 		/* Round up # deleted by truncating fraction */
20365 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20366 		icr.icr_pmtu = icr.icr_onlink = 0;
20367 		ncr.ncr_host = 0;
20368 	} else if (delete_cnt <=
20369 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20370 		/*
20371 		 * Free all unused and offlink entries, plus a fraction of
20372 		 * pmtu entries.  It follows from the previous if statement
20373 		 * that icc_pmtu is non-zero, and that
20374 		 * delete_cnt != icc_unused + icc_offlink.
20375 		 */
20376 		icr.icr_offlink = 1;
20377 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20378 		/* Round up # deleted by truncating fraction */
20379 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20380 		icr.icr_onlink = 0;
20381 		ncr.ncr_host = 0;
20382 	} else {
20383 		/*
20384 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20385 		 * of onlink entries.  If we're here, then we know that
20386 		 * icc_onlink is non-zero, and that
20387 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20388 		 */
20389 		icr.icr_offlink = icr.icr_pmtu = 1;
20390 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20391 		    icc.icc_pmtu;
20392 		/* Round up # deleted by truncating fraction */
20393 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20394 		/* Using the same delete fraction as for onlink IREs */
20395 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20396 	}
20397 #ifdef DEBUG
20398 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20399 	    "fractions %d/%d/%d/%d\n",
20400 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20401 	    icc.icc_unused, icc.icc_offlink,
20402 	    icc.icc_pmtu, icc.icc_onlink,
20403 	    icr.icr_unused, icr.icr_offlink,
20404 	    icr.icr_pmtu, icr.icr_onlink));
20405 #endif
20406 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20407 	if (ncr.ncr_host != 0)
20408 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20409 		    (uchar_t *)&ncr, ipst);
20410 #ifdef DEBUG
20411 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20412 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20413 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20414 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20415 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20416 	    icc.icc_pmtu, icc.icc_onlink));
20417 #endif
20418 }
20419 
20420 /*
20421  * ip_unbind is called when a copy of an unbind request is received from the
20422  * upper level protocol.  We remove this conn from any fanout hash list it is
20423  * on, and zero out the bind information.  No reply is expected up above.
20424  */
20425 void
20426 ip_unbind(conn_t *connp)
20427 {
20428 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20429 
20430 	if (is_system_labeled() && connp->conn_anon_port) {
20431 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20432 		    connp->conn_mlp_type, connp->conn_ulp,
20433 		    ntohs(connp->conn_lport), B_FALSE);
20434 		connp->conn_anon_port = 0;
20435 	}
20436 	connp->conn_mlp_type = mlptSingle;
20437 
20438 	ipcl_hash_remove(connp);
20439 
20440 }
20441 
20442 /*
20443  * Write side put procedure.  Outbound data, IOCTLs, responses from
20444  * resolvers, etc, come down through here.
20445  *
20446  * arg2 is always a queue_t *.
20447  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20448  * the zoneid.
20449  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20450  */
20451 void
20452 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20453 {
20454 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20455 }
20456 
20457 void
20458 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20459     ip_opt_info_t *infop)
20460 {
20461 	conn_t		*connp = NULL;
20462 	queue_t		*q = (queue_t *)arg2;
20463 	ipha_t		*ipha;
20464 #define	rptr	((uchar_t *)ipha)
20465 	ire_t		*ire = NULL;
20466 	ire_t		*sctp_ire = NULL;
20467 	uint32_t	v_hlen_tos_len;
20468 	ipaddr_t	dst;
20469 	mblk_t		*first_mp = NULL;
20470 	boolean_t	mctl_present;
20471 	ipsec_out_t	*io;
20472 	int		match_flags;
20473 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20474 	ipif_t		*dst_ipif;
20475 	boolean_t	multirt_need_resolve = B_FALSE;
20476 	mblk_t		*copy_mp = NULL;
20477 	int		err;
20478 	zoneid_t	zoneid;
20479 	boolean_t	need_decref = B_FALSE;
20480 	boolean_t	ignore_dontroute = B_FALSE;
20481 	boolean_t	ignore_nexthop = B_FALSE;
20482 	boolean_t	ip_nexthop = B_FALSE;
20483 	ipaddr_t	nexthop_addr;
20484 	ip_stack_t	*ipst;
20485 
20486 #ifdef	_BIG_ENDIAN
20487 #define	V_HLEN	(v_hlen_tos_len >> 24)
20488 #else
20489 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20490 #endif
20491 
20492 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20493 	    "ip_wput_start: q %p", q);
20494 
20495 	/*
20496 	 * ip_wput fast path
20497 	 */
20498 
20499 	/* is packet from ARP ? */
20500 	if (q->q_next != NULL) {
20501 		zoneid = (zoneid_t)(uintptr_t)arg;
20502 		goto qnext;
20503 	}
20504 
20505 	connp = (conn_t *)arg;
20506 	ASSERT(connp != NULL);
20507 	zoneid = connp->conn_zoneid;
20508 	ipst = connp->conn_netstack->netstack_ip;
20509 	ASSERT(ipst != NULL);
20510 
20511 	/* is queue flow controlled? */
20512 	if ((q->q_first != NULL || connp->conn_draining) &&
20513 	    (caller == IP_WPUT)) {
20514 		ASSERT(!need_decref);
20515 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20516 		(void) putq(q, mp);
20517 		return;
20518 	}
20519 
20520 	/* Multidata transmit? */
20521 	if (DB_TYPE(mp) == M_MULTIDATA) {
20522 		/*
20523 		 * We should never get here, since all Multidata messages
20524 		 * originating from tcp should have been directed over to
20525 		 * tcp_multisend() in the first place.
20526 		 */
20527 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20528 		freemsg(mp);
20529 		return;
20530 	} else if (DB_TYPE(mp) != M_DATA)
20531 		goto notdata;
20532 
20533 	if (mp->b_flag & MSGHASREF) {
20534 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20535 		mp->b_flag &= ~MSGHASREF;
20536 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20537 		need_decref = B_TRUE;
20538 	}
20539 	ipha = (ipha_t *)mp->b_rptr;
20540 
20541 	/* is IP header non-aligned or mblk smaller than basic IP header */
20542 #ifndef SAFETY_BEFORE_SPEED
20543 	if (!OK_32PTR(rptr) ||
20544 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20545 		goto hdrtoosmall;
20546 #endif
20547 
20548 	ASSERT(OK_32PTR(ipha));
20549 
20550 	/*
20551 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20552 	 * wrong version, we'll catch it again in ip_output_v6.
20553 	 *
20554 	 * Note that this is *only* locally-generated output here, and never
20555 	 * forwarded data, and that we need to deal only with transports that
20556 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20557 	 * label.)
20558 	 */
20559 	if (is_system_labeled() &&
20560 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20561 	    !connp->conn_ulp_labeled) {
20562 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20563 		    connp->conn_mac_exempt, ipst);
20564 		ipha = (ipha_t *)mp->b_rptr;
20565 		if (err != 0) {
20566 			first_mp = mp;
20567 			if (err == EINVAL)
20568 				goto icmp_parameter_problem;
20569 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20570 			goto discard_pkt;
20571 		}
20572 	}
20573 
20574 	ASSERT(infop != NULL);
20575 
20576 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20577 		/*
20578 		 * IP_PKTINFO ancillary option is present.
20579 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20580 		 * allows using address of any zone as the source address.
20581 		 */
20582 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20583 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20584 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20585 		if (ire == NULL)
20586 			goto drop_pkt;
20587 		ire_refrele(ire);
20588 		ire = NULL;
20589 	}
20590 
20591 	/*
20592 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20593 	 */
20594 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20595 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20596 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20597 
20598 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20599 			goto drop_pkt;
20600 		/*
20601 		 * check that there is an ipif belonging
20602 		 * to our zone. IPCL_ZONEID is not used because
20603 		 * IP_ALLZONES option is valid only when the ill is
20604 		 * accessible from all zones i.e has a valid ipif in
20605 		 * all zones.
20606 		 */
20607 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20608 			goto drop_pkt;
20609 		}
20610 	}
20611 
20612 	/*
20613 	 * If there is a policy, try to attach an ipsec_out in
20614 	 * the front. At the end, first_mp either points to a
20615 	 * M_DATA message or IPSEC_OUT message linked to a
20616 	 * M_DATA message. We have to do it now as we might
20617 	 * lose the "conn" if we go through ip_newroute.
20618 	 */
20619 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20620 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20621 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20622 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20623 			if (need_decref)
20624 				CONN_DEC_REF(connp);
20625 			return;
20626 		} else {
20627 			ASSERT(mp->b_datap->db_type == M_CTL);
20628 			first_mp = mp;
20629 			mp = mp->b_cont;
20630 			mctl_present = B_TRUE;
20631 		}
20632 	} else {
20633 		first_mp = mp;
20634 		mctl_present = B_FALSE;
20635 	}
20636 
20637 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20638 
20639 	/* is wrong version or IP options present */
20640 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20641 		goto version_hdrlen_check;
20642 	dst = ipha->ipha_dst;
20643 
20644 	/* If IP_BOUND_IF has been set, use that ill. */
20645 	if (connp->conn_outgoing_ill != NULL) {
20646 		xmit_ill = conn_get_held_ill(connp,
20647 		    &connp->conn_outgoing_ill, &err);
20648 		if (err == ILL_LOOKUP_FAILED)
20649 			goto drop_pkt;
20650 
20651 		goto send_from_ill;
20652 	}
20653 
20654 	/* is packet multicast? */
20655 	if (CLASSD(dst))
20656 		goto multicast;
20657 
20658 	/*
20659 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20660 	 * takes precedence over conn_dontroute and conn_nexthop_set
20661 	 */
20662 	if (xmit_ill != NULL)
20663 		goto send_from_ill;
20664 
20665 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20666 		/*
20667 		 * If the destination is a broadcast, local, or loopback
20668 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20669 		 * standard path.
20670 		 */
20671 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20672 		if ((ire == NULL) || (ire->ire_type &
20673 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20674 			if (ire != NULL) {
20675 				ire_refrele(ire);
20676 				/* No more access to ire */
20677 				ire = NULL;
20678 			}
20679 			/*
20680 			 * bypass routing checks and go directly to interface.
20681 			 */
20682 			if (connp->conn_dontroute)
20683 				goto dontroute;
20684 
20685 			ASSERT(connp->conn_nexthop_set);
20686 			ip_nexthop = B_TRUE;
20687 			nexthop_addr = connp->conn_nexthop_v4;
20688 			goto send_from_ill;
20689 		}
20690 
20691 		/* Must be a broadcast, a loopback or a local ire */
20692 		ire_refrele(ire);
20693 		/* No more access to ire */
20694 		ire = NULL;
20695 	}
20696 
20697 	/*
20698 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20699 	 * this for the tcp global queue and listen end point
20700 	 * as it does not really have a real destination to
20701 	 * talk to.  This is also true for SCTP.
20702 	 */
20703 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20704 	    !connp->conn_fully_bound) {
20705 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20706 		if (ire == NULL)
20707 			goto noirefound;
20708 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20709 		    "ip_wput_end: q %p (%S)", q, "end");
20710 
20711 		/*
20712 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20713 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20714 		 */
20715 		if (ire->ire_flags & RTF_MULTIRT) {
20716 
20717 			/*
20718 			 * Force the TTL of multirouted packets if required.
20719 			 * The TTL of such packets is bounded by the
20720 			 * ip_multirt_ttl ndd variable.
20721 			 */
20722 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20723 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20724 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20725 				    "(was %d), dst 0x%08x\n",
20726 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20727 				    ntohl(ire->ire_addr)));
20728 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20729 			}
20730 			/*
20731 			 * We look at this point if there are pending
20732 			 * unresolved routes. ire_multirt_resolvable()
20733 			 * checks in O(n) that all IRE_OFFSUBNET ire
20734 			 * entries for the packet's destination and
20735 			 * flagged RTF_MULTIRT are currently resolved.
20736 			 * If some remain unresolved, we make a copy
20737 			 * of the current message. It will be used
20738 			 * to initiate additional route resolutions.
20739 			 */
20740 			multirt_need_resolve =
20741 			    ire_multirt_need_resolve(ire->ire_addr,
20742 			    msg_getlabel(first_mp), ipst);
20743 			ip2dbg(("ip_wput[TCP]: ire %p, "
20744 			    "multirt_need_resolve %d, first_mp %p\n",
20745 			    (void *)ire, multirt_need_resolve,
20746 			    (void *)first_mp));
20747 			if (multirt_need_resolve) {
20748 				copy_mp = copymsg(first_mp);
20749 				if (copy_mp != NULL) {
20750 					MULTIRT_DEBUG_TAG(copy_mp);
20751 				}
20752 			}
20753 		}
20754 
20755 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20756 
20757 		/*
20758 		 * Try to resolve another multiroute if
20759 		 * ire_multirt_need_resolve() deemed it necessary.
20760 		 */
20761 		if (copy_mp != NULL)
20762 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20763 		if (need_decref)
20764 			CONN_DEC_REF(connp);
20765 		return;
20766 	}
20767 
20768 	/*
20769 	 * Access to conn_ire_cache. (protected by conn_lock)
20770 	 *
20771 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20772 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20773 	 * send a packet or two with the IRE_CACHE that is going away.
20774 	 * Access to the ire requires an ire refhold on the ire prior to
20775 	 * its use since an interface unplumb thread may delete the cached
20776 	 * ire and release the refhold at any time.
20777 	 *
20778 	 * Caching an ire in the conn_ire_cache
20779 	 *
20780 	 * o Caching an ire pointer in the conn requires a strict check for
20781 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20782 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20783 	 * in the conn is done after making sure under the bucket lock that the
20784 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20785 	 * caching an ire after the unplumb thread has cleaned up the conn.
20786 	 * If the conn does not send a packet subsequently the unplumb thread
20787 	 * will be hanging waiting for the ire count to drop to zero.
20788 	 *
20789 	 * o We also need to atomically test for a null conn_ire_cache and
20790 	 * set the conn_ire_cache under the the protection of the conn_lock
20791 	 * to avoid races among concurrent threads trying to simultaneously
20792 	 * cache an ire in the conn_ire_cache.
20793 	 */
20794 	mutex_enter(&connp->conn_lock);
20795 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20796 
20797 	if (ire != NULL && ire->ire_addr == dst &&
20798 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20799 
20800 		IRE_REFHOLD(ire);
20801 		mutex_exit(&connp->conn_lock);
20802 
20803 	} else {
20804 		boolean_t cached = B_FALSE;
20805 		connp->conn_ire_cache = NULL;
20806 		mutex_exit(&connp->conn_lock);
20807 		/* Release the old ire */
20808 		if (ire != NULL && sctp_ire == NULL)
20809 			IRE_REFRELE_NOTR(ire);
20810 
20811 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20812 		if (ire == NULL)
20813 			goto noirefound;
20814 		IRE_REFHOLD_NOTR(ire);
20815 
20816 		mutex_enter(&connp->conn_lock);
20817 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20818 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20819 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20820 				if (connp->conn_ulp == IPPROTO_TCP)
20821 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20822 				connp->conn_ire_cache = ire;
20823 				cached = B_TRUE;
20824 			}
20825 			rw_exit(&ire->ire_bucket->irb_lock);
20826 		}
20827 		mutex_exit(&connp->conn_lock);
20828 
20829 		/*
20830 		 * We can continue to use the ire but since it was
20831 		 * not cached, we should drop the extra reference.
20832 		 */
20833 		if (!cached)
20834 			IRE_REFRELE_NOTR(ire);
20835 	}
20836 
20837 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20838 	    "ip_wput_end: q %p (%S)", q, "end");
20839 
20840 	/*
20841 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20842 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20843 	 */
20844 	if (ire->ire_flags & RTF_MULTIRT) {
20845 		/*
20846 		 * Force the TTL of multirouted packets if required.
20847 		 * The TTL of such packets is bounded by the
20848 		 * ip_multirt_ttl ndd variable.
20849 		 */
20850 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20851 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20852 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20853 			    "(was %d), dst 0x%08x\n",
20854 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20855 			    ntohl(ire->ire_addr)));
20856 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20857 		}
20858 
20859 		/*
20860 		 * At this point, we check to see if there are any pending
20861 		 * unresolved routes. ire_multirt_resolvable()
20862 		 * checks in O(n) that all IRE_OFFSUBNET ire
20863 		 * entries for the packet's destination and
20864 		 * flagged RTF_MULTIRT are currently resolved.
20865 		 * If some remain unresolved, we make a copy
20866 		 * of the current message. It will be used
20867 		 * to initiate additional route resolutions.
20868 		 */
20869 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20870 		    msg_getlabel(first_mp), ipst);
20871 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20872 		    "multirt_need_resolve %d, first_mp %p\n",
20873 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20874 		if (multirt_need_resolve) {
20875 			copy_mp = copymsg(first_mp);
20876 			if (copy_mp != NULL) {
20877 				MULTIRT_DEBUG_TAG(copy_mp);
20878 			}
20879 		}
20880 	}
20881 
20882 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20883 
20884 	/*
20885 	 * Try to resolve another multiroute if
20886 	 * ire_multirt_resolvable() deemed it necessary
20887 	 */
20888 	if (copy_mp != NULL)
20889 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20890 	if (need_decref)
20891 		CONN_DEC_REF(connp);
20892 	return;
20893 
20894 qnext:
20895 	/*
20896 	 * Upper Level Protocols pass down complete IP datagrams
20897 	 * as M_DATA messages.	Everything else is a sideshow.
20898 	 *
20899 	 * 1) We could be re-entering ip_wput because of ip_neworute
20900 	 *    in which case we could have a IPSEC_OUT message. We
20901 	 *    need to pass through ip_wput like other datagrams and
20902 	 *    hence cannot branch to ip_wput_nondata.
20903 	 *
20904 	 * 2) ARP, AH, ESP, and other clients who are on the module
20905 	 *    instance of IP stream, give us something to deal with.
20906 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20907 	 *
20908 	 * 3) ICMP replies also could come here.
20909 	 */
20910 	ipst = ILLQ_TO_IPST(q);
20911 
20912 	if (DB_TYPE(mp) != M_DATA) {
20913 notdata:
20914 		if (DB_TYPE(mp) == M_CTL) {
20915 			/*
20916 			 * M_CTL messages are used by ARP, AH and ESP to
20917 			 * communicate with IP. We deal with IPSEC_IN and
20918 			 * IPSEC_OUT here. ip_wput_nondata handles other
20919 			 * cases.
20920 			 */
20921 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20922 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20923 				first_mp = mp->b_cont;
20924 				first_mp->b_flag &= ~MSGHASREF;
20925 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20926 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20927 				CONN_DEC_REF(connp);
20928 				connp = NULL;
20929 			}
20930 			if (ii->ipsec_info_type == IPSEC_IN) {
20931 				/*
20932 				 * Either this message goes back to
20933 				 * IPsec for further processing or to
20934 				 * ULP after policy checks.
20935 				 */
20936 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20937 				return;
20938 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20939 				io = (ipsec_out_t *)ii;
20940 				if (io->ipsec_out_proc_begin) {
20941 					/*
20942 					 * IPsec processing has already started.
20943 					 * Complete it.
20944 					 * IPQoS notes: We don't care what is
20945 					 * in ipsec_out_ill_index since this
20946 					 * won't be processed for IPQoS policies
20947 					 * in ipsec_out_process.
20948 					 */
20949 					ipsec_out_process(q, mp, NULL,
20950 					    io->ipsec_out_ill_index);
20951 					return;
20952 				} else {
20953 					connp = (q->q_next != NULL) ?
20954 					    NULL : Q_TO_CONN(q);
20955 					first_mp = mp;
20956 					mp = mp->b_cont;
20957 					mctl_present = B_TRUE;
20958 				}
20959 				zoneid = io->ipsec_out_zoneid;
20960 				ASSERT(zoneid != ALL_ZONES);
20961 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20962 				/*
20963 				 * It's an IPsec control message requesting
20964 				 * an SADB update to be sent to the IPsec
20965 				 * hardware acceleration capable ills.
20966 				 */
20967 				ipsec_ctl_t *ipsec_ctl =
20968 				    (ipsec_ctl_t *)mp->b_rptr;
20969 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20970 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20971 				mblk_t *cmp = mp->b_cont;
20972 
20973 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20974 				ASSERT(cmp != NULL);
20975 
20976 				freeb(mp);
20977 				ill_ipsec_capab_send_all(satype, cmp, sa,
20978 				    ipst->ips_netstack);
20979 				return;
20980 			} else {
20981 				/*
20982 				 * This must be ARP or special TSOL signaling.
20983 				 */
20984 				ip_wput_nondata(NULL, q, mp, NULL);
20985 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20986 				    "ip_wput_end: q %p (%S)", q, "nondata");
20987 				return;
20988 			}
20989 		} else {
20990 			/*
20991 			 * This must be non-(ARP/AH/ESP) messages.
20992 			 */
20993 			ASSERT(!need_decref);
20994 			ip_wput_nondata(NULL, q, mp, NULL);
20995 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20996 			    "ip_wput_end: q %p (%S)", q, "nondata");
20997 			return;
20998 		}
20999 	} else {
21000 		first_mp = mp;
21001 		mctl_present = B_FALSE;
21002 	}
21003 
21004 	ASSERT(first_mp != NULL);
21005 
21006 	if (mctl_present) {
21007 		io = (ipsec_out_t *)first_mp->b_rptr;
21008 		if (io->ipsec_out_ip_nexthop) {
21009 			/*
21010 			 * We may have lost the conn context if we are
21011 			 * coming here from ip_newroute(). Copy the
21012 			 * nexthop information.
21013 			 */
21014 			ip_nexthop = B_TRUE;
21015 			nexthop_addr = io->ipsec_out_nexthop_addr;
21016 
21017 			ipha = (ipha_t *)mp->b_rptr;
21018 			dst = ipha->ipha_dst;
21019 			goto send_from_ill;
21020 		}
21021 	}
21022 
21023 	ASSERT(xmit_ill == NULL);
21024 
21025 	/* We have a complete IP datagram heading outbound. */
21026 	ipha = (ipha_t *)mp->b_rptr;
21027 
21028 #ifndef SPEED_BEFORE_SAFETY
21029 	/*
21030 	 * Make sure we have a full-word aligned message and that at least
21031 	 * a simple IP header is accessible in the first message.  If not,
21032 	 * try a pullup.  For labeled systems we need to always take this
21033 	 * path as M_CTLs are "notdata" but have trailing data to process.
21034 	 */
21035 	if (!OK_32PTR(rptr) ||
21036 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21037 hdrtoosmall:
21038 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21039 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21040 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21041 			if (first_mp == NULL)
21042 				first_mp = mp;
21043 			goto discard_pkt;
21044 		}
21045 
21046 		/* This function assumes that mp points to an IPv4 packet. */
21047 		if (is_system_labeled() && q->q_next == NULL &&
21048 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21049 		    !connp->conn_ulp_labeled) {
21050 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21051 			    connp->conn_mac_exempt, ipst);
21052 			ipha = (ipha_t *)mp->b_rptr;
21053 			if (first_mp != NULL)
21054 				first_mp->b_cont = mp;
21055 			if (err != 0) {
21056 				if (first_mp == NULL)
21057 					first_mp = mp;
21058 				if (err == EINVAL)
21059 					goto icmp_parameter_problem;
21060 				ip2dbg(("ip_wput: label check failed (%d)\n",
21061 				    err));
21062 				goto discard_pkt;
21063 			}
21064 		}
21065 
21066 		ipha = (ipha_t *)mp->b_rptr;
21067 		if (first_mp == NULL) {
21068 			ASSERT(xmit_ill == NULL);
21069 			/*
21070 			 * If we got here because of "goto hdrtoosmall"
21071 			 * We need to attach a IPSEC_OUT.
21072 			 */
21073 			if (connp->conn_out_enforce_policy) {
21074 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21075 				    NULL, ipha->ipha_protocol,
21076 				    ipst->ips_netstack)) == NULL)) {
21077 					BUMP_MIB(&ipst->ips_ip_mib,
21078 					    ipIfStatsOutDiscards);
21079 					if (need_decref)
21080 						CONN_DEC_REF(connp);
21081 					return;
21082 				} else {
21083 					ASSERT(mp->b_datap->db_type == M_CTL);
21084 					first_mp = mp;
21085 					mp = mp->b_cont;
21086 					mctl_present = B_TRUE;
21087 				}
21088 			} else {
21089 				first_mp = mp;
21090 				mctl_present = B_FALSE;
21091 			}
21092 		}
21093 	}
21094 #endif
21095 
21096 	/* Most of the code below is written for speed, not readability */
21097 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21098 
21099 	/*
21100 	 * If ip_newroute() fails, we're going to need a full
21101 	 * header for the icmp wraparound.
21102 	 */
21103 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21104 		uint_t	v_hlen;
21105 version_hdrlen_check:
21106 		ASSERT(first_mp != NULL);
21107 		v_hlen = V_HLEN;
21108 		/*
21109 		 * siphon off IPv6 packets coming down from transport
21110 		 * layer modules here.
21111 		 * Note: high-order bit carries NUD reachability confirmation
21112 		 */
21113 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21114 			/*
21115 			 * FIXME: assume that callers of ip_output* call
21116 			 * the right version?
21117 			 */
21118 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21119 			ASSERT(xmit_ill == NULL);
21120 			if (need_decref)
21121 				mp->b_flag |= MSGHASREF;
21122 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21123 			return;
21124 		}
21125 
21126 		if ((v_hlen >> 4) != IP_VERSION) {
21127 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21128 			    "ip_wput_end: q %p (%S)", q, "badvers");
21129 			goto discard_pkt;
21130 		}
21131 		/*
21132 		 * Is the header length at least 20 bytes?
21133 		 *
21134 		 * Are there enough bytes accessible in the header?  If
21135 		 * not, try a pullup.
21136 		 */
21137 		v_hlen &= 0xF;
21138 		v_hlen <<= 2;
21139 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21140 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21141 			    "ip_wput_end: q %p (%S)", q, "badlen");
21142 			goto discard_pkt;
21143 		}
21144 		if (v_hlen > (mp->b_wptr - rptr)) {
21145 			if (!pullupmsg(mp, v_hlen)) {
21146 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21147 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21148 				goto discard_pkt;
21149 			}
21150 			ipha = (ipha_t *)mp->b_rptr;
21151 		}
21152 		/*
21153 		 * Move first entry from any source route into ipha_dst and
21154 		 * verify the options
21155 		 */
21156 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21157 		    zoneid, ipst)) {
21158 			ASSERT(xmit_ill == NULL);
21159 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21160 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21161 			    "ip_wput_end: q %p (%S)", q, "badopts");
21162 			if (need_decref)
21163 				CONN_DEC_REF(connp);
21164 			return;
21165 		}
21166 	}
21167 	dst = ipha->ipha_dst;
21168 
21169 	/*
21170 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21171 	 * we have to run the packet through ip_newroute which will take
21172 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21173 	 * a resolver, or assigning a default gateway, etc.
21174 	 */
21175 	if (CLASSD(dst)) {
21176 		ipif_t	*ipif;
21177 		uint32_t setsrc = 0;
21178 
21179 multicast:
21180 		ASSERT(first_mp != NULL);
21181 		ip2dbg(("ip_wput: CLASSD\n"));
21182 		if (connp == NULL) {
21183 			/*
21184 			 * Use the first good ipif on the ill.
21185 			 * XXX Should this ever happen? (Appears
21186 			 * to show up with just ppp and no ethernet due
21187 			 * to in.rdisc.)
21188 			 * However, ire_send should be able to
21189 			 * call ip_wput_ire directly.
21190 			 *
21191 			 * XXX Also, this can happen for ICMP and other packets
21192 			 * with multicast source addresses.  Perhaps we should
21193 			 * fix things so that we drop the packet in question,
21194 			 * but for now, just run with it.
21195 			 */
21196 			ill_t *ill = (ill_t *)q->q_ptr;
21197 
21198 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21199 			if (ipif == NULL) {
21200 				if (need_decref)
21201 					CONN_DEC_REF(connp);
21202 				freemsg(first_mp);
21203 				return;
21204 			}
21205 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21206 			    ntohl(dst), ill->ill_name));
21207 		} else {
21208 			/*
21209 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21210 			 * and IP_MULTICAST_IF.  The block comment above this
21211 			 * function explains the locking mechanism used here.
21212 			 */
21213 			if (xmit_ill == NULL) {
21214 				xmit_ill = conn_get_held_ill(connp,
21215 				    &connp->conn_outgoing_ill, &err);
21216 				if (err == ILL_LOOKUP_FAILED) {
21217 					ip1dbg(("ip_wput: No ill for "
21218 					    "IP_BOUND_IF\n"));
21219 					BUMP_MIB(&ipst->ips_ip_mib,
21220 					    ipIfStatsOutNoRoutes);
21221 					goto drop_pkt;
21222 				}
21223 			}
21224 
21225 			if (xmit_ill == NULL) {
21226 				ipif = conn_get_held_ipif(connp,
21227 				    &connp->conn_multicast_ipif, &err);
21228 				if (err == IPIF_LOOKUP_FAILED) {
21229 					ip1dbg(("ip_wput: No ipif for "
21230 					    "multicast\n"));
21231 					BUMP_MIB(&ipst->ips_ip_mib,
21232 					    ipIfStatsOutNoRoutes);
21233 					goto drop_pkt;
21234 				}
21235 			}
21236 			if (xmit_ill != NULL) {
21237 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21238 				if (ipif == NULL) {
21239 					ip1dbg(("ip_wput: No ipif for "
21240 					    "xmit_ill\n"));
21241 					BUMP_MIB(&ipst->ips_ip_mib,
21242 					    ipIfStatsOutNoRoutes);
21243 					goto drop_pkt;
21244 				}
21245 			} else if (ipif == NULL || ipif->ipif_isv6) {
21246 				/*
21247 				 * We must do this ipif determination here
21248 				 * else we could pass through ip_newroute
21249 				 * and come back here without the conn context.
21250 				 *
21251 				 * Note: we do late binding i.e. we bind to
21252 				 * the interface when the first packet is sent.
21253 				 * For performance reasons we do not rebind on
21254 				 * each packet but keep the binding until the
21255 				 * next IP_MULTICAST_IF option.
21256 				 *
21257 				 * conn_multicast_{ipif,ill} are shared between
21258 				 * IPv4 and IPv6 and AF_INET6 sockets can
21259 				 * send both IPv4 and IPv6 packets. Hence
21260 				 * we have to check that "isv6" matches above.
21261 				 */
21262 				if (ipif != NULL)
21263 					ipif_refrele(ipif);
21264 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21265 				if (ipif == NULL) {
21266 					ip1dbg(("ip_wput: No ipif for "
21267 					    "multicast\n"));
21268 					BUMP_MIB(&ipst->ips_ip_mib,
21269 					    ipIfStatsOutNoRoutes);
21270 					goto drop_pkt;
21271 				}
21272 				err = conn_set_held_ipif(connp,
21273 				    &connp->conn_multicast_ipif, ipif);
21274 				if (err == IPIF_LOOKUP_FAILED) {
21275 					ipif_refrele(ipif);
21276 					ip1dbg(("ip_wput: No ipif for "
21277 					    "multicast\n"));
21278 					BUMP_MIB(&ipst->ips_ip_mib,
21279 					    ipIfStatsOutNoRoutes);
21280 					goto drop_pkt;
21281 				}
21282 			}
21283 		}
21284 		ASSERT(!ipif->ipif_isv6);
21285 		/*
21286 		 * As we may lose the conn by the time we reach ip_wput_ire,
21287 		 * we copy conn_multicast_loop and conn_dontroute on to an
21288 		 * ipsec_out. In case if this datagram goes out secure,
21289 		 * we need the ill_index also. Copy that also into the
21290 		 * ipsec_out.
21291 		 */
21292 		if (mctl_present) {
21293 			io = (ipsec_out_t *)first_mp->b_rptr;
21294 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21295 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21296 		} else {
21297 			ASSERT(mp == first_mp);
21298 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21299 			    BPRI_HI)) == NULL) {
21300 				ipif_refrele(ipif);
21301 				first_mp = mp;
21302 				goto discard_pkt;
21303 			}
21304 			first_mp->b_datap->db_type = M_CTL;
21305 			first_mp->b_wptr += sizeof (ipsec_info_t);
21306 			/* ipsec_out_secure is B_FALSE now */
21307 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21308 			io = (ipsec_out_t *)first_mp->b_rptr;
21309 			io->ipsec_out_type = IPSEC_OUT;
21310 			io->ipsec_out_len = sizeof (ipsec_out_t);
21311 			io->ipsec_out_use_global_policy = B_TRUE;
21312 			io->ipsec_out_ns = ipst->ips_netstack;
21313 			first_mp->b_cont = mp;
21314 			mctl_present = B_TRUE;
21315 		}
21316 
21317 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21318 		io->ipsec_out_ill_index =
21319 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21320 
21321 		if (connp != NULL) {
21322 			io->ipsec_out_multicast_loop =
21323 			    connp->conn_multicast_loop;
21324 			io->ipsec_out_dontroute = connp->conn_dontroute;
21325 			io->ipsec_out_zoneid = connp->conn_zoneid;
21326 		}
21327 		/*
21328 		 * If the application uses IP_MULTICAST_IF with
21329 		 * different logical addresses of the same ILL, we
21330 		 * need to make sure that the soruce address of
21331 		 * the packet matches the logical IP address used
21332 		 * in the option. We do it by initializing ipha_src
21333 		 * here. This should keep IPsec also happy as
21334 		 * when we return from IPsec processing, we don't
21335 		 * have to worry about getting the right address on
21336 		 * the packet. Thus it is sufficient to look for
21337 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21338 		 * MATCH_IRE_IPIF.
21339 		 *
21340 		 * NOTE : We need to do it for non-secure case also as
21341 		 * this might go out secure if there is a global policy
21342 		 * match in ip_wput_ire.
21343 		 *
21344 		 * As we do not have the ire yet, it is possible that
21345 		 * we set the source address here and then later discover
21346 		 * that the ire implies the source address to be assigned
21347 		 * through the RTF_SETSRC flag.
21348 		 * In that case, the setsrc variable will remind us
21349 		 * that overwritting the source address by the one
21350 		 * of the RTF_SETSRC-flagged ire is allowed.
21351 		 */
21352 		if (ipha->ipha_src == INADDR_ANY &&
21353 		    (connp == NULL || !connp->conn_unspec_src)) {
21354 			ipha->ipha_src = ipif->ipif_src_addr;
21355 			setsrc = RTF_SETSRC;
21356 		}
21357 		/*
21358 		 * Find an IRE which matches the destination and the outgoing
21359 		 * queue (i.e. the outgoing interface.)
21360 		 * For loopback use a unicast IP address for
21361 		 * the ire lookup.
21362 		 */
21363 		if (IS_LOOPBACK(ipif->ipif_ill))
21364 			dst = ipif->ipif_lcl_addr;
21365 
21366 		/*
21367 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21368 		 * We don't need to lookup ire in ctable as the packet
21369 		 * needs to be sent to the destination through the specified
21370 		 * ill irrespective of ires in the cache table.
21371 		 */
21372 		ire = NULL;
21373 		if (xmit_ill == NULL) {
21374 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21375 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21376 		}
21377 
21378 		if (ire == NULL) {
21379 			/*
21380 			 * Multicast loopback and multicast forwarding is
21381 			 * done in ip_wput_ire.
21382 			 *
21383 			 * Mark this packet to make it be delivered to
21384 			 * ip_wput_ire after the new ire has been
21385 			 * created.
21386 			 *
21387 			 * The call to ip_newroute_ipif takes into account
21388 			 * the setsrc reminder. In any case, we take care
21389 			 * of the RTF_MULTIRT flag.
21390 			 */
21391 			mp->b_prev = mp->b_next = NULL;
21392 			if (xmit_ill == NULL ||
21393 			    xmit_ill->ill_ipif_up_count > 0) {
21394 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21395 				    setsrc | RTF_MULTIRT, zoneid, infop);
21396 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21397 				    "ip_wput_end: q %p (%S)", q, "noire");
21398 			} else {
21399 				freemsg(first_mp);
21400 			}
21401 			ipif_refrele(ipif);
21402 			if (xmit_ill != NULL)
21403 				ill_refrele(xmit_ill);
21404 			if (need_decref)
21405 				CONN_DEC_REF(connp);
21406 			return;
21407 		}
21408 
21409 		ipif_refrele(ipif);
21410 		ipif = NULL;
21411 		ASSERT(xmit_ill == NULL);
21412 
21413 		/*
21414 		 * Honor the RTF_SETSRC flag for multicast packets,
21415 		 * if allowed by the setsrc reminder.
21416 		 */
21417 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21418 			ipha->ipha_src = ire->ire_src_addr;
21419 		}
21420 
21421 		/*
21422 		 * Unconditionally force the TTL to 1 for
21423 		 * multirouted multicast packets:
21424 		 * multirouted multicast should not cross
21425 		 * multicast routers.
21426 		 */
21427 		if (ire->ire_flags & RTF_MULTIRT) {
21428 			if (ipha->ipha_ttl > 1) {
21429 				ip2dbg(("ip_wput: forcing multicast "
21430 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21431 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21432 				ipha->ipha_ttl = 1;
21433 			}
21434 		}
21435 	} else {
21436 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21437 		if ((ire != NULL) && (ire->ire_type &
21438 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21439 			ignore_dontroute = B_TRUE;
21440 			ignore_nexthop = B_TRUE;
21441 		}
21442 		if (ire != NULL) {
21443 			ire_refrele(ire);
21444 			ire = NULL;
21445 		}
21446 		/*
21447 		 * Guard against coming in from arp in which case conn is NULL.
21448 		 * Also guard against non M_DATA with dontroute set but
21449 		 * destined to local, loopback or broadcast addresses.
21450 		 */
21451 		if (connp != NULL && connp->conn_dontroute &&
21452 		    !ignore_dontroute) {
21453 dontroute:
21454 			/*
21455 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21456 			 * routing protocols from seeing false direct
21457 			 * connectivity.
21458 			 */
21459 			ipha->ipha_ttl = 1;
21460 			/* If suitable ipif not found, drop packet */
21461 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21462 			if (dst_ipif == NULL) {
21463 noroute:
21464 				ip1dbg(("ip_wput: no route for dst using"
21465 				    " SO_DONTROUTE\n"));
21466 				BUMP_MIB(&ipst->ips_ip_mib,
21467 				    ipIfStatsOutNoRoutes);
21468 				mp->b_prev = mp->b_next = NULL;
21469 				if (first_mp == NULL)
21470 					first_mp = mp;
21471 				goto drop_pkt;
21472 			} else {
21473 				/*
21474 				 * If suitable ipif has been found, set
21475 				 * xmit_ill to the corresponding
21476 				 * ipif_ill because we'll be using the
21477 				 * send_from_ill logic below.
21478 				 */
21479 				ASSERT(xmit_ill == NULL);
21480 				xmit_ill = dst_ipif->ipif_ill;
21481 				mutex_enter(&xmit_ill->ill_lock);
21482 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21483 					mutex_exit(&xmit_ill->ill_lock);
21484 					xmit_ill = NULL;
21485 					ipif_refrele(dst_ipif);
21486 					goto noroute;
21487 				}
21488 				ill_refhold_locked(xmit_ill);
21489 				mutex_exit(&xmit_ill->ill_lock);
21490 				ipif_refrele(dst_ipif);
21491 			}
21492 		}
21493 
21494 send_from_ill:
21495 		if (xmit_ill != NULL) {
21496 			ipif_t *ipif;
21497 
21498 			/*
21499 			 * Mark this packet as originated locally
21500 			 */
21501 			mp->b_prev = mp->b_next = NULL;
21502 
21503 			/*
21504 			 * Could be SO_DONTROUTE case also.
21505 			 * Verify that at least one ipif is up on the ill.
21506 			 */
21507 			if (xmit_ill->ill_ipif_up_count == 0) {
21508 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21509 				    xmit_ill->ill_name));
21510 				goto drop_pkt;
21511 			}
21512 
21513 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21514 			if (ipif == NULL) {
21515 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21516 				    xmit_ill->ill_name));
21517 				goto drop_pkt;
21518 			}
21519 
21520 			match_flags = 0;
21521 			if (IS_UNDER_IPMP(xmit_ill))
21522 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21523 
21524 			/*
21525 			 * Look for a ire that is part of the group,
21526 			 * if found use it else call ip_newroute_ipif.
21527 			 * IPCL_ZONEID is not used for matching because
21528 			 * IP_ALLZONES option is valid only when the
21529 			 * ill is accessible from all zones i.e has a
21530 			 * valid ipif in all zones.
21531 			 */
21532 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21533 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21534 			    msg_getlabel(mp), match_flags, ipst);
21535 			/*
21536 			 * If an ire exists use it or else create
21537 			 * an ire but don't add it to the cache.
21538 			 * Adding an ire may cause issues with
21539 			 * asymmetric routing.
21540 			 * In case of multiroute always act as if
21541 			 * ire does not exist.
21542 			 */
21543 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21544 				if (ire != NULL)
21545 					ire_refrele(ire);
21546 				ip_newroute_ipif(q, first_mp, ipif,
21547 				    dst, connp, 0, zoneid, infop);
21548 				ipif_refrele(ipif);
21549 				ip1dbg(("ip_output: xmit_ill via %s\n",
21550 				    xmit_ill->ill_name));
21551 				ill_refrele(xmit_ill);
21552 				if (need_decref)
21553 					CONN_DEC_REF(connp);
21554 				return;
21555 			}
21556 			ipif_refrele(ipif);
21557 		} else if (ip_nexthop || (connp != NULL &&
21558 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21559 			if (!ip_nexthop) {
21560 				ip_nexthop = B_TRUE;
21561 				nexthop_addr = connp->conn_nexthop_v4;
21562 			}
21563 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21564 			    MATCH_IRE_GW;
21565 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21566 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21567 		} else {
21568 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21569 			    ipst);
21570 		}
21571 		if (!ire) {
21572 			if (ip_nexthop && !ignore_nexthop) {
21573 				if (mctl_present) {
21574 					io = (ipsec_out_t *)first_mp->b_rptr;
21575 					ASSERT(first_mp->b_datap->db_type ==
21576 					    M_CTL);
21577 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21578 				} else {
21579 					ASSERT(mp == first_mp);
21580 					first_mp = allocb(
21581 					    sizeof (ipsec_info_t), BPRI_HI);
21582 					if (first_mp == NULL) {
21583 						first_mp = mp;
21584 						goto discard_pkt;
21585 					}
21586 					first_mp->b_datap->db_type = M_CTL;
21587 					first_mp->b_wptr +=
21588 					    sizeof (ipsec_info_t);
21589 					/* ipsec_out_secure is B_FALSE now */
21590 					bzero(first_mp->b_rptr,
21591 					    sizeof (ipsec_info_t));
21592 					io = (ipsec_out_t *)first_mp->b_rptr;
21593 					io->ipsec_out_type = IPSEC_OUT;
21594 					io->ipsec_out_len =
21595 					    sizeof (ipsec_out_t);
21596 					io->ipsec_out_use_global_policy =
21597 					    B_TRUE;
21598 					io->ipsec_out_ns = ipst->ips_netstack;
21599 					first_mp->b_cont = mp;
21600 					mctl_present = B_TRUE;
21601 				}
21602 				io->ipsec_out_ip_nexthop = ip_nexthop;
21603 				io->ipsec_out_nexthop_addr = nexthop_addr;
21604 			}
21605 noirefound:
21606 			/*
21607 			 * Mark this packet as having originated on
21608 			 * this machine.  This will be noted in
21609 			 * ire_add_then_send, which needs to know
21610 			 * whether to run it back through ip_wput or
21611 			 * ip_rput following successful resolution.
21612 			 */
21613 			mp->b_prev = NULL;
21614 			mp->b_next = NULL;
21615 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21616 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21617 			    "ip_wput_end: q %p (%S)", q, "newroute");
21618 			if (xmit_ill != NULL)
21619 				ill_refrele(xmit_ill);
21620 			if (need_decref)
21621 				CONN_DEC_REF(connp);
21622 			return;
21623 		}
21624 	}
21625 
21626 	/* We now know where we are going with it. */
21627 
21628 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21629 	    "ip_wput_end: q %p (%S)", q, "end");
21630 
21631 	/*
21632 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21633 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21634 	 */
21635 	if (ire->ire_flags & RTF_MULTIRT) {
21636 		/*
21637 		 * Force the TTL of multirouted packets if required.
21638 		 * The TTL of such packets is bounded by the
21639 		 * ip_multirt_ttl ndd variable.
21640 		 */
21641 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21642 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21643 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21644 			    "(was %d), dst 0x%08x\n",
21645 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21646 			    ntohl(ire->ire_addr)));
21647 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21648 		}
21649 		/*
21650 		 * At this point, we check to see if there are any pending
21651 		 * unresolved routes. ire_multirt_resolvable()
21652 		 * checks in O(n) that all IRE_OFFSUBNET ire
21653 		 * entries for the packet's destination and
21654 		 * flagged RTF_MULTIRT are currently resolved.
21655 		 * If some remain unresolved, we make a copy
21656 		 * of the current message. It will be used
21657 		 * to initiate additional route resolutions.
21658 		 */
21659 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21660 		    msg_getlabel(first_mp), ipst);
21661 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21662 		    "multirt_need_resolve %d, first_mp %p\n",
21663 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21664 		if (multirt_need_resolve) {
21665 			copy_mp = copymsg(first_mp);
21666 			if (copy_mp != NULL) {
21667 				MULTIRT_DEBUG_TAG(copy_mp);
21668 			}
21669 		}
21670 	}
21671 
21672 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21673 	/*
21674 	 * Try to resolve another multiroute if
21675 	 * ire_multirt_resolvable() deemed it necessary.
21676 	 * At this point, we need to distinguish
21677 	 * multicasts from other packets. For multicasts,
21678 	 * we call ip_newroute_ipif() and request that both
21679 	 * multirouting and setsrc flags are checked.
21680 	 */
21681 	if (copy_mp != NULL) {
21682 		if (CLASSD(dst)) {
21683 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21684 			if (ipif) {
21685 				ASSERT(infop->ip_opt_ill_index == 0);
21686 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21687 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21688 				ipif_refrele(ipif);
21689 			} else {
21690 				MULTIRT_DEBUG_UNTAG(copy_mp);
21691 				freemsg(copy_mp);
21692 				copy_mp = NULL;
21693 			}
21694 		} else {
21695 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21696 		}
21697 	}
21698 	if (xmit_ill != NULL)
21699 		ill_refrele(xmit_ill);
21700 	if (need_decref)
21701 		CONN_DEC_REF(connp);
21702 	return;
21703 
21704 icmp_parameter_problem:
21705 	/* could not have originated externally */
21706 	ASSERT(mp->b_prev == NULL);
21707 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21708 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21709 		/* it's the IP header length that's in trouble */
21710 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21711 		first_mp = NULL;
21712 	}
21713 
21714 discard_pkt:
21715 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21716 drop_pkt:
21717 	ip1dbg(("ip_wput: dropped packet\n"));
21718 	if (ire != NULL)
21719 		ire_refrele(ire);
21720 	if (need_decref)
21721 		CONN_DEC_REF(connp);
21722 	freemsg(first_mp);
21723 	if (xmit_ill != NULL)
21724 		ill_refrele(xmit_ill);
21725 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21726 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21727 }
21728 
21729 /*
21730  * If this is a conn_t queue, then we pass in the conn. This includes the
21731  * zoneid.
21732  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21733  * in which case we use the global zoneid since those are all part of
21734  * the global zone.
21735  */
21736 void
21737 ip_wput(queue_t *q, mblk_t *mp)
21738 {
21739 	if (CONN_Q(q))
21740 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21741 	else
21742 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21743 }
21744 
21745 /*
21746  *
21747  * The following rules must be observed when accessing any ipif or ill
21748  * that has been cached in the conn. Typically conn_outgoing_ill,
21749  * conn_multicast_ipif and conn_multicast_ill.
21750  *
21751  * Access: The ipif or ill pointed to from the conn can be accessed under
21752  * the protection of the conn_lock or after it has been refheld under the
21753  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21754  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21755  * The reason for this is that a concurrent unplumb could actually be
21756  * cleaning up these cached pointers by walking the conns and might have
21757  * finished cleaning up the conn in question. The macros check that an
21758  * unplumb has not yet started on the ipif or ill.
21759  *
21760  * Caching: An ipif or ill pointer may be cached in the conn only after
21761  * making sure that an unplumb has not started. So the caching is done
21762  * while holding both the conn_lock and the ill_lock and after using the
21763  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21764  * flag before starting the cleanup of conns.
21765  *
21766  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21767  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21768  * or a reference to the ipif or a reference to an ire that references the
21769  * ipif. An ipif only changes its ill when migrating from an underlying ill
21770  * to an IPMP ill in ipif_up().
21771  */
21772 ipif_t *
21773 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21774 {
21775 	ipif_t	*ipif;
21776 	ill_t	*ill;
21777 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21778 
21779 	*err = 0;
21780 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21781 	mutex_enter(&connp->conn_lock);
21782 	ipif = *ipifp;
21783 	if (ipif != NULL) {
21784 		ill = ipif->ipif_ill;
21785 		mutex_enter(&ill->ill_lock);
21786 		if (IPIF_CAN_LOOKUP(ipif)) {
21787 			ipif_refhold_locked(ipif);
21788 			mutex_exit(&ill->ill_lock);
21789 			mutex_exit(&connp->conn_lock);
21790 			rw_exit(&ipst->ips_ill_g_lock);
21791 			return (ipif);
21792 		} else {
21793 			*err = IPIF_LOOKUP_FAILED;
21794 		}
21795 		mutex_exit(&ill->ill_lock);
21796 	}
21797 	mutex_exit(&connp->conn_lock);
21798 	rw_exit(&ipst->ips_ill_g_lock);
21799 	return (NULL);
21800 }
21801 
21802 ill_t *
21803 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21804 {
21805 	ill_t	*ill;
21806 
21807 	*err = 0;
21808 	mutex_enter(&connp->conn_lock);
21809 	ill = *illp;
21810 	if (ill != NULL) {
21811 		mutex_enter(&ill->ill_lock);
21812 		if (ILL_CAN_LOOKUP(ill)) {
21813 			ill_refhold_locked(ill);
21814 			mutex_exit(&ill->ill_lock);
21815 			mutex_exit(&connp->conn_lock);
21816 			return (ill);
21817 		} else {
21818 			*err = ILL_LOOKUP_FAILED;
21819 		}
21820 		mutex_exit(&ill->ill_lock);
21821 	}
21822 	mutex_exit(&connp->conn_lock);
21823 	return (NULL);
21824 }
21825 
21826 static int
21827 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21828 {
21829 	ill_t	*ill;
21830 
21831 	ill = ipif->ipif_ill;
21832 	mutex_enter(&connp->conn_lock);
21833 	mutex_enter(&ill->ill_lock);
21834 	if (IPIF_CAN_LOOKUP(ipif)) {
21835 		*ipifp = ipif;
21836 		mutex_exit(&ill->ill_lock);
21837 		mutex_exit(&connp->conn_lock);
21838 		return (0);
21839 	}
21840 	mutex_exit(&ill->ill_lock);
21841 	mutex_exit(&connp->conn_lock);
21842 	return (IPIF_LOOKUP_FAILED);
21843 }
21844 
21845 /*
21846  * This is called if the outbound datagram needs fragmentation.
21847  *
21848  * NOTE : This function does not ire_refrele the ire argument passed in.
21849  */
21850 static void
21851 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21852     ip_stack_t *ipst, conn_t *connp)
21853 {
21854 	ipha_t		*ipha;
21855 	mblk_t		*mp;
21856 	uint32_t	v_hlen_tos_len;
21857 	uint32_t	max_frag;
21858 	uint32_t	frag_flag;
21859 	boolean_t	dont_use;
21860 
21861 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21862 		mp = ipsec_mp->b_cont;
21863 	} else {
21864 		mp = ipsec_mp;
21865 	}
21866 
21867 	ipha = (ipha_t *)mp->b_rptr;
21868 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21869 
21870 #ifdef	_BIG_ENDIAN
21871 #define	V_HLEN	(v_hlen_tos_len >> 24)
21872 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21873 #else
21874 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21875 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21876 #endif
21877 
21878 #ifndef SPEED_BEFORE_SAFETY
21879 	/*
21880 	 * Check that ipha_length is consistent with
21881 	 * the mblk length
21882 	 */
21883 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21884 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21885 		    LENGTH, msgdsize(mp)));
21886 		freemsg(ipsec_mp);
21887 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21888 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21889 		    "packet length mismatch");
21890 		return;
21891 	}
21892 #endif
21893 	/*
21894 	 * Don't use frag_flag if pre-built packet or source
21895 	 * routed or if multicast (since multicast packets do not solicit
21896 	 * ICMP "packet too big" messages). Get the values of
21897 	 * max_frag and frag_flag atomically by acquiring the
21898 	 * ire_lock.
21899 	 */
21900 	mutex_enter(&ire->ire_lock);
21901 	max_frag = ire->ire_max_frag;
21902 	frag_flag = ire->ire_frag_flag;
21903 	mutex_exit(&ire->ire_lock);
21904 
21905 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21906 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21907 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21908 
21909 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21910 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21911 }
21912 
21913 /*
21914  * Used for deciding the MSS size for the upper layer. Thus
21915  * we need to check the outbound policy values in the conn.
21916  */
21917 int
21918 conn_ipsec_length(conn_t *connp)
21919 {
21920 	ipsec_latch_t *ipl;
21921 
21922 	ipl = connp->conn_latch;
21923 	if (ipl == NULL)
21924 		return (0);
21925 
21926 	if (ipl->ipl_out_policy == NULL)
21927 		return (0);
21928 
21929 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21930 }
21931 
21932 /*
21933  * Returns an estimate of the IPsec headers size. This is used if
21934  * we don't want to call into IPsec to get the exact size.
21935  */
21936 int
21937 ipsec_out_extra_length(mblk_t *ipsec_mp)
21938 {
21939 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21940 	ipsec_action_t *a;
21941 
21942 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21943 	if (!io->ipsec_out_secure)
21944 		return (0);
21945 
21946 	a = io->ipsec_out_act;
21947 
21948 	if (a == NULL) {
21949 		ASSERT(io->ipsec_out_policy != NULL);
21950 		a = io->ipsec_out_policy->ipsp_act;
21951 	}
21952 	ASSERT(a != NULL);
21953 
21954 	return (a->ipa_ovhd);
21955 }
21956 
21957 /*
21958  * Returns an estimate of the IPsec headers size. This is used if
21959  * we don't want to call into IPsec to get the exact size.
21960  */
21961 int
21962 ipsec_in_extra_length(mblk_t *ipsec_mp)
21963 {
21964 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21965 	ipsec_action_t *a;
21966 
21967 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21968 
21969 	a = ii->ipsec_in_action;
21970 	return (a == NULL ? 0 : a->ipa_ovhd);
21971 }
21972 
21973 /*
21974  * If there are any source route options, return the true final
21975  * destination. Otherwise, return the destination.
21976  */
21977 ipaddr_t
21978 ip_get_dst(ipha_t *ipha)
21979 {
21980 	ipoptp_t	opts;
21981 	uchar_t		*opt;
21982 	uint8_t		optval;
21983 	uint8_t		optlen;
21984 	ipaddr_t	dst;
21985 	uint32_t off;
21986 
21987 	dst = ipha->ipha_dst;
21988 
21989 	if (IS_SIMPLE_IPH(ipha))
21990 		return (dst);
21991 
21992 	for (optval = ipoptp_first(&opts, ipha);
21993 	    optval != IPOPT_EOL;
21994 	    optval = ipoptp_next(&opts)) {
21995 		opt = opts.ipoptp_cur;
21996 		optlen = opts.ipoptp_len;
21997 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21998 		switch (optval) {
21999 		case IPOPT_SSRR:
22000 		case IPOPT_LSRR:
22001 			off = opt[IPOPT_OFFSET];
22002 			/*
22003 			 * If one of the conditions is true, it means
22004 			 * end of options and dst already has the right
22005 			 * value.
22006 			 */
22007 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22008 				off = optlen - IP_ADDR_LEN;
22009 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22010 			}
22011 			return (dst);
22012 		default:
22013 			break;
22014 		}
22015 	}
22016 
22017 	return (dst);
22018 }
22019 
22020 mblk_t *
22021 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22022     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22023 {
22024 	ipsec_out_t	*io;
22025 	mblk_t		*first_mp;
22026 	boolean_t policy_present;
22027 	ip_stack_t	*ipst;
22028 	ipsec_stack_t	*ipss;
22029 
22030 	ASSERT(ire != NULL);
22031 	ipst = ire->ire_ipst;
22032 	ipss = ipst->ips_netstack->netstack_ipsec;
22033 
22034 	first_mp = mp;
22035 	if (mp->b_datap->db_type == M_CTL) {
22036 		io = (ipsec_out_t *)first_mp->b_rptr;
22037 		/*
22038 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22039 		 *
22040 		 * 1) There is per-socket policy (including cached global
22041 		 *    policy) or a policy on the IP-in-IP tunnel.
22042 		 * 2) There is no per-socket policy, but it is
22043 		 *    a multicast packet that needs to go out
22044 		 *    on a specific interface. This is the case
22045 		 *    where (ip_wput and ip_wput_multicast) attaches
22046 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22047 		 *
22048 		 * In case (2) we check with global policy to
22049 		 * see if there is a match and set the ill_index
22050 		 * appropriately so that we can lookup the ire
22051 		 * properly in ip_wput_ipsec_out.
22052 		 */
22053 
22054 		/*
22055 		 * ipsec_out_use_global_policy is set to B_FALSE
22056 		 * in ipsec_in_to_out(). Refer to that function for
22057 		 * details.
22058 		 */
22059 		if ((io->ipsec_out_latch == NULL) &&
22060 		    (io->ipsec_out_use_global_policy)) {
22061 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22062 			    ire, connp, unspec_src, zoneid));
22063 		}
22064 		if (!io->ipsec_out_secure) {
22065 			/*
22066 			 * If this is not a secure packet, drop
22067 			 * the IPSEC_OUT mp and treat it as a clear
22068 			 * packet. This happens when we are sending
22069 			 * a ICMP reply back to a clear packet. See
22070 			 * ipsec_in_to_out() for details.
22071 			 */
22072 			mp = first_mp->b_cont;
22073 			freeb(first_mp);
22074 		}
22075 		return (mp);
22076 	}
22077 	/*
22078 	 * See whether we need to attach a global policy here. We
22079 	 * don't depend on the conn (as it could be null) for deciding
22080 	 * what policy this datagram should go through because it
22081 	 * should have happened in ip_wput if there was some
22082 	 * policy. This normally happens for connections which are not
22083 	 * fully bound preventing us from caching policies in
22084 	 * ip_bind. Packets coming from the TCP listener/global queue
22085 	 * - which are non-hard_bound - could also be affected by
22086 	 * applying policy here.
22087 	 *
22088 	 * If this packet is coming from tcp global queue or listener,
22089 	 * we will be applying policy here.  This may not be *right*
22090 	 * if these packets are coming from the detached connection as
22091 	 * it could have gone in clear before. This happens only if a
22092 	 * TCP connection started when there is no policy and somebody
22093 	 * added policy before it became detached. Thus packets of the
22094 	 * detached connection could go out secure and the other end
22095 	 * would drop it because it will be expecting in clear. The
22096 	 * converse is not true i.e if somebody starts a TCP
22097 	 * connection and deletes the policy, all the packets will
22098 	 * still go out with the policy that existed before deleting
22099 	 * because ip_unbind sends up policy information which is used
22100 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22101 	 * TCP to attach a dummy IPSEC_OUT and set
22102 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22103 	 * affect performance for normal cases, we are not doing it.
22104 	 * Thus, set policy before starting any TCP connections.
22105 	 *
22106 	 * NOTE - We might apply policy even for a hard bound connection
22107 	 * - for which we cached policy in ip_bind - if somebody added
22108 	 * global policy after we inherited the policy in ip_bind.
22109 	 * This means that the packets that were going out in clear
22110 	 * previously would start going secure and hence get dropped
22111 	 * on the other side. To fix this, TCP attaches a dummy
22112 	 * ipsec_out and make sure that we don't apply global policy.
22113 	 */
22114 	if (ipha != NULL)
22115 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22116 	else
22117 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22118 	if (!policy_present)
22119 		return (mp);
22120 
22121 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22122 	    zoneid));
22123 }
22124 
22125 /*
22126  * This function does the ire_refrele of the ire passed in as the
22127  * argument. As this function looks up more ires i.e broadcast ires,
22128  * it needs to REFRELE them. Currently, for simplicity we don't
22129  * differentiate the one passed in and looked up here. We always
22130  * REFRELE.
22131  * IPQoS Notes:
22132  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22133  * IPsec packets are done in ipsec_out_process.
22134  */
22135 void
22136 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22137     zoneid_t zoneid)
22138 {
22139 	ipha_t		*ipha;
22140 #define	rptr	((uchar_t *)ipha)
22141 	queue_t		*stq;
22142 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22143 	uint32_t	v_hlen_tos_len;
22144 	uint32_t	ttl_protocol;
22145 	ipaddr_t	src;
22146 	ipaddr_t	dst;
22147 	uint32_t	cksum;
22148 	ipaddr_t	orig_src;
22149 	ire_t		*ire1;
22150 	mblk_t		*next_mp;
22151 	uint_t		hlen;
22152 	uint16_t	*up;
22153 	uint32_t	max_frag = ire->ire_max_frag;
22154 	ill_t		*ill = ire_to_ill(ire);
22155 	int		clusterwide;
22156 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22157 	int		ipsec_len;
22158 	mblk_t		*first_mp;
22159 	ipsec_out_t	*io;
22160 	boolean_t	conn_dontroute;		/* conn value for multicast */
22161 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22162 	boolean_t	multicast_forward;	/* Should we forward ? */
22163 	boolean_t	unspec_src;
22164 	ill_t		*conn_outgoing_ill = NULL;
22165 	ill_t		*ire_ill;
22166 	ill_t		*ire1_ill;
22167 	ill_t		*out_ill;
22168 	uint32_t 	ill_index = 0;
22169 	boolean_t	multirt_send = B_FALSE;
22170 	int		err;
22171 	ipxmit_state_t	pktxmit_state;
22172 	ip_stack_t	*ipst = ire->ire_ipst;
22173 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22174 
22175 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22176 	    "ip_wput_ire_start: q %p", q);
22177 
22178 	multicast_forward = B_FALSE;
22179 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22180 
22181 	if (ire->ire_flags & RTF_MULTIRT) {
22182 		/*
22183 		 * Multirouting case. The bucket where ire is stored
22184 		 * probably holds other RTF_MULTIRT flagged ire
22185 		 * to the destination. In this call to ip_wput_ire,
22186 		 * we attempt to send the packet through all
22187 		 * those ires. Thus, we first ensure that ire is the
22188 		 * first RTF_MULTIRT ire in the bucket,
22189 		 * before walking the ire list.
22190 		 */
22191 		ire_t *first_ire;
22192 		irb_t *irb = ire->ire_bucket;
22193 		ASSERT(irb != NULL);
22194 
22195 		/* Make sure we do not omit any multiroute ire. */
22196 		IRB_REFHOLD(irb);
22197 		for (first_ire = irb->irb_ire;
22198 		    first_ire != NULL;
22199 		    first_ire = first_ire->ire_next) {
22200 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22201 			    (first_ire->ire_addr == ire->ire_addr) &&
22202 			    !(first_ire->ire_marks &
22203 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22204 				break;
22205 		}
22206 
22207 		if ((first_ire != NULL) && (first_ire != ire)) {
22208 			IRE_REFHOLD(first_ire);
22209 			ire_refrele(ire);
22210 			ire = first_ire;
22211 			ill = ire_to_ill(ire);
22212 		}
22213 		IRB_REFRELE(irb);
22214 	}
22215 
22216 	/*
22217 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22218 	 * for performance we don't grab the mutexs in the fastpath
22219 	 */
22220 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22221 	    connp->conn_outgoing_ill != NULL) {
22222 		conn_outgoing_ill = conn_get_held_ill(connp,
22223 		    &connp->conn_outgoing_ill, &err);
22224 		if (err == ILL_LOOKUP_FAILED) {
22225 			ire_refrele(ire);
22226 			freemsg(mp);
22227 			return;
22228 		}
22229 	}
22230 
22231 	if (mp->b_datap->db_type != M_CTL) {
22232 		ipha = (ipha_t *)mp->b_rptr;
22233 	} else {
22234 		io = (ipsec_out_t *)mp->b_rptr;
22235 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22236 		ASSERT(zoneid == io->ipsec_out_zoneid);
22237 		ASSERT(zoneid != ALL_ZONES);
22238 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22239 		dst = ipha->ipha_dst;
22240 		/*
22241 		 * For the multicast case, ipsec_out carries conn_dontroute and
22242 		 * conn_multicast_loop as conn may not be available here. We
22243 		 * need this for multicast loopback and forwarding which is done
22244 		 * later in the code.
22245 		 */
22246 		if (CLASSD(dst)) {
22247 			conn_dontroute = io->ipsec_out_dontroute;
22248 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22249 			/*
22250 			 * If conn_dontroute is not set or conn_multicast_loop
22251 			 * is set, we need to do forwarding/loopback. For
22252 			 * datagrams from ip_wput_multicast, conn_dontroute is
22253 			 * set to B_TRUE and conn_multicast_loop is set to
22254 			 * B_FALSE so that we neither do forwarding nor
22255 			 * loopback.
22256 			 */
22257 			if (!conn_dontroute || conn_multicast_loop)
22258 				multicast_forward = B_TRUE;
22259 		}
22260 	}
22261 
22262 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22263 	    ire->ire_zoneid != ALL_ZONES) {
22264 		/*
22265 		 * When a zone sends a packet to another zone, we try to deliver
22266 		 * the packet under the same conditions as if the destination
22267 		 * was a real node on the network. To do so, we look for a
22268 		 * matching route in the forwarding table.
22269 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22270 		 * ip_newroute() does.
22271 		 * Note that IRE_LOCAL are special, since they are used
22272 		 * when the zoneid doesn't match in some cases. This means that
22273 		 * we need to handle ipha_src differently since ire_src_addr
22274 		 * belongs to the receiving zone instead of the sending zone.
22275 		 * When ip_restrict_interzone_loopback is set, then
22276 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22277 		 * for loopback between zones when the logical "Ethernet" would
22278 		 * have looped them back.
22279 		 */
22280 		ire_t *src_ire;
22281 
22282 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22283 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22284 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22285 		if (src_ire != NULL &&
22286 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22287 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22288 		    ire_local_same_lan(ire, src_ire))) {
22289 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22290 				ipha->ipha_src = src_ire->ire_src_addr;
22291 			ire_refrele(src_ire);
22292 		} else {
22293 			ire_refrele(ire);
22294 			if (conn_outgoing_ill != NULL)
22295 				ill_refrele(conn_outgoing_ill);
22296 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22297 			if (src_ire != NULL) {
22298 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22299 					ire_refrele(src_ire);
22300 					freemsg(mp);
22301 					return;
22302 				}
22303 				ire_refrele(src_ire);
22304 			}
22305 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22306 				/* Failed */
22307 				freemsg(mp);
22308 				return;
22309 			}
22310 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22311 			    ipst);
22312 			return;
22313 		}
22314 	}
22315 
22316 	if (mp->b_datap->db_type == M_CTL ||
22317 	    ipss->ipsec_outbound_v4_policy_present) {
22318 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22319 		    unspec_src, zoneid);
22320 		if (mp == NULL) {
22321 			ire_refrele(ire);
22322 			if (conn_outgoing_ill != NULL)
22323 				ill_refrele(conn_outgoing_ill);
22324 			return;
22325 		}
22326 		/*
22327 		 * Trusted Extensions supports all-zones interfaces, so
22328 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22329 		 * the global zone.
22330 		 */
22331 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22332 			io = (ipsec_out_t *)mp->b_rptr;
22333 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22334 			zoneid = io->ipsec_out_zoneid;
22335 		}
22336 	}
22337 
22338 	first_mp = mp;
22339 	ipsec_len = 0;
22340 
22341 	if (first_mp->b_datap->db_type == M_CTL) {
22342 		io = (ipsec_out_t *)first_mp->b_rptr;
22343 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22344 		mp = first_mp->b_cont;
22345 		ipsec_len = ipsec_out_extra_length(first_mp);
22346 		ASSERT(ipsec_len >= 0);
22347 		/* We already picked up the zoneid from the M_CTL above */
22348 		ASSERT(zoneid == io->ipsec_out_zoneid);
22349 		ASSERT(zoneid != ALL_ZONES);
22350 
22351 		/*
22352 		 * Drop M_CTL here if IPsec processing is not needed.
22353 		 * (Non-IPsec use of M_CTL extracted any information it
22354 		 * needed above).
22355 		 */
22356 		if (ipsec_len == 0) {
22357 			freeb(first_mp);
22358 			first_mp = mp;
22359 		}
22360 	}
22361 
22362 	/*
22363 	 * Fast path for ip_wput_ire
22364 	 */
22365 
22366 	ipha = (ipha_t *)mp->b_rptr;
22367 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22368 	dst = ipha->ipha_dst;
22369 
22370 	/*
22371 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22372 	 * if the socket is a SOCK_RAW type. The transport checksum should
22373 	 * be provided in the pre-built packet, so we don't need to compute it.
22374 	 * Also, other application set flags, like DF, should not be altered.
22375 	 * Other transport MUST pass down zero.
22376 	 */
22377 	ip_hdr_included = ipha->ipha_ident;
22378 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22379 
22380 	if (CLASSD(dst)) {
22381 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22382 		    ntohl(dst),
22383 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22384 		    ntohl(ire->ire_addr)));
22385 	}
22386 
22387 /* Macros to extract header fields from data already in registers */
22388 #ifdef	_BIG_ENDIAN
22389 #define	V_HLEN	(v_hlen_tos_len >> 24)
22390 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22391 #define	PROTO	(ttl_protocol & 0xFF)
22392 #else
22393 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22394 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22395 #define	PROTO	(ttl_protocol >> 8)
22396 #endif
22397 
22398 	orig_src = src = ipha->ipha_src;
22399 	/* (The loop back to "another" is explained down below.) */
22400 another:;
22401 	/*
22402 	 * Assign an ident value for this packet.  We assign idents on
22403 	 * a per destination basis out of the IRE.  There could be
22404 	 * other threads targeting the same destination, so we have to
22405 	 * arrange for a atomic increment.  Note that we use a 32-bit
22406 	 * atomic add because it has better performance than its
22407 	 * 16-bit sibling.
22408 	 *
22409 	 * If running in cluster mode and if the source address
22410 	 * belongs to a replicated service then vector through
22411 	 * cl_inet_ipident vector to allocate ip identifier
22412 	 * NOTE: This is a contract private interface with the
22413 	 * clustering group.
22414 	 */
22415 	clusterwide = 0;
22416 	if (cl_inet_ipident) {
22417 		ASSERT(cl_inet_isclusterwide);
22418 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22419 
22420 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22421 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22422 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22423 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22424 			    (uint8_t *)(uintptr_t)dst, NULL);
22425 			clusterwide = 1;
22426 		}
22427 	}
22428 	if (!clusterwide) {
22429 		ipha->ipha_ident =
22430 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22431 	}
22432 
22433 #ifndef _BIG_ENDIAN
22434 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22435 #endif
22436 
22437 	/*
22438 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22439 	 * This is needed to obey conn_unspec_src when packets go through
22440 	 * ip_newroute + arp.
22441 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22442 	 */
22443 	if (src == INADDR_ANY && !unspec_src) {
22444 		/*
22445 		 * Assign the appropriate source address from the IRE if none
22446 		 * was specified.
22447 		 */
22448 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22449 
22450 		src = ire->ire_src_addr;
22451 		if (connp == NULL) {
22452 			ip1dbg(("ip_wput_ire: no connp and no src "
22453 			    "address for dst 0x%x, using src 0x%x\n",
22454 			    ntohl(dst),
22455 			    ntohl(src)));
22456 		}
22457 		ipha->ipha_src = src;
22458 	}
22459 	stq = ire->ire_stq;
22460 
22461 	/*
22462 	 * We only allow ire chains for broadcasts since there will
22463 	 * be multiple IRE_CACHE entries for the same multicast
22464 	 * address (one per ipif).
22465 	 */
22466 	next_mp = NULL;
22467 
22468 	/* broadcast packet */
22469 	if (ire->ire_type == IRE_BROADCAST)
22470 		goto broadcast;
22471 
22472 	/* loopback ? */
22473 	if (stq == NULL)
22474 		goto nullstq;
22475 
22476 	/* The ill_index for outbound ILL */
22477 	ill_index = Q_TO_INDEX(stq);
22478 
22479 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22480 	ttl_protocol = ((uint16_t *)ipha)[4];
22481 
22482 	/* pseudo checksum (do it in parts for IP header checksum) */
22483 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22484 
22485 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22486 		queue_t *dev_q = stq->q_next;
22487 
22488 		/*
22489 		 * For DIRECT_CAPABLE, we do flow control at
22490 		 * the time of sending the packet. See
22491 		 * ILL_SEND_TX().
22492 		 */
22493 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22494 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22495 			goto blocked;
22496 
22497 		if ((PROTO == IPPROTO_UDP) &&
22498 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22499 			hlen = (V_HLEN & 0xF) << 2;
22500 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22501 			if (*up != 0) {
22502 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22503 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22504 				/* Software checksum? */
22505 				if (DB_CKSUMFLAGS(mp) == 0) {
22506 					IP_STAT(ipst, ip_out_sw_cksum);
22507 					IP_STAT_UPDATE(ipst,
22508 					    ip_udp_out_sw_cksum_bytes,
22509 					    LENGTH - hlen);
22510 				}
22511 			}
22512 		}
22513 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22514 		hlen = (V_HLEN & 0xF) << 2;
22515 		if (PROTO == IPPROTO_TCP) {
22516 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22517 			/*
22518 			 * The packet header is processed once and for all, even
22519 			 * in the multirouting case. We disable hardware
22520 			 * checksum if the packet is multirouted, as it will be
22521 			 * replicated via several interfaces, and not all of
22522 			 * them may have this capability.
22523 			 */
22524 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22525 			    LENGTH, max_frag, ipsec_len, cksum);
22526 			/* Software checksum? */
22527 			if (DB_CKSUMFLAGS(mp) == 0) {
22528 				IP_STAT(ipst, ip_out_sw_cksum);
22529 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22530 				    LENGTH - hlen);
22531 			}
22532 		} else {
22533 			sctp_hdr_t	*sctph;
22534 
22535 			ASSERT(PROTO == IPPROTO_SCTP);
22536 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22537 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22538 			/*
22539 			 * Zero out the checksum field to ensure proper
22540 			 * checksum calculation.
22541 			 */
22542 			sctph->sh_chksum = 0;
22543 #ifdef	DEBUG
22544 			if (!skip_sctp_cksum)
22545 #endif
22546 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22547 		}
22548 	}
22549 
22550 	/*
22551 	 * If this is a multicast packet and originated from ip_wput
22552 	 * we need to do loopback and forwarding checks. If it comes
22553 	 * from ip_wput_multicast, we SHOULD not do this.
22554 	 */
22555 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22556 
22557 	/* checksum */
22558 	cksum += ttl_protocol;
22559 
22560 	/* fragment the packet */
22561 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22562 		goto fragmentit;
22563 	/*
22564 	 * Don't use frag_flag if packet is pre-built or source
22565 	 * routed or if multicast (since multicast packets do
22566 	 * not solicit ICMP "packet too big" messages).
22567 	 */
22568 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22569 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22570 	    !ip_source_route_included(ipha)) &&
22571 	    !CLASSD(ipha->ipha_dst))
22572 		ipha->ipha_fragment_offset_and_flags |=
22573 		    htons(ire->ire_frag_flag);
22574 
22575 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22576 		/* calculate IP header checksum */
22577 		cksum += ipha->ipha_ident;
22578 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22579 		cksum += ipha->ipha_fragment_offset_and_flags;
22580 
22581 		/* IP options present */
22582 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22583 		if (hlen)
22584 			goto checksumoptions;
22585 
22586 		/* calculate hdr checksum */
22587 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22588 		cksum = ~(cksum + (cksum >> 16));
22589 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22590 	}
22591 	if (ipsec_len != 0) {
22592 		/*
22593 		 * We will do the rest of the processing after
22594 		 * we come back from IPsec in ip_wput_ipsec_out().
22595 		 */
22596 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22597 
22598 		io = (ipsec_out_t *)first_mp->b_rptr;
22599 		io->ipsec_out_ill_index =
22600 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22601 		ipsec_out_process(q, first_mp, ire, 0);
22602 		ire_refrele(ire);
22603 		if (conn_outgoing_ill != NULL)
22604 			ill_refrele(conn_outgoing_ill);
22605 		return;
22606 	}
22607 
22608 	/*
22609 	 * In most cases, the emission loop below is entered only
22610 	 * once. Only in the case where the ire holds the
22611 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22612 	 * flagged ires in the bucket, and send the packet
22613 	 * through all crossed RTF_MULTIRT routes.
22614 	 */
22615 	if (ire->ire_flags & RTF_MULTIRT) {
22616 		multirt_send = B_TRUE;
22617 	}
22618 	do {
22619 		if (multirt_send) {
22620 			irb_t *irb;
22621 			/*
22622 			 * We are in a multiple send case, need to get
22623 			 * the next ire and make a duplicate of the packet.
22624 			 * ire1 holds here the next ire to process in the
22625 			 * bucket. If multirouting is expected,
22626 			 * any non-RTF_MULTIRT ire that has the
22627 			 * right destination address is ignored.
22628 			 */
22629 			irb = ire->ire_bucket;
22630 			ASSERT(irb != NULL);
22631 
22632 			IRB_REFHOLD(irb);
22633 			for (ire1 = ire->ire_next;
22634 			    ire1 != NULL;
22635 			    ire1 = ire1->ire_next) {
22636 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22637 					continue;
22638 				if (ire1->ire_addr != ire->ire_addr)
22639 					continue;
22640 				if (ire1->ire_marks &
22641 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22642 					continue;
22643 
22644 				/* Got one */
22645 				IRE_REFHOLD(ire1);
22646 				break;
22647 			}
22648 			IRB_REFRELE(irb);
22649 
22650 			if (ire1 != NULL) {
22651 				next_mp = copyb(mp);
22652 				if ((next_mp == NULL) ||
22653 				    ((mp->b_cont != NULL) &&
22654 				    ((next_mp->b_cont =
22655 				    dupmsg(mp->b_cont)) == NULL))) {
22656 					freemsg(next_mp);
22657 					next_mp = NULL;
22658 					ire_refrele(ire1);
22659 					ire1 = NULL;
22660 				}
22661 			}
22662 
22663 			/* Last multiroute ire; don't loop anymore. */
22664 			if (ire1 == NULL) {
22665 				multirt_send = B_FALSE;
22666 			}
22667 		}
22668 
22669 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22670 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22671 		    mblk_t *, mp);
22672 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22673 		    ipst->ips_ipv4firewall_physical_out,
22674 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22675 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22676 
22677 		if (mp == NULL)
22678 			goto release_ire_and_ill;
22679 
22680 		if (ipst->ips_ipobs_enabled) {
22681 			zoneid_t szone;
22682 
22683 			/*
22684 			 * On the outbound path the destination zone will be
22685 			 * unknown as we're sending this packet out on the
22686 			 * wire.
22687 			 */
22688 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22689 			    ALL_ZONES);
22690 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22691 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22692 		}
22693 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22694 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22695 
22696 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22697 
22698 		if ((pktxmit_state == SEND_FAILED) ||
22699 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22700 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22701 			    "- packet dropped\n"));
22702 release_ire_and_ill:
22703 			ire_refrele(ire);
22704 			if (next_mp != NULL) {
22705 				freemsg(next_mp);
22706 				ire_refrele(ire1);
22707 			}
22708 			if (conn_outgoing_ill != NULL)
22709 				ill_refrele(conn_outgoing_ill);
22710 			return;
22711 		}
22712 
22713 		if (CLASSD(dst)) {
22714 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22715 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22716 			    LENGTH);
22717 		}
22718 
22719 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22720 		    "ip_wput_ire_end: q %p (%S)",
22721 		    q, "last copy out");
22722 		IRE_REFRELE(ire);
22723 
22724 		if (multirt_send) {
22725 			ASSERT(ire1);
22726 			/*
22727 			 * Proceed with the next RTF_MULTIRT ire,
22728 			 * Also set up the send-to queue accordingly.
22729 			 */
22730 			ire = ire1;
22731 			ire1 = NULL;
22732 			stq = ire->ire_stq;
22733 			mp = next_mp;
22734 			next_mp = NULL;
22735 			ipha = (ipha_t *)mp->b_rptr;
22736 			ill_index = Q_TO_INDEX(stq);
22737 			ill = (ill_t *)stq->q_ptr;
22738 		}
22739 	} while (multirt_send);
22740 	if (conn_outgoing_ill != NULL)
22741 		ill_refrele(conn_outgoing_ill);
22742 	return;
22743 
22744 	/*
22745 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22746 	 */
22747 broadcast:
22748 	{
22749 		/*
22750 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22751 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22752 		 * can be overridden stack-wide through the ip_broadcast_ttl
22753 		 * ndd tunable, or on a per-connection basis through the
22754 		 * IP_BROADCAST_TTL socket option.
22755 		 *
22756 		 * In the event that we are replying to incoming ICMP packets,
22757 		 * connp could be NULL.
22758 		 */
22759 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22760 		if (connp != NULL) {
22761 			if (connp->conn_dontroute)
22762 				ipha->ipha_ttl = 1;
22763 			else if (connp->conn_broadcast_ttl != 0)
22764 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22765 		}
22766 
22767 		/*
22768 		 * Note that we are not doing a IRB_REFHOLD here.
22769 		 * Actually we don't care if the list changes i.e
22770 		 * if somebody deletes an IRE from the list while
22771 		 * we drop the lock, the next time we come around
22772 		 * ire_next will be NULL and hence we won't send
22773 		 * out multiple copies which is fine.
22774 		 */
22775 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22776 		ire1 = ire->ire_next;
22777 		if (conn_outgoing_ill != NULL) {
22778 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22779 				ASSERT(ire1 == ire->ire_next);
22780 				if (ire1 != NULL && ire1->ire_addr == dst) {
22781 					ire_refrele(ire);
22782 					ire = ire1;
22783 					IRE_REFHOLD(ire);
22784 					ire1 = ire->ire_next;
22785 					continue;
22786 				}
22787 				rw_exit(&ire->ire_bucket->irb_lock);
22788 				/* Did not find a matching ill */
22789 				ip1dbg(("ip_wput_ire: broadcast with no "
22790 				    "matching IP_BOUND_IF ill %s dst %x\n",
22791 				    conn_outgoing_ill->ill_name, dst));
22792 				freemsg(first_mp);
22793 				if (ire != NULL)
22794 					ire_refrele(ire);
22795 				ill_refrele(conn_outgoing_ill);
22796 				return;
22797 			}
22798 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22799 			/*
22800 			 * If the next IRE has the same address and is not one
22801 			 * of the two copies that we need to send, try to see
22802 			 * whether this copy should be sent at all. This
22803 			 * assumes that we insert loopbacks first and then
22804 			 * non-loopbacks. This is acheived by inserting the
22805 			 * loopback always before non-loopback.
22806 			 * This is used to send a single copy of a broadcast
22807 			 * packet out all physical interfaces that have an
22808 			 * matching IRE_BROADCAST while also looping
22809 			 * back one copy (to ip_wput_local) for each
22810 			 * matching physical interface. However, we avoid
22811 			 * sending packets out different logical that match by
22812 			 * having ipif_up/ipif_down supress duplicate
22813 			 * IRE_BROADCASTS.
22814 			 *
22815 			 * This feature is currently used to get broadcasts
22816 			 * sent to multiple interfaces, when the broadcast
22817 			 * address being used applies to multiple interfaces.
22818 			 * For example, a whole net broadcast will be
22819 			 * replicated on every connected subnet of
22820 			 * the target net.
22821 			 *
22822 			 * Each zone has its own set of IRE_BROADCASTs, so that
22823 			 * we're able to distribute inbound packets to multiple
22824 			 * zones who share a broadcast address. We avoid looping
22825 			 * back outbound packets in different zones but on the
22826 			 * same ill, as the application would see duplicates.
22827 			 *
22828 			 * This logic assumes that ire_add_v4() groups the
22829 			 * IRE_BROADCAST entries so that those with the same
22830 			 * ire_addr are kept together.
22831 			 */
22832 			ire_ill = ire->ire_ipif->ipif_ill;
22833 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22834 				while (ire1 != NULL && ire1->ire_addr == dst) {
22835 					ire1_ill = ire1->ire_ipif->ipif_ill;
22836 					if (ire1_ill != ire_ill)
22837 						break;
22838 					ire1 = ire1->ire_next;
22839 				}
22840 			}
22841 		}
22842 		ASSERT(multirt_send == B_FALSE);
22843 		if (ire1 != NULL && ire1->ire_addr == dst) {
22844 			if ((ire->ire_flags & RTF_MULTIRT) &&
22845 			    (ire1->ire_flags & RTF_MULTIRT)) {
22846 				/*
22847 				 * We are in the multirouting case.
22848 				 * The message must be sent at least
22849 				 * on both ires. These ires have been
22850 				 * inserted AFTER the standard ones
22851 				 * in ip_rt_add(). There are thus no
22852 				 * other ire entries for the destination
22853 				 * address in the rest of the bucket
22854 				 * that do not have the RTF_MULTIRT
22855 				 * flag. We don't process a copy
22856 				 * of the message here. This will be
22857 				 * done in the final sending loop.
22858 				 */
22859 				multirt_send = B_TRUE;
22860 			} else {
22861 				next_mp = ip_copymsg(first_mp);
22862 				if (next_mp != NULL)
22863 					IRE_REFHOLD(ire1);
22864 			}
22865 		}
22866 		rw_exit(&ire->ire_bucket->irb_lock);
22867 	}
22868 
22869 	if (stq) {
22870 		/*
22871 		 * A non-NULL send-to queue means this packet is going
22872 		 * out of this machine.
22873 		 */
22874 		out_ill = (ill_t *)stq->q_ptr;
22875 
22876 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22877 		ttl_protocol = ((uint16_t *)ipha)[4];
22878 		/*
22879 		 * We accumulate the pseudo header checksum in cksum.
22880 		 * This is pretty hairy code, so watch close.  One
22881 		 * thing to keep in mind is that UDP and TCP have
22882 		 * stored their respective datagram lengths in their
22883 		 * checksum fields.  This lines things up real nice.
22884 		 */
22885 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22886 		    (src >> 16) + (src & 0xFFFF);
22887 		/*
22888 		 * We assume the udp checksum field contains the
22889 		 * length, so to compute the pseudo header checksum,
22890 		 * all we need is the protocol number and src/dst.
22891 		 */
22892 		/* Provide the checksums for UDP and TCP. */
22893 		if ((PROTO == IPPROTO_TCP) &&
22894 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22895 			/* hlen gets the number of uchar_ts in the IP header */
22896 			hlen = (V_HLEN & 0xF) << 2;
22897 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22898 			IP_STAT(ipst, ip_out_sw_cksum);
22899 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22900 			    LENGTH - hlen);
22901 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22902 		} else if (PROTO == IPPROTO_SCTP &&
22903 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22904 			sctp_hdr_t	*sctph;
22905 
22906 			hlen = (V_HLEN & 0xF) << 2;
22907 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22908 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22909 			sctph->sh_chksum = 0;
22910 #ifdef	DEBUG
22911 			if (!skip_sctp_cksum)
22912 #endif
22913 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22914 		} else {
22915 			queue_t	*dev_q = stq->q_next;
22916 
22917 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22918 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22919 blocked:
22920 				ipha->ipha_ident = ip_hdr_included;
22921 				/*
22922 				 * If we don't have a conn to apply
22923 				 * backpressure, free the message.
22924 				 * In the ire_send path, we don't know
22925 				 * the position to requeue the packet. Rather
22926 				 * than reorder packets, we just drop this
22927 				 * packet.
22928 				 */
22929 				if (ipst->ips_ip_output_queue &&
22930 				    connp != NULL &&
22931 				    caller != IRE_SEND) {
22932 					if (caller == IP_WSRV) {
22933 						idl_tx_list_t *idl_txl;
22934 
22935 						idl_txl =
22936 						    &ipst->ips_idl_tx_list[0];
22937 						connp->conn_did_putbq = 1;
22938 						(void) putbq(connp->conn_wq,
22939 						    first_mp);
22940 						conn_drain_insert(connp,
22941 						    idl_txl);
22942 						/*
22943 						 * This is the service thread,
22944 						 * and the queue is already
22945 						 * noenabled. The check for
22946 						 * canput and the putbq is not
22947 						 * atomic. So we need to check
22948 						 * again.
22949 						 */
22950 						if (canput(stq->q_next))
22951 							connp->conn_did_putbq
22952 							    = 0;
22953 						IP_STAT(ipst, ip_conn_flputbq);
22954 					} else {
22955 						/*
22956 						 * We are not the service proc.
22957 						 * ip_wsrv will be scheduled or
22958 						 * is already running.
22959 						 */
22960 
22961 						(void) putq(connp->conn_wq,
22962 						    first_mp);
22963 					}
22964 				} else {
22965 					out_ill = (ill_t *)stq->q_ptr;
22966 					BUMP_MIB(out_ill->ill_ip_mib,
22967 					    ipIfStatsOutDiscards);
22968 					freemsg(first_mp);
22969 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22970 					    "ip_wput_ire_end: q %p (%S)",
22971 					    q, "discard");
22972 				}
22973 				ire_refrele(ire);
22974 				if (next_mp) {
22975 					ire_refrele(ire1);
22976 					freemsg(next_mp);
22977 				}
22978 				if (conn_outgoing_ill != NULL)
22979 					ill_refrele(conn_outgoing_ill);
22980 				return;
22981 			}
22982 			if ((PROTO == IPPROTO_UDP) &&
22983 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22984 				/*
22985 				 * hlen gets the number of uchar_ts in the
22986 				 * IP header
22987 				 */
22988 				hlen = (V_HLEN & 0xF) << 2;
22989 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22990 				max_frag = ire->ire_max_frag;
22991 				if (*up != 0) {
22992 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22993 					    up, PROTO, hlen, LENGTH, max_frag,
22994 					    ipsec_len, cksum);
22995 					/* Software checksum? */
22996 					if (DB_CKSUMFLAGS(mp) == 0) {
22997 						IP_STAT(ipst, ip_out_sw_cksum);
22998 						IP_STAT_UPDATE(ipst,
22999 						    ip_udp_out_sw_cksum_bytes,
23000 						    LENGTH - hlen);
23001 					}
23002 				}
23003 			}
23004 		}
23005 		/*
23006 		 * Need to do this even when fragmenting. The local
23007 		 * loopback can be done without computing checksums
23008 		 * but forwarding out other interface must be done
23009 		 * after the IP checksum (and ULP checksums) have been
23010 		 * computed.
23011 		 *
23012 		 * NOTE : multicast_forward is set only if this packet
23013 		 * originated from ip_wput. For packets originating from
23014 		 * ip_wput_multicast, it is not set.
23015 		 */
23016 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23017 multi_loopback:
23018 			ip2dbg(("ip_wput: multicast, loop %d\n",
23019 			    conn_multicast_loop));
23020 
23021 			/*  Forget header checksum offload */
23022 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23023 
23024 			/*
23025 			 * Local loopback of multicasts?  Check the
23026 			 * ill.
23027 			 *
23028 			 * Note that the loopback function will not come
23029 			 * in through ip_rput - it will only do the
23030 			 * client fanout thus we need to do an mforward
23031 			 * as well.  The is different from the BSD
23032 			 * logic.
23033 			 */
23034 			if (ill != NULL) {
23035 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23036 				    ALL_ZONES) != NULL) {
23037 					/*
23038 					 * Pass along the virtual output q.
23039 					 * ip_wput_local() will distribute the
23040 					 * packet to all the matching zones,
23041 					 * except the sending zone when
23042 					 * IP_MULTICAST_LOOP is false.
23043 					 */
23044 					ip_multicast_loopback(q, ill, first_mp,
23045 					    conn_multicast_loop ? 0 :
23046 					    IP_FF_NO_MCAST_LOOP, zoneid);
23047 				}
23048 			}
23049 			if (ipha->ipha_ttl == 0) {
23050 				/*
23051 				 * 0 => only to this host i.e. we are
23052 				 * done. We are also done if this was the
23053 				 * loopback interface since it is sufficient
23054 				 * to loopback one copy of a multicast packet.
23055 				 */
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, "loopback");
23060 				ire_refrele(ire);
23061 				if (conn_outgoing_ill != NULL)
23062 					ill_refrele(conn_outgoing_ill);
23063 				return;
23064 			}
23065 			/*
23066 			 * ILLF_MULTICAST is checked in ip_newroute
23067 			 * i.e. we don't need to check it here since
23068 			 * all IRE_CACHEs come from ip_newroute.
23069 			 * For multicast traffic, SO_DONTROUTE is interpreted
23070 			 * to mean only send the packet out the interface
23071 			 * (optionally specified with IP_MULTICAST_IF)
23072 			 * and do not forward it out additional interfaces.
23073 			 * RSVP and the rsvp daemon is an example of a
23074 			 * protocol and user level process that
23075 			 * handles it's own routing. Hence, it uses the
23076 			 * SO_DONTROUTE option to accomplish this.
23077 			 */
23078 
23079 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23080 			    ill != NULL) {
23081 				/* Unconditionally redo the checksum */
23082 				ipha->ipha_hdr_checksum = 0;
23083 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23084 
23085 				/*
23086 				 * If this needs to go out secure, we need
23087 				 * to wait till we finish the IPsec
23088 				 * processing.
23089 				 */
23090 				if (ipsec_len == 0 &&
23091 				    ip_mforward(ill, ipha, mp)) {
23092 					freemsg(first_mp);
23093 					ip1dbg(("ip_wput: mforward failed\n"));
23094 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23095 					    "ip_wput_ire_end: q %p (%S)",
23096 					    q, "mforward failed");
23097 					ire_refrele(ire);
23098 					if (conn_outgoing_ill != NULL)
23099 						ill_refrele(conn_outgoing_ill);
23100 					return;
23101 				}
23102 			}
23103 		}
23104 		max_frag = ire->ire_max_frag;
23105 		cksum += ttl_protocol;
23106 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23107 			/* No fragmentation required for this one. */
23108 			/*
23109 			 * Don't use frag_flag if packet is pre-built or source
23110 			 * routed or if multicast (since multicast packets do
23111 			 * not solicit ICMP "packet too big" messages).
23112 			 */
23113 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23114 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23115 			    !ip_source_route_included(ipha)) &&
23116 			    !CLASSD(ipha->ipha_dst))
23117 				ipha->ipha_fragment_offset_and_flags |=
23118 				    htons(ire->ire_frag_flag);
23119 
23120 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23121 				/* Complete the IP header checksum. */
23122 				cksum += ipha->ipha_ident;
23123 				cksum += (v_hlen_tos_len >> 16)+
23124 				    (v_hlen_tos_len & 0xFFFF);
23125 				cksum += ipha->ipha_fragment_offset_and_flags;
23126 				hlen = (V_HLEN & 0xF) -
23127 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23128 				if (hlen) {
23129 checksumoptions:
23130 					/*
23131 					 * Account for the IP Options in the IP
23132 					 * header checksum.
23133 					 */
23134 					up = (uint16_t *)(rptr+
23135 					    IP_SIMPLE_HDR_LENGTH);
23136 					do {
23137 						cksum += up[0];
23138 						cksum += up[1];
23139 						up += 2;
23140 					} while (--hlen);
23141 				}
23142 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23143 				cksum = ~(cksum + (cksum >> 16));
23144 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23145 			}
23146 			if (ipsec_len != 0) {
23147 				ipsec_out_process(q, first_mp, ire, ill_index);
23148 				if (!next_mp) {
23149 					ire_refrele(ire);
23150 					if (conn_outgoing_ill != NULL)
23151 						ill_refrele(conn_outgoing_ill);
23152 					return;
23153 				}
23154 				goto next;
23155 			}
23156 
23157 			/*
23158 			 * multirt_send has already been handled
23159 			 * for broadcast, but not yet for multicast
23160 			 * or IP options.
23161 			 */
23162 			if (next_mp == NULL) {
23163 				if (ire->ire_flags & RTF_MULTIRT) {
23164 					multirt_send = B_TRUE;
23165 				}
23166 			}
23167 
23168 			/*
23169 			 * In most cases, the emission loop below is
23170 			 * entered only once. Only in the case where
23171 			 * the ire holds the RTF_MULTIRT flag, do we loop
23172 			 * to process all RTF_MULTIRT ires in the bucket,
23173 			 * and send the packet through all crossed
23174 			 * RTF_MULTIRT routes.
23175 			 */
23176 			do {
23177 				if (multirt_send) {
23178 					irb_t *irb;
23179 
23180 					irb = ire->ire_bucket;
23181 					ASSERT(irb != NULL);
23182 					/*
23183 					 * We are in a multiple send case,
23184 					 * need to get the next IRE and make
23185 					 * a duplicate of the packet.
23186 					 */
23187 					IRB_REFHOLD(irb);
23188 					for (ire1 = ire->ire_next;
23189 					    ire1 != NULL;
23190 					    ire1 = ire1->ire_next) {
23191 						if (!(ire1->ire_flags &
23192 						    RTF_MULTIRT))
23193 							continue;
23194 
23195 						if (ire1->ire_addr !=
23196 						    ire->ire_addr)
23197 							continue;
23198 
23199 						if (ire1->ire_marks &
23200 						    (IRE_MARK_CONDEMNED |
23201 						    IRE_MARK_TESTHIDDEN))
23202 							continue;
23203 
23204 						/* Got one */
23205 						IRE_REFHOLD(ire1);
23206 						break;
23207 					}
23208 					IRB_REFRELE(irb);
23209 
23210 					if (ire1 != NULL) {
23211 						next_mp = copyb(mp);
23212 						if ((next_mp == NULL) ||
23213 						    ((mp->b_cont != NULL) &&
23214 						    ((next_mp->b_cont =
23215 						    dupmsg(mp->b_cont))
23216 						    == NULL))) {
23217 							freemsg(next_mp);
23218 							next_mp = NULL;
23219 							ire_refrele(ire1);
23220 							ire1 = NULL;
23221 						}
23222 					}
23223 
23224 					/*
23225 					 * Last multiroute ire; don't loop
23226 					 * anymore. The emission is over
23227 					 * and next_mp is NULL.
23228 					 */
23229 					if (ire1 == NULL) {
23230 						multirt_send = B_FALSE;
23231 					}
23232 				}
23233 
23234 				out_ill = ire_to_ill(ire);
23235 				DTRACE_PROBE4(ip4__physical__out__start,
23236 				    ill_t *, NULL,
23237 				    ill_t *, out_ill,
23238 				    ipha_t *, ipha, mblk_t *, mp);
23239 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23240 				    ipst->ips_ipv4firewall_physical_out,
23241 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23242 				DTRACE_PROBE1(ip4__physical__out__end,
23243 				    mblk_t *, mp);
23244 				if (mp == NULL)
23245 					goto release_ire_and_ill_2;
23246 
23247 				ASSERT(ipsec_len == 0);
23248 				mp->b_prev =
23249 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23250 				DTRACE_PROBE2(ip__xmit__2,
23251 				    mblk_t *, mp, ire_t *, ire);
23252 				pktxmit_state = ip_xmit_v4(mp, ire,
23253 				    NULL, B_TRUE, connp);
23254 				if ((pktxmit_state == SEND_FAILED) ||
23255 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23256 release_ire_and_ill_2:
23257 					if (next_mp) {
23258 						freemsg(next_mp);
23259 						ire_refrele(ire1);
23260 					}
23261 					ire_refrele(ire);
23262 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23263 					    "ip_wput_ire_end: q %p (%S)",
23264 					    q, "discard MDATA");
23265 					if (conn_outgoing_ill != NULL)
23266 						ill_refrele(conn_outgoing_ill);
23267 					return;
23268 				}
23269 
23270 				if (CLASSD(dst)) {
23271 					BUMP_MIB(out_ill->ill_ip_mib,
23272 					    ipIfStatsHCOutMcastPkts);
23273 					UPDATE_MIB(out_ill->ill_ip_mib,
23274 					    ipIfStatsHCOutMcastOctets,
23275 					    LENGTH);
23276 				} else if (ire->ire_type == IRE_BROADCAST) {
23277 					BUMP_MIB(out_ill->ill_ip_mib,
23278 					    ipIfStatsHCOutBcastPkts);
23279 				}
23280 
23281 				if (multirt_send) {
23282 					/*
23283 					 * We are in a multiple send case,
23284 					 * need to re-enter the sending loop
23285 					 * using the next ire.
23286 					 */
23287 					ire_refrele(ire);
23288 					ire = ire1;
23289 					stq = ire->ire_stq;
23290 					mp = next_mp;
23291 					next_mp = NULL;
23292 					ipha = (ipha_t *)mp->b_rptr;
23293 					ill_index = Q_TO_INDEX(stq);
23294 				}
23295 			} while (multirt_send);
23296 
23297 			if (!next_mp) {
23298 				/*
23299 				 * Last copy going out (the ultra-common
23300 				 * case).  Note that we intentionally replicate
23301 				 * the putnext rather than calling it before
23302 				 * the next_mp check in hopes of a little
23303 				 * tail-call action out of the compiler.
23304 				 */
23305 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23306 				    "ip_wput_ire_end: q %p (%S)",
23307 				    q, "last copy out(1)");
23308 				ire_refrele(ire);
23309 				if (conn_outgoing_ill != NULL)
23310 					ill_refrele(conn_outgoing_ill);
23311 				return;
23312 			}
23313 			/* More copies going out below. */
23314 		} else {
23315 			int offset;
23316 fragmentit:
23317 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23318 			/*
23319 			 * If this would generate a icmp_frag_needed message,
23320 			 * we need to handle it before we do the IPsec
23321 			 * processing. Otherwise, we need to strip the IPsec
23322 			 * headers before we send up the message to the ULPs
23323 			 * which becomes messy and difficult.
23324 			 */
23325 			if (ipsec_len != 0) {
23326 				if ((max_frag < (unsigned int)(LENGTH +
23327 				    ipsec_len)) && (offset & IPH_DF)) {
23328 					out_ill = (ill_t *)stq->q_ptr;
23329 					BUMP_MIB(out_ill->ill_ip_mib,
23330 					    ipIfStatsOutFragFails);
23331 					BUMP_MIB(out_ill->ill_ip_mib,
23332 					    ipIfStatsOutFragReqds);
23333 					ipha->ipha_hdr_checksum = 0;
23334 					ipha->ipha_hdr_checksum =
23335 					    (uint16_t)ip_csum_hdr(ipha);
23336 					icmp_frag_needed(ire->ire_stq, first_mp,
23337 					    max_frag, zoneid, ipst);
23338 					if (!next_mp) {
23339 						ire_refrele(ire);
23340 						if (conn_outgoing_ill != NULL) {
23341 							ill_refrele(
23342 							    conn_outgoing_ill);
23343 						}
23344 						return;
23345 					}
23346 				} else {
23347 					/*
23348 					 * This won't cause a icmp_frag_needed
23349 					 * message. to be generated. Send it on
23350 					 * the wire. Note that this could still
23351 					 * cause fragmentation and all we
23352 					 * do is the generation of the message
23353 					 * to the ULP if needed before IPsec.
23354 					 */
23355 					if (!next_mp) {
23356 						ipsec_out_process(q, first_mp,
23357 						    ire, ill_index);
23358 						TRACE_2(TR_FAC_IP,
23359 						    TR_IP_WPUT_IRE_END,
23360 						    "ip_wput_ire_end: q %p "
23361 						    "(%S)", q,
23362 						    "last ipsec_out_process");
23363 						ire_refrele(ire);
23364 						if (conn_outgoing_ill != NULL) {
23365 							ill_refrele(
23366 							    conn_outgoing_ill);
23367 						}
23368 						return;
23369 					}
23370 					ipsec_out_process(q, first_mp,
23371 					    ire, ill_index);
23372 				}
23373 			} else {
23374 				/*
23375 				 * Initiate IPPF processing. For
23376 				 * fragmentable packets we finish
23377 				 * all QOS packet processing before
23378 				 * calling:
23379 				 * ip_wput_ire_fragmentit->ip_wput_frag
23380 				 */
23381 
23382 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23383 					ip_process(IPP_LOCAL_OUT, &mp,
23384 					    ill_index);
23385 					if (mp == NULL) {
23386 						out_ill = (ill_t *)stq->q_ptr;
23387 						BUMP_MIB(out_ill->ill_ip_mib,
23388 						    ipIfStatsOutDiscards);
23389 						if (next_mp != NULL) {
23390 							freemsg(next_mp);
23391 							ire_refrele(ire1);
23392 						}
23393 						ire_refrele(ire);
23394 						TRACE_2(TR_FAC_IP,
23395 						    TR_IP_WPUT_IRE_END,
23396 						    "ip_wput_ire: q %p (%S)",
23397 						    q, "discard MDATA");
23398 						if (conn_outgoing_ill != NULL) {
23399 							ill_refrele(
23400 							    conn_outgoing_ill);
23401 						}
23402 						return;
23403 					}
23404 				}
23405 				if (!next_mp) {
23406 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23407 					    "ip_wput_ire_end: q %p (%S)",
23408 					    q, "last fragmentation");
23409 					ip_wput_ire_fragmentit(mp, ire,
23410 					    zoneid, ipst, connp);
23411 					ire_refrele(ire);
23412 					if (conn_outgoing_ill != NULL)
23413 						ill_refrele(conn_outgoing_ill);
23414 					return;
23415 				}
23416 				ip_wput_ire_fragmentit(mp, ire,
23417 				    zoneid, ipst, connp);
23418 			}
23419 		}
23420 	} else {
23421 nullstq:
23422 		/* A NULL stq means the destination address is local. */
23423 		UPDATE_OB_PKT_COUNT(ire);
23424 		ire->ire_last_used_time = lbolt;
23425 		ASSERT(ire->ire_ipif != NULL);
23426 		if (!next_mp) {
23427 			/*
23428 			 * Is there an "in" and "out" for traffic local
23429 			 * to a host (loopback)?  The code in Solaris doesn't
23430 			 * explicitly draw a line in its code for in vs out,
23431 			 * so we've had to draw a line in the sand: ip_wput_ire
23432 			 * is considered to be the "output" side and
23433 			 * ip_wput_local to be the "input" side.
23434 			 */
23435 			out_ill = ire_to_ill(ire);
23436 
23437 			/*
23438 			 * DTrace this as ip:::send.  A blocked packet will
23439 			 * fire the send probe, but not the receive probe.
23440 			 */
23441 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23442 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23443 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23444 
23445 			DTRACE_PROBE4(ip4__loopback__out__start,
23446 			    ill_t *, NULL, ill_t *, out_ill,
23447 			    ipha_t *, ipha, mblk_t *, first_mp);
23448 
23449 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23450 			    ipst->ips_ipv4firewall_loopback_out,
23451 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23452 
23453 			DTRACE_PROBE1(ip4__loopback__out_end,
23454 			    mblk_t *, first_mp);
23455 
23456 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23457 			    "ip_wput_ire_end: q %p (%S)",
23458 			    q, "local address");
23459 
23460 			if (first_mp != NULL)
23461 				ip_wput_local(q, out_ill, ipha,
23462 				    first_mp, ire, 0, ire->ire_zoneid);
23463 			ire_refrele(ire);
23464 			if (conn_outgoing_ill != NULL)
23465 				ill_refrele(conn_outgoing_ill);
23466 			return;
23467 		}
23468 
23469 		out_ill = ire_to_ill(ire);
23470 
23471 		/*
23472 		 * DTrace this as ip:::send.  A blocked packet will fire the
23473 		 * send probe, but not the receive probe.
23474 		 */
23475 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23476 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23477 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23478 
23479 		DTRACE_PROBE4(ip4__loopback__out__start,
23480 		    ill_t *, NULL, ill_t *, out_ill,
23481 		    ipha_t *, ipha, mblk_t *, first_mp);
23482 
23483 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23484 		    ipst->ips_ipv4firewall_loopback_out,
23485 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23486 
23487 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23488 
23489 		if (first_mp != NULL)
23490 			ip_wput_local(q, out_ill, ipha,
23491 			    first_mp, ire, 0, ire->ire_zoneid);
23492 	}
23493 next:
23494 	/*
23495 	 * More copies going out to additional interfaces.
23496 	 * ire1 has already been held. We don't need the
23497 	 * "ire" anymore.
23498 	 */
23499 	ire_refrele(ire);
23500 	ire = ire1;
23501 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23502 	mp = next_mp;
23503 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23504 	ill = ire_to_ill(ire);
23505 	first_mp = mp;
23506 	if (ipsec_len != 0) {
23507 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23508 		mp = mp->b_cont;
23509 	}
23510 	dst = ire->ire_addr;
23511 	ipha = (ipha_t *)mp->b_rptr;
23512 	/*
23513 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23514 	 * Restore ipha_ident "no checksum" flag.
23515 	 */
23516 	src = orig_src;
23517 	ipha->ipha_ident = ip_hdr_included;
23518 	goto another;
23519 
23520 #undef	rptr
23521 #undef	Q_TO_INDEX
23522 }
23523 
23524 /*
23525  * Routine to allocate a message that is used to notify the ULP about MDT.
23526  * The caller may provide a pointer to the link-layer MDT capabilities,
23527  * or NULL if MDT is to be disabled on the stream.
23528  */
23529 mblk_t *
23530 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23531 {
23532 	mblk_t *mp;
23533 	ip_mdt_info_t *mdti;
23534 	ill_mdt_capab_t *idst;
23535 
23536 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23537 		DB_TYPE(mp) = M_CTL;
23538 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23539 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23540 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23541 		idst = &(mdti->mdt_capab);
23542 
23543 		/*
23544 		 * If the caller provides us with the capability, copy
23545 		 * it over into our notification message; otherwise
23546 		 * we zero out the capability portion.
23547 		 */
23548 		if (isrc != NULL)
23549 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23550 		else
23551 			bzero((caddr_t)idst, sizeof (*idst));
23552 	}
23553 	return (mp);
23554 }
23555 
23556 /*
23557  * Routine which determines whether MDT can be enabled on the destination
23558  * IRE and IPC combination, and if so, allocates and returns the MDT
23559  * notification mblk that may be used by ULP.  We also check if we need to
23560  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23561  * MDT usage in the past have been lifted.  This gets called during IP
23562  * and ULP binding.
23563  */
23564 mblk_t *
23565 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23566     ill_mdt_capab_t *mdt_cap)
23567 {
23568 	mblk_t *mp;
23569 	boolean_t rc = B_FALSE;
23570 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23571 
23572 	ASSERT(dst_ire != NULL);
23573 	ASSERT(connp != NULL);
23574 	ASSERT(mdt_cap != NULL);
23575 
23576 	/*
23577 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23578 	 * Multidata, which is handled in tcp_multisend().  This
23579 	 * is the reason why we do all these checks here, to ensure
23580 	 * that we don't enable Multidata for the cases which we
23581 	 * can't handle at the moment.
23582 	 */
23583 	do {
23584 		/* Only do TCP at the moment */
23585 		if (connp->conn_ulp != IPPROTO_TCP)
23586 			break;
23587 
23588 		/*
23589 		 * IPsec outbound policy present?  Note that we get here
23590 		 * after calling ipsec_conn_cache_policy() where the global
23591 		 * policy checking is performed.  conn_latch will be
23592 		 * non-NULL as long as there's a policy defined,
23593 		 * i.e. conn_out_enforce_policy may be NULL in such case
23594 		 * when the connection is non-secure, and hence we check
23595 		 * further if the latch refers to an outbound policy.
23596 		 */
23597 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23598 			break;
23599 
23600 		/* CGTP (multiroute) is enabled? */
23601 		if (dst_ire->ire_flags & RTF_MULTIRT)
23602 			break;
23603 
23604 		/* Outbound IPQoS enabled? */
23605 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23606 			/*
23607 			 * In this case, we disable MDT for this and all
23608 			 * future connections going over the interface.
23609 			 */
23610 			mdt_cap->ill_mdt_on = 0;
23611 			break;
23612 		}
23613 
23614 		/* socket option(s) present? */
23615 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23616 			break;
23617 
23618 		rc = B_TRUE;
23619 	/* CONSTCOND */
23620 	} while (0);
23621 
23622 	/* Remember the result */
23623 	connp->conn_mdt_ok = rc;
23624 
23625 	if (!rc)
23626 		return (NULL);
23627 	else if (!mdt_cap->ill_mdt_on) {
23628 		/*
23629 		 * If MDT has been previously turned off in the past, and we
23630 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23631 		 * then enable it for this interface.
23632 		 */
23633 		mdt_cap->ill_mdt_on = 1;
23634 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23635 		    "interface %s\n", ill_name));
23636 	}
23637 
23638 	/* Allocate the MDT info mblk */
23639 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23640 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23641 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23642 		return (NULL);
23643 	}
23644 	return (mp);
23645 }
23646 
23647 /*
23648  * Routine to allocate a message that is used to notify the ULP about LSO.
23649  * The caller may provide a pointer to the link-layer LSO capabilities,
23650  * or NULL if LSO is to be disabled on the stream.
23651  */
23652 mblk_t *
23653 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23654 {
23655 	mblk_t *mp;
23656 	ip_lso_info_t *lsoi;
23657 	ill_lso_capab_t *idst;
23658 
23659 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23660 		DB_TYPE(mp) = M_CTL;
23661 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23662 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23663 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23664 		idst = &(lsoi->lso_capab);
23665 
23666 		/*
23667 		 * If the caller provides us with the capability, copy
23668 		 * it over into our notification message; otherwise
23669 		 * we zero out the capability portion.
23670 		 */
23671 		if (isrc != NULL)
23672 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23673 		else
23674 			bzero((caddr_t)idst, sizeof (*idst));
23675 	}
23676 	return (mp);
23677 }
23678 
23679 /*
23680  * Routine which determines whether LSO can be enabled on the destination
23681  * IRE and IPC combination, and if so, allocates and returns the LSO
23682  * notification mblk that may be used by ULP.  We also check if we need to
23683  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23684  * LSO usage in the past have been lifted.  This gets called during IP
23685  * and ULP binding.
23686  */
23687 mblk_t *
23688 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23689     ill_lso_capab_t *lso_cap)
23690 {
23691 	mblk_t *mp;
23692 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23693 
23694 	ASSERT(dst_ire != NULL);
23695 	ASSERT(connp != NULL);
23696 	ASSERT(lso_cap != NULL);
23697 
23698 	connp->conn_lso_ok = B_TRUE;
23699 
23700 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23701 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23702 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23703 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23704 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23705 		connp->conn_lso_ok = B_FALSE;
23706 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23707 			/*
23708 			 * Disable LSO for this and all future connections going
23709 			 * over the interface.
23710 			 */
23711 			lso_cap->ill_lso_on = 0;
23712 		}
23713 	}
23714 
23715 	if (!connp->conn_lso_ok)
23716 		return (NULL);
23717 	else if (!lso_cap->ill_lso_on) {
23718 		/*
23719 		 * If LSO has been previously turned off in the past, and we
23720 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23721 		 * then enable it for this interface.
23722 		 */
23723 		lso_cap->ill_lso_on = 1;
23724 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23725 		    ill_name));
23726 	}
23727 
23728 	/* Allocate the LSO info mblk */
23729 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23730 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23731 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23732 
23733 	return (mp);
23734 }
23735 
23736 /*
23737  * Create destination address attribute, and fill it with the physical
23738  * destination address and SAP taken from the template DL_UNITDATA_REQ
23739  * message block.
23740  */
23741 boolean_t
23742 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23743 {
23744 	dl_unitdata_req_t *dlurp;
23745 	pattr_t *pa;
23746 	pattrinfo_t pa_info;
23747 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23748 	uint_t das_len, das_off;
23749 
23750 	ASSERT(dlmp != NULL);
23751 
23752 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23753 	das_len = dlurp->dl_dest_addr_length;
23754 	das_off = dlurp->dl_dest_addr_offset;
23755 
23756 	pa_info.type = PATTR_DSTADDRSAP;
23757 	pa_info.len = sizeof (**das) + das_len - 1;
23758 
23759 	/* create and associate the attribute */
23760 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23761 	if (pa != NULL) {
23762 		ASSERT(*das != NULL);
23763 		(*das)->addr_is_group = 0;
23764 		(*das)->addr_len = (uint8_t)das_len;
23765 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23766 	}
23767 
23768 	return (pa != NULL);
23769 }
23770 
23771 /*
23772  * Create hardware checksum attribute and fill it with the values passed.
23773  */
23774 boolean_t
23775 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23776     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23777 {
23778 	pattr_t *pa;
23779 	pattrinfo_t pa_info;
23780 
23781 	ASSERT(mmd != NULL);
23782 
23783 	pa_info.type = PATTR_HCKSUM;
23784 	pa_info.len = sizeof (pattr_hcksum_t);
23785 
23786 	/* create and associate the attribute */
23787 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23788 	if (pa != NULL) {
23789 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23790 
23791 		hck->hcksum_start_offset = start_offset;
23792 		hck->hcksum_stuff_offset = stuff_offset;
23793 		hck->hcksum_end_offset = end_offset;
23794 		hck->hcksum_flags = flags;
23795 	}
23796 	return (pa != NULL);
23797 }
23798 
23799 /*
23800  * Create zerocopy attribute and fill it with the specified flags
23801  */
23802 boolean_t
23803 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23804 {
23805 	pattr_t *pa;
23806 	pattrinfo_t pa_info;
23807 
23808 	ASSERT(mmd != NULL);
23809 	pa_info.type = PATTR_ZCOPY;
23810 	pa_info.len = sizeof (pattr_zcopy_t);
23811 
23812 	/* create and associate the attribute */
23813 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23814 	if (pa != NULL) {
23815 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23816 
23817 		zcopy->zcopy_flags = flags;
23818 	}
23819 	return (pa != NULL);
23820 }
23821 
23822 /*
23823  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23824  * block chain. We could rewrite to handle arbitrary message block chains but
23825  * that would make the code complicated and slow. Right now there three
23826  * restrictions:
23827  *
23828  *   1. The first message block must contain the complete IP header and
23829  *	at least 1 byte of payload data.
23830  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23831  *	so that we can use a single Multidata message.
23832  *   3. No frag must be distributed over two or more message blocks so
23833  *	that we don't need more than two packet descriptors per frag.
23834  *
23835  * The above restrictions allow us to support userland applications (which
23836  * will send down a single message block) and NFS over UDP (which will
23837  * send down a chain of at most three message blocks).
23838  *
23839  * We also don't use MDT for payloads with less than or equal to
23840  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23841  */
23842 boolean_t
23843 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23844 {
23845 	int	blocks;
23846 	ssize_t	total, missing, size;
23847 
23848 	ASSERT(mp != NULL);
23849 	ASSERT(hdr_len > 0);
23850 
23851 	size = MBLKL(mp) - hdr_len;
23852 	if (size <= 0)
23853 		return (B_FALSE);
23854 
23855 	/* The first mblk contains the header and some payload. */
23856 	blocks = 1;
23857 	total = size;
23858 	size %= len;
23859 	missing = (size == 0) ? 0 : (len - size);
23860 	mp = mp->b_cont;
23861 
23862 	while (mp != NULL) {
23863 		/*
23864 		 * Give up if we encounter a zero length message block.
23865 		 * In practice, this should rarely happen and therefore
23866 		 * not worth the trouble of freeing and re-linking the
23867 		 * mblk from the chain to handle such case.
23868 		 */
23869 		if ((size = MBLKL(mp)) == 0)
23870 			return (B_FALSE);
23871 
23872 		/* Too many payload buffers for a single Multidata message? */
23873 		if (++blocks > MULTIDATA_MAX_PBUFS)
23874 			return (B_FALSE);
23875 
23876 		total += size;
23877 		/* Is a frag distributed over two or more message blocks? */
23878 		if (missing > size)
23879 			return (B_FALSE);
23880 		size -= missing;
23881 
23882 		size %= len;
23883 		missing = (size == 0) ? 0 : (len - size);
23884 
23885 		mp = mp->b_cont;
23886 	}
23887 
23888 	return (total > ip_wput_frag_mdt_min);
23889 }
23890 
23891 /*
23892  * Outbound IPv4 fragmentation routine using MDT.
23893  */
23894 static void
23895 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23896     uint32_t frag_flag, int offset)
23897 {
23898 	ipha_t		*ipha_orig;
23899 	int		i1, ip_data_end;
23900 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23901 	mblk_t		*hdr_mp, *md_mp = NULL;
23902 	unsigned char	*hdr_ptr, *pld_ptr;
23903 	multidata_t	*mmd;
23904 	ip_pdescinfo_t	pdi;
23905 	ill_t		*ill;
23906 	ip_stack_t	*ipst = ire->ire_ipst;
23907 
23908 	ASSERT(DB_TYPE(mp) == M_DATA);
23909 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23910 
23911 	ill = ire_to_ill(ire);
23912 	ASSERT(ill != NULL);
23913 
23914 	ipha_orig = (ipha_t *)mp->b_rptr;
23915 	mp->b_rptr += sizeof (ipha_t);
23916 
23917 	/* Calculate how many packets we will send out */
23918 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23919 	pkts = (i1 + len - 1) / len;
23920 	ASSERT(pkts > 1);
23921 
23922 	/* Allocate a message block which will hold all the IP Headers. */
23923 	wroff = ipst->ips_ip_wroff_extra;
23924 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23925 
23926 	i1 = pkts * hdr_chunk_len;
23927 	/*
23928 	 * Create the header buffer, Multidata and destination address
23929 	 * and SAP attribute that should be associated with it.
23930 	 */
23931 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23932 	    ((hdr_mp->b_wptr += i1),
23933 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23934 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23935 		freemsg(mp);
23936 		if (md_mp == NULL) {
23937 			freemsg(hdr_mp);
23938 		} else {
23939 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23940 			freemsg(md_mp);
23941 		}
23942 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23943 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23944 		return;
23945 	}
23946 	IP_STAT(ipst, ip_frag_mdt_allocd);
23947 
23948 	/*
23949 	 * Add a payload buffer to the Multidata; this operation must not
23950 	 * fail, or otherwise our logic in this routine is broken.  There
23951 	 * is no memory allocation done by the routine, so any returned
23952 	 * failure simply tells us that we've done something wrong.
23953 	 *
23954 	 * A failure tells us that either we're adding the same payload
23955 	 * buffer more than once, or we're trying to add more buffers than
23956 	 * allowed.  None of the above cases should happen, and we panic
23957 	 * because either there's horrible heap corruption, and/or
23958 	 * programming mistake.
23959 	 */
23960 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23961 		goto pbuf_panic;
23962 
23963 	hdr_ptr = hdr_mp->b_rptr;
23964 	pld_ptr = mp->b_rptr;
23965 
23966 	/* Establish the ending byte offset, based on the starting offset. */
23967 	offset <<= 3;
23968 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23969 	    IP_SIMPLE_HDR_LENGTH;
23970 
23971 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23972 
23973 	while (pld_ptr < mp->b_wptr) {
23974 		ipha_t		*ipha;
23975 		uint16_t	offset_and_flags;
23976 		uint16_t	ip_len;
23977 		int		error;
23978 
23979 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23980 		ipha = (ipha_t *)(hdr_ptr + wroff);
23981 		ASSERT(OK_32PTR(ipha));
23982 		*ipha = *ipha_orig;
23983 
23984 		if (ip_data_end - offset > len) {
23985 			offset_and_flags = IPH_MF;
23986 		} else {
23987 			/*
23988 			 * Last frag. Set len to the length of this last piece.
23989 			 */
23990 			len = ip_data_end - offset;
23991 			/* A frag of a frag might have IPH_MF non-zero */
23992 			offset_and_flags =
23993 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23994 			    IPH_MF;
23995 		}
23996 		offset_and_flags |= (uint16_t)(offset >> 3);
23997 		offset_and_flags |= (uint16_t)frag_flag;
23998 		/* Store the offset and flags in the IP header. */
23999 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24000 
24001 		/* Store the length in the IP header. */
24002 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24003 		ipha->ipha_length = htons(ip_len);
24004 
24005 		/*
24006 		 * Set the IP header checksum.  Note that mp is just
24007 		 * the header, so this is easy to pass to ip_csum.
24008 		 */
24009 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24010 
24011 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24012 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24013 		    NULL, int, 0);
24014 
24015 		/*
24016 		 * Record offset and size of header and data of the next packet
24017 		 * in the multidata message.
24018 		 */
24019 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24020 		PDESC_PLD_INIT(&pdi);
24021 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24022 		ASSERT(i1 > 0);
24023 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24024 		if (i1 == len) {
24025 			pld_ptr += len;
24026 		} else {
24027 			i1 = len - i1;
24028 			mp = mp->b_cont;
24029 			ASSERT(mp != NULL);
24030 			ASSERT(MBLKL(mp) >= i1);
24031 			/*
24032 			 * Attach the next payload message block to the
24033 			 * multidata message.
24034 			 */
24035 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24036 				goto pbuf_panic;
24037 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24038 			pld_ptr = mp->b_rptr + i1;
24039 		}
24040 
24041 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24042 		    KM_NOSLEEP)) == NULL) {
24043 			/*
24044 			 * Any failure other than ENOMEM indicates that we
24045 			 * have passed in invalid pdesc info or parameters
24046 			 * to mmd_addpdesc, which must not happen.
24047 			 *
24048 			 * EINVAL is a result of failure on boundary checks
24049 			 * against the pdesc info contents.  It should not
24050 			 * happen, and we panic because either there's
24051 			 * horrible heap corruption, and/or programming
24052 			 * mistake.
24053 			 */
24054 			if (error != ENOMEM) {
24055 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24056 				    "pdesc logic error detected for "
24057 				    "mmd %p pinfo %p (%d)\n",
24058 				    (void *)mmd, (void *)&pdi, error);
24059 				/* NOTREACHED */
24060 			}
24061 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24062 			/* Free unattached payload message blocks as well */
24063 			md_mp->b_cont = mp->b_cont;
24064 			goto free_mmd;
24065 		}
24066 
24067 		/* Advance fragment offset. */
24068 		offset += len;
24069 
24070 		/* Advance to location for next header in the buffer. */
24071 		hdr_ptr += hdr_chunk_len;
24072 
24073 		/* Did we reach the next payload message block? */
24074 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24075 			mp = mp->b_cont;
24076 			/*
24077 			 * Attach the next message block with payload
24078 			 * data to the multidata message.
24079 			 */
24080 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24081 				goto pbuf_panic;
24082 			pld_ptr = mp->b_rptr;
24083 		}
24084 	}
24085 
24086 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24087 	ASSERT(mp->b_wptr == pld_ptr);
24088 
24089 	/* Update IP statistics */
24090 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24091 
24092 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24093 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24094 
24095 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24096 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24097 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24098 
24099 	if (pkt_type == OB_PKT) {
24100 		ire->ire_ob_pkt_count += pkts;
24101 		if (ire->ire_ipif != NULL)
24102 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24103 	} else {
24104 		/* The type is IB_PKT in the forwarding path. */
24105 		ire->ire_ib_pkt_count += pkts;
24106 		ASSERT(!IRE_IS_LOCAL(ire));
24107 		if (ire->ire_type & IRE_BROADCAST) {
24108 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24109 		} else {
24110 			UPDATE_MIB(ill->ill_ip_mib,
24111 			    ipIfStatsHCOutForwDatagrams, pkts);
24112 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24113 		}
24114 	}
24115 	ire->ire_last_used_time = lbolt;
24116 	/* Send it down */
24117 	putnext(ire->ire_stq, md_mp);
24118 	return;
24119 
24120 pbuf_panic:
24121 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24122 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24123 	    pbuf_idx);
24124 	/* NOTREACHED */
24125 }
24126 
24127 /*
24128  * Outbound IP fragmentation routine.
24129  *
24130  * NOTE : This routine does not ire_refrele the ire that is passed in
24131  * as the argument.
24132  */
24133 static void
24134 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24135     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24136 {
24137 	int		i1;
24138 	mblk_t		*ll_hdr_mp;
24139 	int 		ll_hdr_len;
24140 	int		hdr_len;
24141 	mblk_t		*hdr_mp;
24142 	ipha_t		*ipha;
24143 	int		ip_data_end;
24144 	int		len;
24145 	mblk_t		*mp = mp_orig, *mp1;
24146 	int		offset;
24147 	queue_t		*q;
24148 	uint32_t	v_hlen_tos_len;
24149 	mblk_t		*first_mp;
24150 	boolean_t	mctl_present;
24151 	ill_t		*ill;
24152 	ill_t		*out_ill;
24153 	mblk_t		*xmit_mp;
24154 	mblk_t		*carve_mp;
24155 	ire_t		*ire1 = NULL;
24156 	ire_t		*save_ire = NULL;
24157 	mblk_t  	*next_mp = NULL;
24158 	boolean_t	last_frag = B_FALSE;
24159 	boolean_t	multirt_send = B_FALSE;
24160 	ire_t		*first_ire = NULL;
24161 	irb_t		*irb = NULL;
24162 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24163 
24164 	ill = ire_to_ill(ire);
24165 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24166 
24167 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24168 
24169 	if (max_frag == 0) {
24170 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24171 		    " -  dropping packet\n"));
24172 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24173 		freemsg(mp);
24174 		return;
24175 	}
24176 
24177 	/*
24178 	 * IPsec does not allow hw accelerated packets to be fragmented
24179 	 * This check is made in ip_wput_ipsec_out prior to coming here
24180 	 * via ip_wput_ire_fragmentit.
24181 	 *
24182 	 * If at this point we have an ire whose ARP request has not
24183 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24184 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24185 	 * This packet and all fragmentable packets for this ire will
24186 	 * continue to get dropped while ire_nce->nce_state remains in
24187 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24188 	 * ND_REACHABLE, all subsquent large packets for this ire will
24189 	 * get fragemented and sent out by this function.
24190 	 */
24191 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24192 		/* If nce_state is ND_INITIAL, trigger ARP query */
24193 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24194 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24195 		    " -  dropping packet\n"));
24196 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24197 		freemsg(mp);
24198 		return;
24199 	}
24200 
24201 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24202 	    "ip_wput_frag_start:");
24203 
24204 	if (mp->b_datap->db_type == M_CTL) {
24205 		first_mp = mp;
24206 		mp_orig = mp = mp->b_cont;
24207 		mctl_present = B_TRUE;
24208 	} else {
24209 		first_mp = mp;
24210 		mctl_present = B_FALSE;
24211 	}
24212 
24213 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24214 	ipha = (ipha_t *)mp->b_rptr;
24215 
24216 	/*
24217 	 * If the Don't Fragment flag is on, generate an ICMP destination
24218 	 * unreachable, fragmentation needed.
24219 	 */
24220 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24221 	if (offset & IPH_DF) {
24222 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24223 		if (is_system_labeled()) {
24224 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24225 			    ire->ire_max_frag - max_frag, AF_INET);
24226 		}
24227 		/*
24228 		 * Need to compute hdr checksum if called from ip_wput_ire.
24229 		 * Note that ip_rput_forward verifies the checksum before
24230 		 * calling this routine so in that case this is a noop.
24231 		 */
24232 		ipha->ipha_hdr_checksum = 0;
24233 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24234 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24235 		    ipst);
24236 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24237 		    "ip_wput_frag_end:(%S)",
24238 		    "don't fragment");
24239 		return;
24240 	}
24241 	/*
24242 	 * Labeled systems adjust max_frag if they add a label
24243 	 * to send the correct path mtu.  We need the real mtu since we
24244 	 * are fragmenting the packet after label adjustment.
24245 	 */
24246 	if (is_system_labeled())
24247 		max_frag = ire->ire_max_frag;
24248 	if (mctl_present)
24249 		freeb(first_mp);
24250 	/*
24251 	 * Establish the starting offset.  May not be zero if we are fragging
24252 	 * a fragment that is being forwarded.
24253 	 */
24254 	offset = offset & IPH_OFFSET;
24255 
24256 	/* TODO why is this test needed? */
24257 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24258 	if (((max_frag - LENGTH) & ~7) < 8) {
24259 		/* TODO: notify ulp somehow */
24260 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24261 		freemsg(mp);
24262 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24263 		    "ip_wput_frag_end:(%S)",
24264 		    "len < 8");
24265 		return;
24266 	}
24267 
24268 	hdr_len = (V_HLEN & 0xF) << 2;
24269 
24270 	ipha->ipha_hdr_checksum = 0;
24271 
24272 	/*
24273 	 * Establish the number of bytes maximum per frag, after putting
24274 	 * in the header.
24275 	 */
24276 	len = (max_frag - hdr_len) & ~7;
24277 
24278 	/* Check if we can use MDT to send out the frags. */
24279 	ASSERT(!IRE_IS_LOCAL(ire));
24280 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24281 	    ipst->ips_ip_multidata_outbound &&
24282 	    !(ire->ire_flags & RTF_MULTIRT) &&
24283 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24284 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24285 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24286 		ASSERT(ill->ill_mdt_capab != NULL);
24287 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24288 			/*
24289 			 * If MDT has been previously turned off in the past,
24290 			 * and we currently can do MDT (due to IPQoS policy
24291 			 * removal, etc.) then enable it for this interface.
24292 			 */
24293 			ill->ill_mdt_capab->ill_mdt_on = 1;
24294 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24295 			    ill->ill_name));
24296 		}
24297 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24298 		    offset);
24299 		return;
24300 	}
24301 
24302 	/* Get a copy of the header for the trailing frags */
24303 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24304 	    mp);
24305 	if (!hdr_mp) {
24306 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24307 		freemsg(mp);
24308 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24309 		    "ip_wput_frag_end:(%S)",
24310 		    "couldn't copy hdr");
24311 		return;
24312 	}
24313 
24314 	/* Store the starting offset, with the MoreFrags flag. */
24315 	i1 = offset | IPH_MF | frag_flag;
24316 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24317 
24318 	/* Establish the ending byte offset, based on the starting offset. */
24319 	offset <<= 3;
24320 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24321 
24322 	/* Store the length of the first fragment in the IP header. */
24323 	i1 = len + hdr_len;
24324 	ASSERT(i1 <= IP_MAXPACKET);
24325 	ipha->ipha_length = htons((uint16_t)i1);
24326 
24327 	/*
24328 	 * Compute the IP header checksum for the first frag.  We have to
24329 	 * watch out that we stop at the end of the header.
24330 	 */
24331 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24332 
24333 	/*
24334 	 * Now carve off the first frag.  Note that this will include the
24335 	 * original IP header.
24336 	 */
24337 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24338 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24339 		freeb(hdr_mp);
24340 		freemsg(mp_orig);
24341 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24342 		    "ip_wput_frag_end:(%S)",
24343 		    "couldn't carve first");
24344 		return;
24345 	}
24346 
24347 	/*
24348 	 * Multirouting case. Each fragment is replicated
24349 	 * via all non-condemned RTF_MULTIRT routes
24350 	 * currently resolved.
24351 	 * We ensure that first_ire is the first RTF_MULTIRT
24352 	 * ire in the bucket.
24353 	 */
24354 	if (ire->ire_flags & RTF_MULTIRT) {
24355 		irb = ire->ire_bucket;
24356 		ASSERT(irb != NULL);
24357 
24358 		multirt_send = B_TRUE;
24359 
24360 		/* Make sure we do not omit any multiroute ire. */
24361 		IRB_REFHOLD(irb);
24362 		for (first_ire = irb->irb_ire;
24363 		    first_ire != NULL;
24364 		    first_ire = first_ire->ire_next) {
24365 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24366 			    (first_ire->ire_addr == ire->ire_addr) &&
24367 			    !(first_ire->ire_marks &
24368 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24369 				break;
24370 		}
24371 
24372 		if (first_ire != NULL) {
24373 			if (first_ire != ire) {
24374 				IRE_REFHOLD(first_ire);
24375 				/*
24376 				 * Do not release the ire passed in
24377 				 * as the argument.
24378 				 */
24379 				ire = first_ire;
24380 			} else {
24381 				first_ire = NULL;
24382 			}
24383 		}
24384 		IRB_REFRELE(irb);
24385 
24386 		/*
24387 		 * Save the first ire; we will need to restore it
24388 		 * for the trailing frags.
24389 		 * We REFHOLD save_ire, as each iterated ire will be
24390 		 * REFRELEd.
24391 		 */
24392 		save_ire = ire;
24393 		IRE_REFHOLD(save_ire);
24394 	}
24395 
24396 	/*
24397 	 * First fragment emission loop.
24398 	 * In most cases, the emission loop below is entered only
24399 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24400 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24401 	 * bucket, and send the fragment through all crossed
24402 	 * RTF_MULTIRT routes.
24403 	 */
24404 	do {
24405 		if (ire->ire_flags & RTF_MULTIRT) {
24406 			/*
24407 			 * We are in a multiple send case, need to get
24408 			 * the next ire and make a copy of the packet.
24409 			 * ire1 holds here the next ire to process in the
24410 			 * bucket. If multirouting is expected,
24411 			 * any non-RTF_MULTIRT ire that has the
24412 			 * right destination address is ignored.
24413 			 *
24414 			 * We have to take into account the MTU of
24415 			 * each walked ire. max_frag is set by the
24416 			 * the caller and generally refers to
24417 			 * the primary ire entry. Here we ensure that
24418 			 * no route with a lower MTU will be used, as
24419 			 * fragments are carved once for all ires,
24420 			 * then replicated.
24421 			 */
24422 			ASSERT(irb != NULL);
24423 			IRB_REFHOLD(irb);
24424 			for (ire1 = ire->ire_next;
24425 			    ire1 != NULL;
24426 			    ire1 = ire1->ire_next) {
24427 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24428 					continue;
24429 				if (ire1->ire_addr != ire->ire_addr)
24430 					continue;
24431 				if (ire1->ire_marks &
24432 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24433 					continue;
24434 				/*
24435 				 * Ensure we do not exceed the MTU
24436 				 * of the next route.
24437 				 */
24438 				if (ire1->ire_max_frag < max_frag) {
24439 					ip_multirt_bad_mtu(ire1, max_frag);
24440 					continue;
24441 				}
24442 
24443 				/* Got one. */
24444 				IRE_REFHOLD(ire1);
24445 				break;
24446 			}
24447 			IRB_REFRELE(irb);
24448 
24449 			if (ire1 != NULL) {
24450 				next_mp = copyb(mp);
24451 				if ((next_mp == NULL) ||
24452 				    ((mp->b_cont != NULL) &&
24453 				    ((next_mp->b_cont =
24454 				    dupmsg(mp->b_cont)) == NULL))) {
24455 					freemsg(next_mp);
24456 					next_mp = NULL;
24457 					ire_refrele(ire1);
24458 					ire1 = NULL;
24459 				}
24460 			}
24461 
24462 			/* Last multiroute ire; don't loop anymore. */
24463 			if (ire1 == NULL) {
24464 				multirt_send = B_FALSE;
24465 			}
24466 		}
24467 
24468 		ll_hdr_len = 0;
24469 		LOCK_IRE_FP_MP(ire);
24470 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24471 		if (ll_hdr_mp != NULL) {
24472 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24473 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24474 		} else {
24475 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24476 		}
24477 
24478 		/* If there is a transmit header, get a copy for this frag. */
24479 		/*
24480 		 * TODO: should check db_ref before calling ip_carve_mp since
24481 		 * it might give us a dup.
24482 		 */
24483 		if (!ll_hdr_mp) {
24484 			/* No xmit header. */
24485 			xmit_mp = mp;
24486 
24487 		/* We have a link-layer header that can fit in our mblk. */
24488 		} else if (mp->b_datap->db_ref == 1 &&
24489 		    ll_hdr_len != 0 &&
24490 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24491 			/* M_DATA fastpath */
24492 			mp->b_rptr -= ll_hdr_len;
24493 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24494 			xmit_mp = mp;
24495 
24496 		/* Corner case if copyb has failed */
24497 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24498 			UNLOCK_IRE_FP_MP(ire);
24499 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24500 			freeb(hdr_mp);
24501 			freemsg(mp);
24502 			freemsg(mp_orig);
24503 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24504 			    "ip_wput_frag_end:(%S)",
24505 			    "discard");
24506 
24507 			if (multirt_send) {
24508 				ASSERT(ire1);
24509 				ASSERT(next_mp);
24510 
24511 				freemsg(next_mp);
24512 				ire_refrele(ire1);
24513 			}
24514 			if (save_ire != NULL)
24515 				IRE_REFRELE(save_ire);
24516 
24517 			if (first_ire != NULL)
24518 				ire_refrele(first_ire);
24519 			return;
24520 
24521 		/*
24522 		 * Case of res_mp OR the fastpath mp can't fit
24523 		 * in the mblk
24524 		 */
24525 		} else {
24526 			xmit_mp->b_cont = mp;
24527 
24528 			/*
24529 			 * Get priority marking, if any.
24530 			 * We propagate the CoS marking from the
24531 			 * original packet that went to QoS processing
24532 			 * in ip_wput_ire to the newly carved mp.
24533 			 */
24534 			if (DB_TYPE(xmit_mp) == M_DATA)
24535 				xmit_mp->b_band = mp->b_band;
24536 		}
24537 		UNLOCK_IRE_FP_MP(ire);
24538 
24539 		q = ire->ire_stq;
24540 		out_ill = (ill_t *)q->q_ptr;
24541 
24542 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24543 
24544 		DTRACE_PROBE4(ip4__physical__out__start,
24545 		    ill_t *, NULL, ill_t *, out_ill,
24546 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24547 
24548 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24549 		    ipst->ips_ipv4firewall_physical_out,
24550 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24551 
24552 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24553 
24554 		if (xmit_mp != NULL) {
24555 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24556 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24557 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24558 
24559 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24560 
24561 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24562 			UPDATE_MIB(out_ill->ill_ip_mib,
24563 			    ipIfStatsHCOutOctets, i1);
24564 
24565 			if (pkt_type != OB_PKT) {
24566 				/*
24567 				 * Update the packet count and MIB stats
24568 				 * of trailing RTF_MULTIRT ires.
24569 				 */
24570 				UPDATE_OB_PKT_COUNT(ire);
24571 				BUMP_MIB(out_ill->ill_ip_mib,
24572 				    ipIfStatsOutFragReqds);
24573 			}
24574 		}
24575 
24576 		if (multirt_send) {
24577 			/*
24578 			 * We are in a multiple send case; look for
24579 			 * the next ire and re-enter the loop.
24580 			 */
24581 			ASSERT(ire1);
24582 			ASSERT(next_mp);
24583 			/* REFRELE the current ire before looping */
24584 			ire_refrele(ire);
24585 			ire = ire1;
24586 			ire1 = NULL;
24587 			mp = next_mp;
24588 			next_mp = NULL;
24589 		}
24590 	} while (multirt_send);
24591 
24592 	ASSERT(ire1 == NULL);
24593 
24594 	/* Restore the original ire; we need it for the trailing frags */
24595 	if (save_ire != NULL) {
24596 		/* REFRELE the last iterated ire */
24597 		ire_refrele(ire);
24598 		/* save_ire has been REFHOLDed */
24599 		ire = save_ire;
24600 		save_ire = NULL;
24601 		q = ire->ire_stq;
24602 	}
24603 
24604 	if (pkt_type == OB_PKT) {
24605 		UPDATE_OB_PKT_COUNT(ire);
24606 	} else {
24607 		out_ill = (ill_t *)q->q_ptr;
24608 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24609 		UPDATE_IB_PKT_COUNT(ire);
24610 	}
24611 
24612 	/* Advance the offset to the second frag starting point. */
24613 	offset += len;
24614 	/*
24615 	 * Update hdr_len from the copied header - there might be less options
24616 	 * in the later fragments.
24617 	 */
24618 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24619 	/* Loop until done. */
24620 	for (;;) {
24621 		uint16_t	offset_and_flags;
24622 		uint16_t	ip_len;
24623 
24624 		if (ip_data_end - offset > len) {
24625 			/*
24626 			 * Carve off the appropriate amount from the original
24627 			 * datagram.
24628 			 */
24629 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24630 				mp = NULL;
24631 				break;
24632 			}
24633 			/*
24634 			 * More frags after this one.  Get another copy
24635 			 * of the header.
24636 			 */
24637 			if (carve_mp->b_datap->db_ref == 1 &&
24638 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24639 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24640 				/* Inline IP header */
24641 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24642 				    hdr_mp->b_rptr;
24643 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24644 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24645 				mp = carve_mp;
24646 			} else {
24647 				if (!(mp = copyb(hdr_mp))) {
24648 					freemsg(carve_mp);
24649 					break;
24650 				}
24651 				/* Get priority marking, if any. */
24652 				mp->b_band = carve_mp->b_band;
24653 				mp->b_cont = carve_mp;
24654 			}
24655 			ipha = (ipha_t *)mp->b_rptr;
24656 			offset_and_flags = IPH_MF;
24657 		} else {
24658 			/*
24659 			 * Last frag.  Consume the header. Set len to
24660 			 * the length of this last piece.
24661 			 */
24662 			len = ip_data_end - offset;
24663 
24664 			/*
24665 			 * Carve off the appropriate amount from the original
24666 			 * datagram.
24667 			 */
24668 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24669 				mp = NULL;
24670 				break;
24671 			}
24672 			if (carve_mp->b_datap->db_ref == 1 &&
24673 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24674 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24675 				/* Inline IP header */
24676 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24677 				    hdr_mp->b_rptr;
24678 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24679 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24680 				mp = carve_mp;
24681 				freeb(hdr_mp);
24682 				hdr_mp = mp;
24683 			} else {
24684 				mp = hdr_mp;
24685 				/* Get priority marking, if any. */
24686 				mp->b_band = carve_mp->b_band;
24687 				mp->b_cont = carve_mp;
24688 			}
24689 			ipha = (ipha_t *)mp->b_rptr;
24690 			/* A frag of a frag might have IPH_MF non-zero */
24691 			offset_and_flags =
24692 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24693 			    IPH_MF;
24694 		}
24695 		offset_and_flags |= (uint16_t)(offset >> 3);
24696 		offset_and_flags |= (uint16_t)frag_flag;
24697 		/* Store the offset and flags in the IP header. */
24698 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24699 
24700 		/* Store the length in the IP header. */
24701 		ip_len = (uint16_t)(len + hdr_len);
24702 		ipha->ipha_length = htons(ip_len);
24703 
24704 		/*
24705 		 * Set the IP header checksum.	Note that mp is just
24706 		 * the header, so this is easy to pass to ip_csum.
24707 		 */
24708 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24709 
24710 		/* Attach a transmit header, if any, and ship it. */
24711 		if (pkt_type == OB_PKT) {
24712 			UPDATE_OB_PKT_COUNT(ire);
24713 		} else {
24714 			out_ill = (ill_t *)q->q_ptr;
24715 			BUMP_MIB(out_ill->ill_ip_mib,
24716 			    ipIfStatsHCOutForwDatagrams);
24717 			UPDATE_IB_PKT_COUNT(ire);
24718 		}
24719 
24720 		if (ire->ire_flags & RTF_MULTIRT) {
24721 			irb = ire->ire_bucket;
24722 			ASSERT(irb != NULL);
24723 
24724 			multirt_send = B_TRUE;
24725 
24726 			/*
24727 			 * Save the original ire; we will need to restore it
24728 			 * for the tailing frags.
24729 			 */
24730 			save_ire = ire;
24731 			IRE_REFHOLD(save_ire);
24732 		}
24733 		/*
24734 		 * Emission loop for this fragment, similar
24735 		 * to what is done for the first fragment.
24736 		 */
24737 		do {
24738 			if (multirt_send) {
24739 				/*
24740 				 * We are in a multiple send case, need to get
24741 				 * the next ire and make a copy of the packet.
24742 				 */
24743 				ASSERT(irb != NULL);
24744 				IRB_REFHOLD(irb);
24745 				for (ire1 = ire->ire_next;
24746 				    ire1 != NULL;
24747 				    ire1 = ire1->ire_next) {
24748 					if (!(ire1->ire_flags & RTF_MULTIRT))
24749 						continue;
24750 					if (ire1->ire_addr != ire->ire_addr)
24751 						continue;
24752 					if (ire1->ire_marks &
24753 					    (IRE_MARK_CONDEMNED |
24754 					    IRE_MARK_TESTHIDDEN))
24755 						continue;
24756 					/*
24757 					 * Ensure we do not exceed the MTU
24758 					 * of the next route.
24759 					 */
24760 					if (ire1->ire_max_frag < max_frag) {
24761 						ip_multirt_bad_mtu(ire1,
24762 						    max_frag);
24763 						continue;
24764 					}
24765 
24766 					/* Got one. */
24767 					IRE_REFHOLD(ire1);
24768 					break;
24769 				}
24770 				IRB_REFRELE(irb);
24771 
24772 				if (ire1 != NULL) {
24773 					next_mp = copyb(mp);
24774 					if ((next_mp == NULL) ||
24775 					    ((mp->b_cont != NULL) &&
24776 					    ((next_mp->b_cont =
24777 					    dupmsg(mp->b_cont)) == NULL))) {
24778 						freemsg(next_mp);
24779 						next_mp = NULL;
24780 						ire_refrele(ire1);
24781 						ire1 = NULL;
24782 					}
24783 				}
24784 
24785 				/* Last multiroute ire; don't loop anymore. */
24786 				if (ire1 == NULL) {
24787 					multirt_send = B_FALSE;
24788 				}
24789 			}
24790 
24791 			/* Update transmit header */
24792 			ll_hdr_len = 0;
24793 			LOCK_IRE_FP_MP(ire);
24794 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24795 			if (ll_hdr_mp != NULL) {
24796 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24797 				ll_hdr_len = MBLKL(ll_hdr_mp);
24798 			} else {
24799 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24800 			}
24801 
24802 			if (!ll_hdr_mp) {
24803 				xmit_mp = mp;
24804 
24805 			/*
24806 			 * We have link-layer header that can fit in
24807 			 * our mblk.
24808 			 */
24809 			} else if (mp->b_datap->db_ref == 1 &&
24810 			    ll_hdr_len != 0 &&
24811 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24812 				/* M_DATA fastpath */
24813 				mp->b_rptr -= ll_hdr_len;
24814 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24815 				    ll_hdr_len);
24816 				xmit_mp = mp;
24817 
24818 			/*
24819 			 * Case of res_mp OR the fastpath mp can't fit
24820 			 * in the mblk
24821 			 */
24822 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24823 				xmit_mp->b_cont = mp;
24824 				/* Get priority marking, if any. */
24825 				if (DB_TYPE(xmit_mp) == M_DATA)
24826 					xmit_mp->b_band = mp->b_band;
24827 
24828 			/* Corner case if copyb failed */
24829 			} else {
24830 				/*
24831 				 * Exit both the replication and
24832 				 * fragmentation loops.
24833 				 */
24834 				UNLOCK_IRE_FP_MP(ire);
24835 				goto drop_pkt;
24836 			}
24837 			UNLOCK_IRE_FP_MP(ire);
24838 
24839 			mp1 = mp;
24840 			out_ill = (ill_t *)q->q_ptr;
24841 
24842 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24843 
24844 			DTRACE_PROBE4(ip4__physical__out__start,
24845 			    ill_t *, NULL, ill_t *, out_ill,
24846 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24847 
24848 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24849 			    ipst->ips_ipv4firewall_physical_out,
24850 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24851 
24852 			DTRACE_PROBE1(ip4__physical__out__end,
24853 			    mblk_t *, xmit_mp);
24854 
24855 			if (mp != mp1 && hdr_mp == mp1)
24856 				hdr_mp = mp;
24857 			if (mp != mp1 && mp_orig == mp1)
24858 				mp_orig = mp;
24859 
24860 			if (xmit_mp != NULL) {
24861 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24862 				    NULL, void_ip_t *, ipha,
24863 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24864 				    ipha, ip6_t *, NULL, int, 0);
24865 
24866 				ILL_SEND_TX(out_ill, ire, connp,
24867 				    xmit_mp, 0, connp);
24868 
24869 				BUMP_MIB(out_ill->ill_ip_mib,
24870 				    ipIfStatsHCOutTransmits);
24871 				UPDATE_MIB(out_ill->ill_ip_mib,
24872 				    ipIfStatsHCOutOctets, ip_len);
24873 
24874 				if (pkt_type != OB_PKT) {
24875 					/*
24876 					 * Update the packet count of trailing
24877 					 * RTF_MULTIRT ires.
24878 					 */
24879 					UPDATE_OB_PKT_COUNT(ire);
24880 				}
24881 			}
24882 
24883 			/* All done if we just consumed the hdr_mp. */
24884 			if (mp == hdr_mp) {
24885 				last_frag = B_TRUE;
24886 				BUMP_MIB(out_ill->ill_ip_mib,
24887 				    ipIfStatsOutFragOKs);
24888 			}
24889 
24890 			if (multirt_send) {
24891 				/*
24892 				 * We are in a multiple send case; look for
24893 				 * the next ire and re-enter the loop.
24894 				 */
24895 				ASSERT(ire1);
24896 				ASSERT(next_mp);
24897 				/* REFRELE the current ire before looping */
24898 				ire_refrele(ire);
24899 				ire = ire1;
24900 				ire1 = NULL;
24901 				q = ire->ire_stq;
24902 				mp = next_mp;
24903 				next_mp = NULL;
24904 			}
24905 		} while (multirt_send);
24906 		/*
24907 		 * Restore the original ire; we need it for the
24908 		 * trailing frags
24909 		 */
24910 		if (save_ire != NULL) {
24911 			ASSERT(ire1 == NULL);
24912 			/* REFRELE the last iterated ire */
24913 			ire_refrele(ire);
24914 			/* save_ire has been REFHOLDed */
24915 			ire = save_ire;
24916 			q = ire->ire_stq;
24917 			save_ire = NULL;
24918 		}
24919 
24920 		if (last_frag) {
24921 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24922 			    "ip_wput_frag_end:(%S)",
24923 			    "consumed hdr_mp");
24924 
24925 			if (first_ire != NULL)
24926 				ire_refrele(first_ire);
24927 			return;
24928 		}
24929 		/* Otherwise, advance and loop. */
24930 		offset += len;
24931 	}
24932 
24933 drop_pkt:
24934 	/* Clean up following allocation failure. */
24935 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24936 	freemsg(mp);
24937 	if (mp != hdr_mp)
24938 		freeb(hdr_mp);
24939 	if (mp != mp_orig)
24940 		freemsg(mp_orig);
24941 
24942 	if (save_ire != NULL)
24943 		IRE_REFRELE(save_ire);
24944 	if (first_ire != NULL)
24945 		ire_refrele(first_ire);
24946 
24947 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24948 	    "ip_wput_frag_end:(%S)",
24949 	    "end--alloc failure");
24950 }
24951 
24952 /*
24953  * Copy the header plus those options which have the copy bit set
24954  * src is the template to make sure we preserve the cred for TX purposes.
24955  */
24956 static mblk_t *
24957 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24958     mblk_t *src)
24959 {
24960 	mblk_t	*mp;
24961 	uchar_t	*up;
24962 
24963 	/*
24964 	 * Quick check if we need to look for options without the copy bit
24965 	 * set
24966 	 */
24967 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24968 	if (!mp)
24969 		return (mp);
24970 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24971 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24972 		bcopy(rptr, mp->b_rptr, hdr_len);
24973 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24974 		return (mp);
24975 	}
24976 	up  = mp->b_rptr;
24977 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24978 	up += IP_SIMPLE_HDR_LENGTH;
24979 	rptr += IP_SIMPLE_HDR_LENGTH;
24980 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24981 	while (hdr_len > 0) {
24982 		uint32_t optval;
24983 		uint32_t optlen;
24984 
24985 		optval = *rptr;
24986 		if (optval == IPOPT_EOL)
24987 			break;
24988 		if (optval == IPOPT_NOP)
24989 			optlen = 1;
24990 		else
24991 			optlen = rptr[1];
24992 		if (optval & IPOPT_COPY) {
24993 			bcopy(rptr, up, optlen);
24994 			up += optlen;
24995 		}
24996 		rptr += optlen;
24997 		hdr_len -= optlen;
24998 	}
24999 	/*
25000 	 * Make sure that we drop an even number of words by filling
25001 	 * with EOL to the next word boundary.
25002 	 */
25003 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25004 	    hdr_len & 0x3; hdr_len++)
25005 		*up++ = IPOPT_EOL;
25006 	mp->b_wptr = up;
25007 	/* Update header length */
25008 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25009 	return (mp);
25010 }
25011 
25012 /*
25013  * Delivery to local recipients including fanout to multiple recipients.
25014  * Does not do checksumming of UDP/TCP.
25015  * Note: q should be the read side queue for either the ill or conn.
25016  * Note: rq should be the read side q for the lower (ill) stream.
25017  * We don't send packets to IPPF processing, thus the last argument
25018  * to all the fanout calls are B_FALSE.
25019  */
25020 void
25021 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25022     int fanout_flags, zoneid_t zoneid)
25023 {
25024 	uint32_t	protocol;
25025 	mblk_t		*first_mp;
25026 	boolean_t	mctl_present;
25027 	int		ire_type;
25028 #define	rptr	((uchar_t *)ipha)
25029 	ip_stack_t	*ipst = ill->ill_ipst;
25030 
25031 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25032 	    "ip_wput_local_start: q %p", q);
25033 
25034 	if (ire != NULL) {
25035 		ire_type = ire->ire_type;
25036 	} else {
25037 		/*
25038 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25039 		 * packet is not multicast, we can't tell the ire type.
25040 		 */
25041 		ASSERT(CLASSD(ipha->ipha_dst));
25042 		ire_type = IRE_BROADCAST;
25043 	}
25044 
25045 	first_mp = mp;
25046 	if (first_mp->b_datap->db_type == M_CTL) {
25047 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25048 		if (!io->ipsec_out_secure) {
25049 			/*
25050 			 * This ipsec_out_t was allocated in ip_wput
25051 			 * for multicast packets to store the ill_index.
25052 			 * As this is being delivered locally, we don't
25053 			 * need this anymore.
25054 			 */
25055 			mp = first_mp->b_cont;
25056 			freeb(first_mp);
25057 			first_mp = mp;
25058 			mctl_present = B_FALSE;
25059 		} else {
25060 			/*
25061 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25062 			 * security properties for the looped-back packet.
25063 			 */
25064 			mctl_present = B_TRUE;
25065 			mp = first_mp->b_cont;
25066 			ASSERT(mp != NULL);
25067 			ipsec_out_to_in(first_mp);
25068 		}
25069 	} else {
25070 		mctl_present = B_FALSE;
25071 	}
25072 
25073 	DTRACE_PROBE4(ip4__loopback__in__start,
25074 	    ill_t *, ill, ill_t *, NULL,
25075 	    ipha_t *, ipha, mblk_t *, first_mp);
25076 
25077 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25078 	    ipst->ips_ipv4firewall_loopback_in,
25079 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25080 
25081 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25082 
25083 	if (first_mp == NULL)
25084 		return;
25085 
25086 	if (ipst->ips_ipobs_enabled) {
25087 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25088 		zoneid_t stackzoneid = netstackid_to_zoneid(
25089 		    ipst->ips_netstack->netstack_stackid);
25090 
25091 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25092 		/*
25093 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25094 		 * address.  Restrict the lookup below to the destination zone.
25095 		 */
25096 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25097 			lookup_zoneid = zoneid;
25098 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25099 		    lookup_zoneid);
25100 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25101 		    IPV4_VERSION, 0, ipst);
25102 	}
25103 
25104 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25105 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25106 	    int, 1);
25107 
25108 	ipst->ips_loopback_packets++;
25109 
25110 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25111 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25112 	if (!IS_SIMPLE_IPH(ipha)) {
25113 		ip_wput_local_options(ipha, ipst);
25114 	}
25115 
25116 	protocol = ipha->ipha_protocol;
25117 	switch (protocol) {
25118 	case IPPROTO_ICMP: {
25119 		ire_t		*ire_zone;
25120 		ilm_t		*ilm;
25121 		mblk_t		*mp1;
25122 		zoneid_t	last_zoneid;
25123 		ilm_walker_t	ilw;
25124 
25125 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25126 			ASSERT(ire_type == IRE_BROADCAST);
25127 			/*
25128 			 * In the multicast case, applications may have joined
25129 			 * the group from different zones, so we need to deliver
25130 			 * the packet to each of them. Loop through the
25131 			 * multicast memberships structures (ilm) on the receive
25132 			 * ill and send a copy of the packet up each matching
25133 			 * one. However, we don't do this for multicasts sent on
25134 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25135 			 * they must stay in the sender's zone.
25136 			 *
25137 			 * ilm_add_v6() ensures that ilms in the same zone are
25138 			 * contiguous in the ill_ilm list. We use this property
25139 			 * to avoid sending duplicates needed when two
25140 			 * applications in the same zone join the same group on
25141 			 * different logical interfaces: we ignore the ilm if
25142 			 * it's zoneid is the same as the last matching one.
25143 			 * In addition, the sending of the packet for
25144 			 * ire_zoneid is delayed until all of the other ilms
25145 			 * have been exhausted.
25146 			 */
25147 			last_zoneid = -1;
25148 			ilm = ilm_walker_start(&ilw, ill);
25149 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25150 				if (ipha->ipha_dst != ilm->ilm_addr ||
25151 				    ilm->ilm_zoneid == last_zoneid ||
25152 				    ilm->ilm_zoneid == zoneid ||
25153 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25154 					continue;
25155 				mp1 = ip_copymsg(first_mp);
25156 				if (mp1 == NULL)
25157 					continue;
25158 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25159 				    0, 0, mctl_present, B_FALSE, ill,
25160 				    ilm->ilm_zoneid);
25161 				last_zoneid = ilm->ilm_zoneid;
25162 			}
25163 			ilm_walker_finish(&ilw);
25164 			/*
25165 			 * Loopback case: the sending endpoint has
25166 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25167 			 * dispatch the multicast packet to the sending zone.
25168 			 */
25169 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25170 				freemsg(first_mp);
25171 				return;
25172 			}
25173 		} else if (ire_type == IRE_BROADCAST) {
25174 			/*
25175 			 * In the broadcast case, there may be many zones
25176 			 * which need a copy of the packet delivered to them.
25177 			 * There is one IRE_BROADCAST per broadcast address
25178 			 * and per zone; we walk those using a helper function.
25179 			 * In addition, the sending of the packet for zoneid is
25180 			 * delayed until all of the other ires have been
25181 			 * processed.
25182 			 */
25183 			IRB_REFHOLD(ire->ire_bucket);
25184 			ire_zone = NULL;
25185 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25186 			    ire)) != NULL) {
25187 				mp1 = ip_copymsg(first_mp);
25188 				if (mp1 == NULL)
25189 					continue;
25190 
25191 				UPDATE_IB_PKT_COUNT(ire_zone);
25192 				ire_zone->ire_last_used_time = lbolt;
25193 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25194 				    mctl_present, B_FALSE, ill,
25195 				    ire_zone->ire_zoneid);
25196 			}
25197 			IRB_REFRELE(ire->ire_bucket);
25198 		}
25199 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25200 		    0, mctl_present, B_FALSE, ill, zoneid);
25201 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25202 		    "ip_wput_local_end: q %p (%S)",
25203 		    q, "icmp");
25204 		return;
25205 	}
25206 	case IPPROTO_IGMP:
25207 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25208 			/* Bad packet - discarded by igmp_input */
25209 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25210 			    "ip_wput_local_end: q %p (%S)",
25211 			    q, "igmp_input--bad packet");
25212 			if (mctl_present)
25213 				freeb(first_mp);
25214 			return;
25215 		}
25216 		/*
25217 		 * igmp_input() may have returned the pulled up message.
25218 		 * So first_mp and ipha need to be reinitialized.
25219 		 */
25220 		ipha = (ipha_t *)mp->b_rptr;
25221 		if (mctl_present)
25222 			first_mp->b_cont = mp;
25223 		else
25224 			first_mp = mp;
25225 		/* deliver to local raw users */
25226 		break;
25227 	case IPPROTO_ENCAP:
25228 		/*
25229 		 * This case is covered by either ip_fanout_proto, or by
25230 		 * the above security processing for self-tunneled packets.
25231 		 */
25232 		break;
25233 	case IPPROTO_UDP: {
25234 		uint16_t	*up;
25235 		uint32_t	ports;
25236 
25237 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25238 		    UDP_PORTS_OFFSET);
25239 		/* Force a 'valid' checksum. */
25240 		up[3] = 0;
25241 
25242 		ports = *(uint32_t *)up;
25243 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25244 		    (ire_type == IRE_BROADCAST),
25245 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25246 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25247 		    ill, zoneid);
25248 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25249 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25250 		return;
25251 	}
25252 	case IPPROTO_TCP: {
25253 
25254 		/*
25255 		 * For TCP, discard broadcast packets.
25256 		 */
25257 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25258 			freemsg(first_mp);
25259 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25260 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25261 			return;
25262 		}
25263 
25264 		if (mp->b_datap->db_type == M_DATA) {
25265 			/*
25266 			 * M_DATA mblk, so init mblk (chain) for no struio().
25267 			 */
25268 			mblk_t	*mp1 = mp;
25269 
25270 			do {
25271 				mp1->b_datap->db_struioflag = 0;
25272 			} while ((mp1 = mp1->b_cont) != NULL);
25273 		}
25274 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25275 		    <= mp->b_wptr);
25276 		ip_fanout_tcp(q, first_mp, ill, ipha,
25277 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25278 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25279 		    mctl_present, B_FALSE, zoneid);
25280 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25281 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25282 		return;
25283 	}
25284 	case IPPROTO_SCTP:
25285 	{
25286 		uint32_t	ports;
25287 
25288 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25289 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25290 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25291 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25292 		return;
25293 	}
25294 
25295 	default:
25296 		break;
25297 	}
25298 	/*
25299 	 * Find a client for some other protocol.  We give
25300 	 * copies to multiple clients, if more than one is
25301 	 * bound.
25302 	 */
25303 	ip_fanout_proto(q, first_mp, ill, ipha,
25304 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25305 	    mctl_present, B_FALSE, ill, zoneid);
25306 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25307 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25308 #undef	rptr
25309 }
25310 
25311 /*
25312  * Update any source route, record route, or timestamp options.
25313  * Check that we are at end of strict source route.
25314  * The options have been sanity checked by ip_wput_options().
25315  */
25316 static void
25317 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25318 {
25319 	ipoptp_t	opts;
25320 	uchar_t		*opt;
25321 	uint8_t		optval;
25322 	uint8_t		optlen;
25323 	ipaddr_t	dst;
25324 	uint32_t	ts;
25325 	ire_t		*ire;
25326 	timestruc_t	now;
25327 
25328 	ip2dbg(("ip_wput_local_options\n"));
25329 	for (optval = ipoptp_first(&opts, ipha);
25330 	    optval != IPOPT_EOL;
25331 	    optval = ipoptp_next(&opts)) {
25332 		opt = opts.ipoptp_cur;
25333 		optlen = opts.ipoptp_len;
25334 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25335 		switch (optval) {
25336 			uint32_t off;
25337 		case IPOPT_SSRR:
25338 		case IPOPT_LSRR:
25339 			off = opt[IPOPT_OFFSET];
25340 			off--;
25341 			if (optlen < IP_ADDR_LEN ||
25342 			    off > optlen - IP_ADDR_LEN) {
25343 				/* End of source route */
25344 				break;
25345 			}
25346 			/*
25347 			 * This will only happen if two consecutive entries
25348 			 * in the source route contains our address or if
25349 			 * it is a packet with a loose source route which
25350 			 * reaches us before consuming the whole source route
25351 			 */
25352 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25353 			if (optval == IPOPT_SSRR) {
25354 				return;
25355 			}
25356 			/*
25357 			 * Hack: instead of dropping the packet truncate the
25358 			 * source route to what has been used by filling the
25359 			 * rest with IPOPT_NOP.
25360 			 */
25361 			opt[IPOPT_OLEN] = (uint8_t)off;
25362 			while (off < optlen) {
25363 				opt[off++] = IPOPT_NOP;
25364 			}
25365 			break;
25366 		case IPOPT_RR:
25367 			off = opt[IPOPT_OFFSET];
25368 			off--;
25369 			if (optlen < IP_ADDR_LEN ||
25370 			    off > optlen - IP_ADDR_LEN) {
25371 				/* No more room - ignore */
25372 				ip1dbg((
25373 				    "ip_wput_forward_options: end of RR\n"));
25374 				break;
25375 			}
25376 			dst = htonl(INADDR_LOOPBACK);
25377 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25378 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25379 			break;
25380 		case IPOPT_TS:
25381 			/* Insert timestamp if there is romm */
25382 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25383 			case IPOPT_TS_TSONLY:
25384 				off = IPOPT_TS_TIMELEN;
25385 				break;
25386 			case IPOPT_TS_PRESPEC:
25387 			case IPOPT_TS_PRESPEC_RFC791:
25388 				/* Verify that the address matched */
25389 				off = opt[IPOPT_OFFSET] - 1;
25390 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25391 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25392 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25393 				    ipst);
25394 				if (ire == NULL) {
25395 					/* Not for us */
25396 					break;
25397 				}
25398 				ire_refrele(ire);
25399 				/* FALLTHRU */
25400 			case IPOPT_TS_TSANDADDR:
25401 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25402 				break;
25403 			default:
25404 				/*
25405 				 * ip_*put_options should have already
25406 				 * dropped this packet.
25407 				 */
25408 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25409 				    "unknown IT - bug in ip_wput_options?\n");
25410 				return;	/* Keep "lint" happy */
25411 			}
25412 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25413 				/* Increase overflow counter */
25414 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25415 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25416 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25417 				    (off << 4);
25418 				break;
25419 			}
25420 			off = opt[IPOPT_OFFSET] - 1;
25421 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25422 			case IPOPT_TS_PRESPEC:
25423 			case IPOPT_TS_PRESPEC_RFC791:
25424 			case IPOPT_TS_TSANDADDR:
25425 				dst = htonl(INADDR_LOOPBACK);
25426 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25427 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25428 				/* FALLTHRU */
25429 			case IPOPT_TS_TSONLY:
25430 				off = opt[IPOPT_OFFSET] - 1;
25431 				/* Compute # of milliseconds since midnight */
25432 				gethrestime(&now);
25433 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25434 				    now.tv_nsec / (NANOSEC / MILLISEC);
25435 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25436 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25437 				break;
25438 			}
25439 			break;
25440 		}
25441 	}
25442 }
25443 
25444 /*
25445  * Send out a multicast packet on interface ipif.
25446  * The sender does not have an conn.
25447  * Caller verifies that this isn't a PHYI_LOOPBACK.
25448  */
25449 void
25450 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25451 {
25452 	ipha_t	*ipha;
25453 	ire_t	*ire;
25454 	ipaddr_t	dst;
25455 	mblk_t		*first_mp;
25456 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25457 
25458 	/* igmp_sendpkt always allocates a ipsec_out_t */
25459 	ASSERT(mp->b_datap->db_type == M_CTL);
25460 	ASSERT(!ipif->ipif_isv6);
25461 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25462 
25463 	first_mp = mp;
25464 	mp = first_mp->b_cont;
25465 	ASSERT(mp->b_datap->db_type == M_DATA);
25466 	ipha = (ipha_t *)mp->b_rptr;
25467 
25468 	/*
25469 	 * Find an IRE which matches the destination and the outgoing
25470 	 * queue (i.e. the outgoing interface.)
25471 	 */
25472 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25473 		dst = ipif->ipif_pp_dst_addr;
25474 	else
25475 		dst = ipha->ipha_dst;
25476 	/*
25477 	 * The source address has already been initialized by the
25478 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25479 	 * be sufficient rather than MATCH_IRE_IPIF.
25480 	 *
25481 	 * This function is used for sending IGMP packets.  For IPMP,
25482 	 * we sidestep IGMP snooping issues by sending all multicast
25483 	 * traffic on a single interface in the IPMP group.
25484 	 */
25485 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25486 	    MATCH_IRE_ILL, ipst);
25487 	if (!ire) {
25488 		/*
25489 		 * Mark this packet to make it be delivered to
25490 		 * ip_wput_ire after the new ire has been
25491 		 * created.
25492 		 */
25493 		mp->b_prev = NULL;
25494 		mp->b_next = NULL;
25495 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25496 		    zoneid, &zero_info);
25497 		return;
25498 	}
25499 
25500 	/*
25501 	 * Honor the RTF_SETSRC flag; this is the only case
25502 	 * where we force this addr whatever the current src addr is,
25503 	 * because this address is set by igmp_sendpkt(), and
25504 	 * cannot be specified by any user.
25505 	 */
25506 	if (ire->ire_flags & RTF_SETSRC) {
25507 		ipha->ipha_src = ire->ire_src_addr;
25508 	}
25509 
25510 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25511 }
25512 
25513 /*
25514  * NOTE : This function does not ire_refrele the ire argument passed in.
25515  *
25516  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25517  * failure. The nce_fp_mp can vanish any time in the case of
25518  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25519  * the ire_lock to access the nce_fp_mp in this case.
25520  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25521  * prepending a fastpath message IPQoS processing must precede it, we also set
25522  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25523  * (IPQoS might have set the b_band for CoS marking).
25524  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25525  * must follow it so that IPQoS can mark the dl_priority field for CoS
25526  * marking, if needed.
25527  */
25528 static mblk_t *
25529 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25530     uint32_t ill_index, ipha_t **iphap)
25531 {
25532 	uint_t	hlen;
25533 	ipha_t *ipha;
25534 	mblk_t *mp1;
25535 	boolean_t qos_done = B_FALSE;
25536 	uchar_t	*ll_hdr;
25537 	ip_stack_t	*ipst = ire->ire_ipst;
25538 
25539 #define	rptr	((uchar_t *)ipha)
25540 
25541 	ipha = (ipha_t *)mp->b_rptr;
25542 	hlen = 0;
25543 	LOCK_IRE_FP_MP(ire);
25544 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25545 		ASSERT(DB_TYPE(mp1) == M_DATA);
25546 		/* Initiate IPPF processing */
25547 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25548 			UNLOCK_IRE_FP_MP(ire);
25549 			ip_process(proc, &mp, ill_index);
25550 			if (mp == NULL)
25551 				return (NULL);
25552 
25553 			ipha = (ipha_t *)mp->b_rptr;
25554 			LOCK_IRE_FP_MP(ire);
25555 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25556 				qos_done = B_TRUE;
25557 				goto no_fp_mp;
25558 			}
25559 			ASSERT(DB_TYPE(mp1) == M_DATA);
25560 		}
25561 		hlen = MBLKL(mp1);
25562 		/*
25563 		 * Check if we have enough room to prepend fastpath
25564 		 * header
25565 		 */
25566 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25567 			ll_hdr = rptr - hlen;
25568 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25569 			/*
25570 			 * Set the b_rptr to the start of the link layer
25571 			 * header
25572 			 */
25573 			mp->b_rptr = ll_hdr;
25574 			mp1 = mp;
25575 		} else {
25576 			mp1 = copyb(mp1);
25577 			if (mp1 == NULL)
25578 				goto unlock_err;
25579 			mp1->b_band = mp->b_band;
25580 			mp1->b_cont = mp;
25581 			/*
25582 			 * XXX disable ICK_VALID and compute checksum
25583 			 * here; can happen if nce_fp_mp changes and
25584 			 * it can't be copied now due to insufficient
25585 			 * space. (unlikely, fp mp can change, but it
25586 			 * does not increase in length)
25587 			 */
25588 		}
25589 		UNLOCK_IRE_FP_MP(ire);
25590 	} else {
25591 no_fp_mp:
25592 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25593 		if (mp1 == NULL) {
25594 unlock_err:
25595 			UNLOCK_IRE_FP_MP(ire);
25596 			freemsg(mp);
25597 			return (NULL);
25598 		}
25599 		UNLOCK_IRE_FP_MP(ire);
25600 		mp1->b_cont = mp;
25601 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25602 			ip_process(proc, &mp1, ill_index);
25603 			if (mp1 == NULL)
25604 				return (NULL);
25605 
25606 			if (mp1->b_cont == NULL)
25607 				ipha = NULL;
25608 			else
25609 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25610 		}
25611 	}
25612 
25613 	*iphap = ipha;
25614 	return (mp1);
25615 #undef rptr
25616 }
25617 
25618 /*
25619  * Finish the outbound IPsec processing for an IPv6 packet. This function
25620  * is called from ipsec_out_process() if the IPsec packet was processed
25621  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25622  * asynchronously.
25623  */
25624 void
25625 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25626     ire_t *ire_arg)
25627 {
25628 	in6_addr_t *v6dstp;
25629 	ire_t *ire;
25630 	mblk_t *mp;
25631 	ip6_t *ip6h1;
25632 	uint_t	ill_index;
25633 	ipsec_out_t *io;
25634 	boolean_t hwaccel;
25635 	uint32_t flags = IP6_NO_IPPOLICY;
25636 	int match_flags;
25637 	zoneid_t zoneid;
25638 	boolean_t ill_need_rele = B_FALSE;
25639 	boolean_t ire_need_rele = B_FALSE;
25640 	ip_stack_t	*ipst;
25641 
25642 	mp = ipsec_mp->b_cont;
25643 	ip6h1 = (ip6_t *)mp->b_rptr;
25644 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25645 	ASSERT(io->ipsec_out_ns != NULL);
25646 	ipst = io->ipsec_out_ns->netstack_ip;
25647 	ill_index = io->ipsec_out_ill_index;
25648 	if (io->ipsec_out_reachable) {
25649 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25650 	}
25651 	hwaccel = io->ipsec_out_accelerated;
25652 	zoneid = io->ipsec_out_zoneid;
25653 	ASSERT(zoneid != ALL_ZONES);
25654 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25655 	/* Multicast addresses should have non-zero ill_index. */
25656 	v6dstp = &ip6h->ip6_dst;
25657 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25658 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25659 
25660 	if (ill == NULL && ill_index != 0) {
25661 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25662 		/* Failure case frees things for us. */
25663 		if (ill == NULL)
25664 			return;
25665 
25666 		ill_need_rele = B_TRUE;
25667 	}
25668 	ASSERT(mp != NULL);
25669 
25670 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25671 		boolean_t unspec_src;
25672 		ipif_t	*ipif;
25673 
25674 		/*
25675 		 * Use the ill_index to get the right ill.
25676 		 */
25677 		unspec_src = io->ipsec_out_unspec_src;
25678 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25679 		if (ipif == NULL) {
25680 			if (ill_need_rele)
25681 				ill_refrele(ill);
25682 			freemsg(ipsec_mp);
25683 			return;
25684 		}
25685 
25686 		if (ire_arg != NULL) {
25687 			ire = ire_arg;
25688 		} else {
25689 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25690 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25691 			ire_need_rele = B_TRUE;
25692 		}
25693 		if (ire != NULL) {
25694 			ipif_refrele(ipif);
25695 			/*
25696 			 * XXX Do the multicast forwarding now, as the IPsec
25697 			 * processing has been done.
25698 			 */
25699 			goto send;
25700 		}
25701 
25702 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25703 		mp->b_prev = NULL;
25704 		mp->b_next = NULL;
25705 
25706 		/*
25707 		 * If the IPsec packet was processed asynchronously,
25708 		 * drop it now.
25709 		 */
25710 		if (q == NULL) {
25711 			if (ill_need_rele)
25712 				ill_refrele(ill);
25713 			freemsg(ipsec_mp);
25714 			return;
25715 		}
25716 
25717 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25718 		    unspec_src, zoneid);
25719 		ipif_refrele(ipif);
25720 	} else {
25721 		if (ire_arg != NULL) {
25722 			ire = ire_arg;
25723 		} else {
25724 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25725 			ire_need_rele = B_TRUE;
25726 		}
25727 		if (ire != NULL)
25728 			goto send;
25729 		/*
25730 		 * ire disappeared underneath.
25731 		 *
25732 		 * What we need to do here is the ip_newroute
25733 		 * logic to get the ire without doing the IPsec
25734 		 * processing. Follow the same old path. But this
25735 		 * time, ip_wput or ire_add_then_send will call us
25736 		 * directly as all the IPsec operations are done.
25737 		 */
25738 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25739 		mp->b_prev = NULL;
25740 		mp->b_next = NULL;
25741 
25742 		/*
25743 		 * If the IPsec packet was processed asynchronously,
25744 		 * drop it now.
25745 		 */
25746 		if (q == NULL) {
25747 			if (ill_need_rele)
25748 				ill_refrele(ill);
25749 			freemsg(ipsec_mp);
25750 			return;
25751 		}
25752 
25753 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25754 		    zoneid, ipst);
25755 	}
25756 	if (ill != NULL && ill_need_rele)
25757 		ill_refrele(ill);
25758 	return;
25759 send:
25760 	if (ill != NULL && ill_need_rele)
25761 		ill_refrele(ill);
25762 
25763 	/* Local delivery */
25764 	if (ire->ire_stq == NULL) {
25765 		ill_t	*out_ill;
25766 		ASSERT(q != NULL);
25767 
25768 		/* PFHooks: LOOPBACK_OUT */
25769 		out_ill = ire_to_ill(ire);
25770 
25771 		/*
25772 		 * DTrace this as ip:::send.  A blocked packet will fire the
25773 		 * send probe, but not the receive probe.
25774 		 */
25775 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25776 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25777 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25778 
25779 		DTRACE_PROBE4(ip6__loopback__out__start,
25780 		    ill_t *, NULL, ill_t *, out_ill,
25781 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25782 
25783 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25784 		    ipst->ips_ipv6firewall_loopback_out,
25785 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25786 
25787 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25788 
25789 		if (ipsec_mp != NULL) {
25790 			ip_wput_local_v6(RD(q), out_ill,
25791 			    ip6h, ipsec_mp, ire, 0, zoneid);
25792 		}
25793 		if (ire_need_rele)
25794 			ire_refrele(ire);
25795 		return;
25796 	}
25797 	/*
25798 	 * Everything is done. Send it out on the wire.
25799 	 * We force the insertion of a fragment header using the
25800 	 * IPH_FRAG_HDR flag in two cases:
25801 	 * - after reception of an ICMPv6 "packet too big" message
25802 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25803 	 * - for multirouted IPv6 packets, so that the receiver can
25804 	 *   discard duplicates according to their fragment identifier
25805 	 */
25806 	/* XXX fix flow control problems. */
25807 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25808 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25809 		if (hwaccel) {
25810 			/*
25811 			 * hardware acceleration does not handle these
25812 			 * "slow path" cases.
25813 			 */
25814 			/* IPsec KSTATS: should bump bean counter here. */
25815 			if (ire_need_rele)
25816 				ire_refrele(ire);
25817 			freemsg(ipsec_mp);
25818 			return;
25819 		}
25820 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25821 		    (mp->b_cont ? msgdsize(mp) :
25822 		    mp->b_wptr - (uchar_t *)ip6h)) {
25823 			/* IPsec KSTATS: should bump bean counter here. */
25824 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25825 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25826 			    msgdsize(mp)));
25827 			if (ire_need_rele)
25828 				ire_refrele(ire);
25829 			freemsg(ipsec_mp);
25830 			return;
25831 		}
25832 		ASSERT(mp->b_prev == NULL);
25833 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25834 		    ntohs(ip6h->ip6_plen) +
25835 		    IPV6_HDR_LEN, ire->ire_max_frag));
25836 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25837 		    ire->ire_max_frag);
25838 	} else {
25839 		UPDATE_OB_PKT_COUNT(ire);
25840 		ire->ire_last_used_time = lbolt;
25841 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25842 	}
25843 	if (ire_need_rele)
25844 		ire_refrele(ire);
25845 	freeb(ipsec_mp);
25846 }
25847 
25848 void
25849 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25850 {
25851 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25852 	da_ipsec_t *hada;	/* data attributes */
25853 	ill_t *ill = (ill_t *)q->q_ptr;
25854 
25855 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25856 
25857 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25858 		/* IPsec KSTATS: Bump lose counter here! */
25859 		freemsg(mp);
25860 		return;
25861 	}
25862 
25863 	/*
25864 	 * It's an IPsec packet that must be
25865 	 * accelerated by the Provider, and the
25866 	 * outbound ill is IPsec acceleration capable.
25867 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25868 	 * to the ill.
25869 	 * IPsec KSTATS: should bump packet counter here.
25870 	 */
25871 
25872 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25873 	if (hada_mp == NULL) {
25874 		/* IPsec KSTATS: should bump packet counter here. */
25875 		freemsg(mp);
25876 		return;
25877 	}
25878 
25879 	hada_mp->b_datap->db_type = M_CTL;
25880 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25881 	hada_mp->b_cont = mp;
25882 
25883 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25884 	bzero(hada, sizeof (da_ipsec_t));
25885 	hada->da_type = IPHADA_M_CTL;
25886 
25887 	putnext(q, hada_mp);
25888 }
25889 
25890 /*
25891  * Finish the outbound IPsec processing. This function is called from
25892  * ipsec_out_process() if the IPsec packet was processed
25893  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25894  * asynchronously.
25895  */
25896 void
25897 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25898     ire_t *ire_arg)
25899 {
25900 	uint32_t v_hlen_tos_len;
25901 	ipaddr_t	dst;
25902 	ipif_t	*ipif = NULL;
25903 	ire_t *ire;
25904 	ire_t *ire1 = NULL;
25905 	mblk_t *next_mp = NULL;
25906 	uint32_t max_frag;
25907 	boolean_t multirt_send = B_FALSE;
25908 	mblk_t *mp;
25909 	ipha_t *ipha1;
25910 	uint_t	ill_index;
25911 	ipsec_out_t *io;
25912 	int match_flags;
25913 	irb_t *irb = NULL;
25914 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25915 	zoneid_t zoneid;
25916 	ipxmit_state_t	pktxmit_state;
25917 	ip_stack_t	*ipst;
25918 
25919 #ifdef	_BIG_ENDIAN
25920 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25921 #else
25922 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25923 #endif
25924 
25925 	mp = ipsec_mp->b_cont;
25926 	ipha1 = (ipha_t *)mp->b_rptr;
25927 	ASSERT(mp != NULL);
25928 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25929 	dst = ipha->ipha_dst;
25930 
25931 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25932 	ill_index = io->ipsec_out_ill_index;
25933 	zoneid = io->ipsec_out_zoneid;
25934 	ASSERT(zoneid != ALL_ZONES);
25935 	ipst = io->ipsec_out_ns->netstack_ip;
25936 	ASSERT(io->ipsec_out_ns != NULL);
25937 
25938 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25939 	if (ill == NULL && ill_index != 0) {
25940 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25941 		/* Failure case frees things for us. */
25942 		if (ill == NULL)
25943 			return;
25944 
25945 		ill_need_rele = B_TRUE;
25946 	}
25947 
25948 	if (CLASSD(dst)) {
25949 		boolean_t conn_dontroute;
25950 		/*
25951 		 * Use the ill_index to get the right ipif.
25952 		 */
25953 		conn_dontroute = io->ipsec_out_dontroute;
25954 		if (ill_index == 0)
25955 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25956 		else
25957 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25958 		if (ipif == NULL) {
25959 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25960 			    " multicast\n"));
25961 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25962 			freemsg(ipsec_mp);
25963 			goto done;
25964 		}
25965 		/*
25966 		 * ipha_src has already been intialized with the
25967 		 * value of the ipif in ip_wput. All we need now is
25968 		 * an ire to send this downstream.
25969 		 */
25970 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25971 		    msg_getlabel(mp), match_flags, ipst);
25972 		if (ire != NULL) {
25973 			ill_t *ill1;
25974 			/*
25975 			 * Do the multicast forwarding now, as the IPsec
25976 			 * processing has been done.
25977 			 */
25978 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25979 			    (ill1 = ire_to_ill(ire))) {
25980 				if (ip_mforward(ill1, ipha, mp)) {
25981 					freemsg(ipsec_mp);
25982 					ip1dbg(("ip_wput_ipsec_out: mforward "
25983 					    "failed\n"));
25984 					ire_refrele(ire);
25985 					goto done;
25986 				}
25987 			}
25988 			goto send;
25989 		}
25990 
25991 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25992 		mp->b_prev = NULL;
25993 		mp->b_next = NULL;
25994 
25995 		/*
25996 		 * If the IPsec packet was processed asynchronously,
25997 		 * drop it now.
25998 		 */
25999 		if (q == NULL) {
26000 			freemsg(ipsec_mp);
26001 			goto done;
26002 		}
26003 
26004 		/*
26005 		 * We may be using a wrong ipif to create the ire.
26006 		 * But it is okay as the source address is assigned
26007 		 * for the packet already. Next outbound packet would
26008 		 * create the IRE with the right IPIF in ip_wput.
26009 		 *
26010 		 * Also handle RTF_MULTIRT routes.
26011 		 */
26012 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26013 		    zoneid, &zero_info);
26014 	} else {
26015 		if (ire_arg != NULL) {
26016 			ire = ire_arg;
26017 			ire_need_rele = B_FALSE;
26018 		} else {
26019 			ire = ire_cache_lookup(dst, zoneid,
26020 			    msg_getlabel(mp), ipst);
26021 		}
26022 		if (ire != NULL) {
26023 			goto send;
26024 		}
26025 
26026 		/*
26027 		 * ire disappeared underneath.
26028 		 *
26029 		 * What we need to do here is the ip_newroute
26030 		 * logic to get the ire without doing the IPsec
26031 		 * processing. Follow the same old path. But this
26032 		 * time, ip_wput or ire_add_then_put will call us
26033 		 * directly as all the IPsec operations are done.
26034 		 */
26035 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26036 		mp->b_prev = NULL;
26037 		mp->b_next = NULL;
26038 
26039 		/*
26040 		 * If the IPsec packet was processed asynchronously,
26041 		 * drop it now.
26042 		 */
26043 		if (q == NULL) {
26044 			freemsg(ipsec_mp);
26045 			goto done;
26046 		}
26047 
26048 		/*
26049 		 * Since we're going through ip_newroute() again, we
26050 		 * need to make sure we don't:
26051 		 *
26052 		 *	1.) Trigger the ASSERT() with the ipha_ident
26053 		 *	    overloading.
26054 		 *	2.) Redo transport-layer checksumming, since we've
26055 		 *	    already done all that to get this far.
26056 		 *
26057 		 * The easiest way not do either of the above is to set
26058 		 * the ipha_ident field to IP_HDR_INCLUDED.
26059 		 */
26060 		ipha->ipha_ident = IP_HDR_INCLUDED;
26061 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26062 		    zoneid, ipst);
26063 	}
26064 	goto done;
26065 send:
26066 	if (ire->ire_stq == NULL) {
26067 		ill_t	*out_ill;
26068 		/*
26069 		 * Loopbacks go through ip_wput_local except for one case.
26070 		 * We come here if we generate a icmp_frag_needed message
26071 		 * after IPsec processing is over. When this function calls
26072 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26073 		 * icmp_frag_needed. The message generated comes back here
26074 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26075 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26076 		 * source address as it is usually set in ip_wput_ire. As
26077 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26078 		 * and we end up here. We can't enter ip_wput_ire once the
26079 		 * IPsec processing is over and hence we need to do it here.
26080 		 */
26081 		ASSERT(q != NULL);
26082 		UPDATE_OB_PKT_COUNT(ire);
26083 		ire->ire_last_used_time = lbolt;
26084 		if (ipha->ipha_src == 0)
26085 			ipha->ipha_src = ire->ire_src_addr;
26086 
26087 		/* PFHooks: LOOPBACK_OUT */
26088 		out_ill = ire_to_ill(ire);
26089 
26090 		/*
26091 		 * DTrace this as ip:::send.  A blocked packet will fire the
26092 		 * send probe, but not the receive probe.
26093 		 */
26094 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26095 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26096 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26097 
26098 		DTRACE_PROBE4(ip4__loopback__out__start,
26099 		    ill_t *, NULL, ill_t *, out_ill,
26100 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26101 
26102 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26103 		    ipst->ips_ipv4firewall_loopback_out,
26104 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26105 
26106 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26107 
26108 		if (ipsec_mp != NULL)
26109 			ip_wput_local(RD(q), out_ill,
26110 			    ipha, ipsec_mp, ire, 0, zoneid);
26111 		if (ire_need_rele)
26112 			ire_refrele(ire);
26113 		goto done;
26114 	}
26115 
26116 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26117 		/*
26118 		 * We are through with IPsec processing.
26119 		 * Fragment this and send it on the wire.
26120 		 */
26121 		if (io->ipsec_out_accelerated) {
26122 			/*
26123 			 * The packet has been accelerated but must
26124 			 * be fragmented. This should not happen
26125 			 * since AH and ESP must not accelerate
26126 			 * packets that need fragmentation, however
26127 			 * the configuration could have changed
26128 			 * since the AH or ESP processing.
26129 			 * Drop packet.
26130 			 * IPsec KSTATS: bump bean counter here.
26131 			 */
26132 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26133 			    "fragmented accelerated packet!\n"));
26134 			freemsg(ipsec_mp);
26135 		} else {
26136 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26137 			    zoneid, ipst, NULL);
26138 		}
26139 		if (ire_need_rele)
26140 			ire_refrele(ire);
26141 		goto done;
26142 	}
26143 
26144 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26145 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26146 	    (void *)ire->ire_ipif, (void *)ipif));
26147 
26148 	/*
26149 	 * Multiroute the secured packet.
26150 	 */
26151 	if (ire->ire_flags & RTF_MULTIRT) {
26152 		ire_t *first_ire;
26153 		irb = ire->ire_bucket;
26154 		ASSERT(irb != NULL);
26155 		/*
26156 		 * This ire has been looked up as the one that
26157 		 * goes through the given ipif;
26158 		 * make sure we do not omit any other multiroute ire
26159 		 * that may be present in the bucket before this one.
26160 		 */
26161 		IRB_REFHOLD(irb);
26162 		for (first_ire = irb->irb_ire;
26163 		    first_ire != NULL;
26164 		    first_ire = first_ire->ire_next) {
26165 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26166 			    (first_ire->ire_addr == ire->ire_addr) &&
26167 			    !(first_ire->ire_marks &
26168 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26169 				break;
26170 		}
26171 
26172 		if ((first_ire != NULL) && (first_ire != ire)) {
26173 			/*
26174 			 * Don't change the ire if the packet must
26175 			 * be fragmented if sent via this new one.
26176 			 */
26177 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26178 				IRE_REFHOLD(first_ire);
26179 				if (ire_need_rele)
26180 					ire_refrele(ire);
26181 				else
26182 					ire_need_rele = B_TRUE;
26183 				ire = first_ire;
26184 			}
26185 		}
26186 		IRB_REFRELE(irb);
26187 
26188 		multirt_send = B_TRUE;
26189 		max_frag = ire->ire_max_frag;
26190 	}
26191 
26192 	/*
26193 	 * In most cases, the emission loop below is entered only once.
26194 	 * Only in the case where the ire holds the RTF_MULTIRT
26195 	 * flag, we loop to process all RTF_MULTIRT ires in the
26196 	 * bucket, and send the packet through all crossed
26197 	 * RTF_MULTIRT routes.
26198 	 */
26199 	do {
26200 		if (multirt_send) {
26201 			/*
26202 			 * ire1 holds here the next ire to process in the
26203 			 * bucket. If multirouting is expected,
26204 			 * any non-RTF_MULTIRT ire that has the
26205 			 * right destination address is ignored.
26206 			 */
26207 			ASSERT(irb != NULL);
26208 			IRB_REFHOLD(irb);
26209 			for (ire1 = ire->ire_next;
26210 			    ire1 != NULL;
26211 			    ire1 = ire1->ire_next) {
26212 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26213 					continue;
26214 				if (ire1->ire_addr != ire->ire_addr)
26215 					continue;
26216 				if (ire1->ire_marks &
26217 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26218 					continue;
26219 				/* No loopback here */
26220 				if (ire1->ire_stq == NULL)
26221 					continue;
26222 				/*
26223 				 * Ensure we do not exceed the MTU
26224 				 * of the next route.
26225 				 */
26226 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26227 					ip_multirt_bad_mtu(ire1, max_frag);
26228 					continue;
26229 				}
26230 
26231 				IRE_REFHOLD(ire1);
26232 				break;
26233 			}
26234 			IRB_REFRELE(irb);
26235 			if (ire1 != NULL) {
26236 				/*
26237 				 * We are in a multiple send case, need to
26238 				 * make a copy of the packet.
26239 				 */
26240 				next_mp = copymsg(ipsec_mp);
26241 				if (next_mp == NULL) {
26242 					ire_refrele(ire1);
26243 					ire1 = NULL;
26244 				}
26245 			}
26246 		}
26247 		/*
26248 		 * Everything is done. Send it out on the wire
26249 		 *
26250 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26251 		 * either send it on the wire or, in the case of
26252 		 * HW acceleration, call ipsec_hw_putnext.
26253 		 */
26254 		if (ire->ire_nce &&
26255 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26256 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26257 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26258 			/*
26259 			 * If ire's link-layer is unresolved (this
26260 			 * would only happen if the incomplete ire
26261 			 * was added to cachetable via forwarding path)
26262 			 * don't bother going to ip_xmit_v4. Just drop the
26263 			 * packet.
26264 			 * There is a slight risk here, in that, if we
26265 			 * have the forwarding path create an incomplete
26266 			 * IRE, then until the IRE is completed, any
26267 			 * transmitted IPsec packets will be dropped
26268 			 * instead of being queued waiting for resolution.
26269 			 *
26270 			 * But the likelihood of a forwarding packet and a wput
26271 			 * packet sending to the same dst at the same time
26272 			 * and there not yet be an ARP entry for it is small.
26273 			 * Furthermore, if this actually happens, it might
26274 			 * be likely that wput would generate multiple
26275 			 * packets (and forwarding would also have a train
26276 			 * of packets) for that destination. If this is
26277 			 * the case, some of them would have been dropped
26278 			 * anyway, since ARP only queues a few packets while
26279 			 * waiting for resolution
26280 			 *
26281 			 * NOTE: We should really call ip_xmit_v4,
26282 			 * and let it queue the packet and send the
26283 			 * ARP query and have ARP come back thus:
26284 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26285 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26286 			 * hw accel work. But it's too complex to get
26287 			 * the IPsec hw  acceleration approach to fit
26288 			 * well with ip_xmit_v4 doing ARP without
26289 			 * doing IPsec simplification. For now, we just
26290 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26291 			 * that we can continue with the send on the next
26292 			 * attempt.
26293 			 *
26294 			 * XXX THis should be revisited, when
26295 			 * the IPsec/IP interaction is cleaned up
26296 			 */
26297 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26298 			    " - dropping packet\n"));
26299 			freemsg(ipsec_mp);
26300 			/*
26301 			 * Call ip_xmit_v4() to trigger ARP query
26302 			 * in case the nce_state is ND_INITIAL
26303 			 */
26304 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26305 			goto drop_pkt;
26306 		}
26307 
26308 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26309 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26310 		    mblk_t *, ipsec_mp);
26311 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26312 		    ipst->ips_ipv4firewall_physical_out, NULL,
26313 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26314 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26315 		if (ipsec_mp == NULL)
26316 			goto drop_pkt;
26317 
26318 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26319 		pktxmit_state = ip_xmit_v4(mp, ire,
26320 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26321 
26322 		if ((pktxmit_state ==  SEND_FAILED) ||
26323 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26324 
26325 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26326 drop_pkt:
26327 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26328 			    ipIfStatsOutDiscards);
26329 			if (ire_need_rele)
26330 				ire_refrele(ire);
26331 			if (ire1 != NULL) {
26332 				ire_refrele(ire1);
26333 				freemsg(next_mp);
26334 			}
26335 			goto done;
26336 		}
26337 
26338 		freeb(ipsec_mp);
26339 		if (ire_need_rele)
26340 			ire_refrele(ire);
26341 
26342 		if (ire1 != NULL) {
26343 			ire = ire1;
26344 			ire_need_rele = B_TRUE;
26345 			ASSERT(next_mp);
26346 			ipsec_mp = next_mp;
26347 			mp = ipsec_mp->b_cont;
26348 			ire1 = NULL;
26349 			next_mp = NULL;
26350 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26351 		} else {
26352 			multirt_send = B_FALSE;
26353 		}
26354 	} while (multirt_send);
26355 done:
26356 	if (ill != NULL && ill_need_rele)
26357 		ill_refrele(ill);
26358 	if (ipif != NULL)
26359 		ipif_refrele(ipif);
26360 }
26361 
26362 /*
26363  * Get the ill corresponding to the specified ire, and compare its
26364  * capabilities with the protocol and algorithms specified by the
26365  * the SA obtained from ipsec_out. If they match, annotate the
26366  * ipsec_out structure to indicate that the packet needs acceleration.
26367  *
26368  *
26369  * A packet is eligible for outbound hardware acceleration if the
26370  * following conditions are satisfied:
26371  *
26372  * 1. the packet will not be fragmented
26373  * 2. the provider supports the algorithm
26374  * 3. there is no pending control message being exchanged
26375  * 4. snoop is not attached
26376  * 5. the destination address is not a broadcast or multicast address.
26377  *
26378  * Rationale:
26379  *	- Hardware drivers do not support fragmentation with
26380  *	  the current interface.
26381  *	- snoop, multicast, and broadcast may result in exposure of
26382  *	  a cleartext datagram.
26383  * We check all five of these conditions here.
26384  *
26385  * XXX would like to nuke "ire_t *" parameter here; problem is that
26386  * IRE is only way to figure out if a v4 address is a broadcast and
26387  * thus ineligible for acceleration...
26388  */
26389 static void
26390 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26391 {
26392 	ipsec_out_t *io;
26393 	mblk_t *data_mp;
26394 	uint_t plen, overhead;
26395 	ip_stack_t	*ipst;
26396 
26397 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26398 		return;
26399 
26400 	if (ill == NULL)
26401 		return;
26402 	ipst = ill->ill_ipst;
26403 	/*
26404 	 * Destination address is a broadcast or multicast.  Punt.
26405 	 */
26406 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26407 	    IRE_LOCAL)))
26408 		return;
26409 
26410 	data_mp = ipsec_mp->b_cont;
26411 
26412 	if (ill->ill_isv6) {
26413 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26414 
26415 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26416 			return;
26417 
26418 		plen = ip6h->ip6_plen;
26419 	} else {
26420 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26421 
26422 		if (CLASSD(ipha->ipha_dst))
26423 			return;
26424 
26425 		plen = ipha->ipha_length;
26426 	}
26427 	/*
26428 	 * Is there a pending DLPI control message being exchanged
26429 	 * between IP/IPsec and the DLS Provider? If there is, it
26430 	 * could be a SADB update, and the state of the DLS Provider
26431 	 * SADB might not be in sync with the SADB maintained by
26432 	 * IPsec. To avoid dropping packets or using the wrong keying
26433 	 * material, we do not accelerate this packet.
26434 	 */
26435 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26436 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26437 		    "ill_dlpi_pending! don't accelerate packet\n"));
26438 		return;
26439 	}
26440 
26441 	/*
26442 	 * Is the Provider in promiscous mode? If it does, we don't
26443 	 * accelerate the packet since it will bounce back up to the
26444 	 * listeners in the clear.
26445 	 */
26446 	if (ill->ill_promisc_on_phys) {
26447 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26448 		    "ill in promiscous mode, don't accelerate packet\n"));
26449 		return;
26450 	}
26451 
26452 	/*
26453 	 * Will the packet require fragmentation?
26454 	 */
26455 
26456 	/*
26457 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26458 	 * as is used elsewhere.
26459 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26460 	 *	+ 2-byte trailer
26461 	 */
26462 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26463 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26464 
26465 	if ((plen + overhead) > ill->ill_max_mtu)
26466 		return;
26467 
26468 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26469 
26470 	/*
26471 	 * Can the ill accelerate this IPsec protocol and algorithm
26472 	 * specified by the SA?
26473 	 */
26474 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26475 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26476 		return;
26477 	}
26478 
26479 	/*
26480 	 * Tell AH or ESP that the outbound ill is capable of
26481 	 * accelerating this packet.
26482 	 */
26483 	io->ipsec_out_is_capab_ill = B_TRUE;
26484 }
26485 
26486 /*
26487  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26488  *
26489  * If this function returns B_TRUE, the requested SA's have been filled
26490  * into the ipsec_out_*_sa pointers.
26491  *
26492  * If the function returns B_FALSE, the packet has been "consumed", most
26493  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26494  *
26495  * The SA references created by the protocol-specific "select"
26496  * function will be released when the ipsec_mp is freed, thanks to the
26497  * ipsec_out_free destructor -- see spd.c.
26498  */
26499 static boolean_t
26500 ipsec_out_select_sa(mblk_t *ipsec_mp)
26501 {
26502 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26503 	ipsec_out_t *io;
26504 	ipsec_policy_t *pp;
26505 	ipsec_action_t *ap;
26506 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26507 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26508 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26509 
26510 	if (!io->ipsec_out_secure) {
26511 		/*
26512 		 * We came here by mistake.
26513 		 * Don't bother with ipsec processing
26514 		 * We should "discourage" this path in the future.
26515 		 */
26516 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26517 		return (B_FALSE);
26518 	}
26519 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26520 	ASSERT((io->ipsec_out_policy != NULL) ||
26521 	    (io->ipsec_out_act != NULL));
26522 
26523 	ASSERT(io->ipsec_out_failed == B_FALSE);
26524 
26525 	/*
26526 	 * IPsec processing has started.
26527 	 */
26528 	io->ipsec_out_proc_begin = B_TRUE;
26529 	ap = io->ipsec_out_act;
26530 	if (ap == NULL) {
26531 		pp = io->ipsec_out_policy;
26532 		ASSERT(pp != NULL);
26533 		ap = pp->ipsp_act;
26534 		ASSERT(ap != NULL);
26535 	}
26536 
26537 	/*
26538 	 * We have an action.  now, let's select SA's.
26539 	 * (In the future, we can cache this in the conn_t..)
26540 	 */
26541 	if (ap->ipa_want_esp) {
26542 		if (io->ipsec_out_esp_sa == NULL) {
26543 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26544 			    IPPROTO_ESP);
26545 		}
26546 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26547 	}
26548 
26549 	if (ap->ipa_want_ah) {
26550 		if (io->ipsec_out_ah_sa == NULL) {
26551 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26552 			    IPPROTO_AH);
26553 		}
26554 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26555 		/*
26556 		 * The ESP and AH processing order needs to be preserved
26557 		 * when both protocols are required (ESP should be applied
26558 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26559 		 * when both ESP and AH are required, and an AH ACQUIRE
26560 		 * is needed.
26561 		 */
26562 		if (ap->ipa_want_esp && need_ah_acquire)
26563 			need_esp_acquire = B_TRUE;
26564 	}
26565 
26566 	/*
26567 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26568 	 * Release SAs that got referenced, but will not be used until we
26569 	 * acquire _all_ of the SAs we need.
26570 	 */
26571 	if (need_ah_acquire || need_esp_acquire) {
26572 		if (io->ipsec_out_ah_sa != NULL) {
26573 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26574 			io->ipsec_out_ah_sa = NULL;
26575 		}
26576 		if (io->ipsec_out_esp_sa != NULL) {
26577 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26578 			io->ipsec_out_esp_sa = NULL;
26579 		}
26580 
26581 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26582 		return (B_FALSE);
26583 	}
26584 
26585 	return (B_TRUE);
26586 }
26587 
26588 /*
26589  * Process an IPSEC_OUT message and see what you can
26590  * do with it.
26591  * IPQoS Notes:
26592  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26593  * IPsec.
26594  * XXX would like to nuke ire_t.
26595  * XXX ill_index better be "real"
26596  */
26597 void
26598 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26599 {
26600 	ipsec_out_t *io;
26601 	ipsec_policy_t *pp;
26602 	ipsec_action_t *ap;
26603 	ipha_t *ipha;
26604 	ip6_t *ip6h;
26605 	mblk_t *mp;
26606 	ill_t *ill;
26607 	zoneid_t zoneid;
26608 	ipsec_status_t ipsec_rc;
26609 	boolean_t ill_need_rele = B_FALSE;
26610 	ip_stack_t	*ipst;
26611 	ipsec_stack_t	*ipss;
26612 
26613 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26614 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26615 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26616 	ipst = io->ipsec_out_ns->netstack_ip;
26617 	mp = ipsec_mp->b_cont;
26618 
26619 	/*
26620 	 * Initiate IPPF processing. We do it here to account for packets
26621 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26622 	 * We can check for ipsec_out_proc_begin even for such packets, as
26623 	 * they will always be false (asserted below).
26624 	 */
26625 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26626 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26627 		    io->ipsec_out_ill_index : ill_index);
26628 		if (mp == NULL) {
26629 			ip2dbg(("ipsec_out_process: packet dropped "\
26630 			    "during IPPF processing\n"));
26631 			freeb(ipsec_mp);
26632 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26633 			return;
26634 		}
26635 	}
26636 
26637 	if (!io->ipsec_out_secure) {
26638 		/*
26639 		 * We came here by mistake.
26640 		 * Don't bother with ipsec processing
26641 		 * Should "discourage" this path in the future.
26642 		 */
26643 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26644 		goto done;
26645 	}
26646 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26647 	ASSERT((io->ipsec_out_policy != NULL) ||
26648 	    (io->ipsec_out_act != NULL));
26649 	ASSERT(io->ipsec_out_failed == B_FALSE);
26650 
26651 	ipss = ipst->ips_netstack->netstack_ipsec;
26652 	if (!ipsec_loaded(ipss)) {
26653 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26654 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26655 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26656 		} else {
26657 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26658 		}
26659 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26660 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26661 		    &ipss->ipsec_dropper);
26662 		return;
26663 	}
26664 
26665 	/*
26666 	 * IPsec processing has started.
26667 	 */
26668 	io->ipsec_out_proc_begin = B_TRUE;
26669 	ap = io->ipsec_out_act;
26670 	if (ap == NULL) {
26671 		pp = io->ipsec_out_policy;
26672 		ASSERT(pp != NULL);
26673 		ap = pp->ipsp_act;
26674 		ASSERT(ap != NULL);
26675 	}
26676 
26677 	/*
26678 	 * Save the outbound ill index. When the packet comes back
26679 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26680 	 * before sending it the accelerated packet.
26681 	 */
26682 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26683 		ill = ire_to_ill(ire);
26684 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26685 	}
26686 
26687 	/*
26688 	 * The order of processing is first insert a IP header if needed.
26689 	 * Then insert the ESP header and then the AH header.
26690 	 */
26691 	if ((io->ipsec_out_se_done == B_FALSE) &&
26692 	    (ap->ipa_want_se)) {
26693 		/*
26694 		 * First get the outer IP header before sending
26695 		 * it to ESP.
26696 		 */
26697 		ipha_t *oipha, *iipha;
26698 		mblk_t *outer_mp, *inner_mp;
26699 
26700 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26701 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26702 			    "ipsec_out_process: "
26703 			    "Self-Encapsulation failed: Out of memory\n");
26704 			freemsg(ipsec_mp);
26705 			if (ill != NULL) {
26706 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26707 			} else {
26708 				BUMP_MIB(&ipst->ips_ip_mib,
26709 				    ipIfStatsOutDiscards);
26710 			}
26711 			return;
26712 		}
26713 		inner_mp = ipsec_mp->b_cont;
26714 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26715 		oipha = (ipha_t *)outer_mp->b_rptr;
26716 		iipha = (ipha_t *)inner_mp->b_rptr;
26717 		*oipha = *iipha;
26718 		outer_mp->b_wptr += sizeof (ipha_t);
26719 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26720 		    sizeof (ipha_t));
26721 		oipha->ipha_protocol = IPPROTO_ENCAP;
26722 		oipha->ipha_version_and_hdr_length =
26723 		    IP_SIMPLE_HDR_VERSION;
26724 		oipha->ipha_hdr_checksum = 0;
26725 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26726 		outer_mp->b_cont = inner_mp;
26727 		ipsec_mp->b_cont = outer_mp;
26728 
26729 		io->ipsec_out_se_done = B_TRUE;
26730 		io->ipsec_out_tunnel = B_TRUE;
26731 	}
26732 
26733 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26734 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26735 	    !ipsec_out_select_sa(ipsec_mp))
26736 		return;
26737 
26738 	/*
26739 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26740 	 * to do the heavy lifting.
26741 	 */
26742 	zoneid = io->ipsec_out_zoneid;
26743 	ASSERT(zoneid != ALL_ZONES);
26744 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26745 		ASSERT(io->ipsec_out_esp_sa != NULL);
26746 		io->ipsec_out_esp_done = B_TRUE;
26747 		/*
26748 		 * Note that since hw accel can only apply one transform,
26749 		 * not two, we skip hw accel for ESP if we also have AH
26750 		 * This is an design limitation of the interface
26751 		 * which should be revisited.
26752 		 */
26753 		ASSERT(ire != NULL);
26754 		if (io->ipsec_out_ah_sa == NULL) {
26755 			ill = (ill_t *)ire->ire_stq->q_ptr;
26756 			ipsec_out_is_accelerated(ipsec_mp,
26757 			    io->ipsec_out_esp_sa, ill, ire);
26758 		}
26759 
26760 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26761 		switch (ipsec_rc) {
26762 		case IPSEC_STATUS_SUCCESS:
26763 			break;
26764 		case IPSEC_STATUS_FAILED:
26765 			if (ill != NULL) {
26766 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26767 			} else {
26768 				BUMP_MIB(&ipst->ips_ip_mib,
26769 				    ipIfStatsOutDiscards);
26770 			}
26771 			/* FALLTHRU */
26772 		case IPSEC_STATUS_PENDING:
26773 			return;
26774 		}
26775 	}
26776 
26777 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26778 		ASSERT(io->ipsec_out_ah_sa != NULL);
26779 		io->ipsec_out_ah_done = B_TRUE;
26780 		if (ire == NULL) {
26781 			int idx = io->ipsec_out_capab_ill_index;
26782 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26783 			    NULL, NULL, NULL, NULL, ipst);
26784 			ill_need_rele = B_TRUE;
26785 		} else {
26786 			ill = (ill_t *)ire->ire_stq->q_ptr;
26787 		}
26788 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26789 		    ire);
26790 
26791 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26792 		switch (ipsec_rc) {
26793 		case IPSEC_STATUS_SUCCESS:
26794 			break;
26795 		case IPSEC_STATUS_FAILED:
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 			/* FALLTHRU */
26803 		case IPSEC_STATUS_PENDING:
26804 			if (ill != NULL && ill_need_rele)
26805 				ill_refrele(ill);
26806 			return;
26807 		}
26808 	}
26809 	/*
26810 	 * We are done with IPsec processing. Send it over the wire.
26811 	 */
26812 done:
26813 	mp = ipsec_mp->b_cont;
26814 	ipha = (ipha_t *)mp->b_rptr;
26815 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26816 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26817 		    ire);
26818 	} else {
26819 		ip6h = (ip6_t *)ipha;
26820 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26821 		    ire);
26822 	}
26823 	if (ill != NULL && ill_need_rele)
26824 		ill_refrele(ill);
26825 }
26826 
26827 /* ARGSUSED */
26828 void
26829 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26830 {
26831 	opt_restart_t	*or;
26832 	int	err;
26833 	conn_t	*connp;
26834 	cred_t	*cr;
26835 
26836 	ASSERT(CONN_Q(q));
26837 	connp = Q_TO_CONN(q);
26838 
26839 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26840 	or = (opt_restart_t *)first_mp->b_rptr;
26841 	/*
26842 	 * We checked for a db_credp the first time svr4_optcom_req
26843 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26844 	 */
26845 	cr = msg_getcred(first_mp, NULL);
26846 	ASSERT(cr != NULL);
26847 
26848 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26849 		err = svr4_optcom_req(q, first_mp, cr,
26850 		    &ip_opt_obj, B_FALSE);
26851 	} else {
26852 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26853 		err = tpi_optcom_req(q, first_mp, cr,
26854 		    &ip_opt_obj, B_FALSE);
26855 	}
26856 	if (err != EINPROGRESS) {
26857 		/* operation is done */
26858 		CONN_OPER_PENDING_DONE(connp);
26859 	}
26860 }
26861 
26862 /*
26863  * ioctls that go through a down/up sequence may need to wait for the down
26864  * to complete. This involves waiting for the ire and ipif refcnts to go down
26865  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26866  */
26867 /* ARGSUSED */
26868 void
26869 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26870 {
26871 	struct iocblk *iocp;
26872 	mblk_t *mp1;
26873 	ip_ioctl_cmd_t *ipip;
26874 	int err;
26875 	sin_t	*sin;
26876 	struct lifreq *lifr;
26877 	struct ifreq *ifr;
26878 
26879 	iocp = (struct iocblk *)mp->b_rptr;
26880 	ASSERT(ipsq != NULL);
26881 	/* Existence of mp1 verified in ip_wput_nondata */
26882 	mp1 = mp->b_cont->b_cont;
26883 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26884 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26885 		/*
26886 		 * Special case where ipx_current_ipif is not set:
26887 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26888 		 * We are here as were not able to complete the operation in
26889 		 * ipif_set_values because we could not become exclusive on
26890 		 * the new ipsq.
26891 		 */
26892 		ill_t *ill = q->q_ptr;
26893 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26894 	}
26895 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26896 
26897 	if (ipip->ipi_cmd_type == IF_CMD) {
26898 		/* This a old style SIOC[GS]IF* command */
26899 		ifr = (struct ifreq *)mp1->b_rptr;
26900 		sin = (sin_t *)&ifr->ifr_addr;
26901 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26902 		/* This a new style SIOC[GS]LIF* command */
26903 		lifr = (struct lifreq *)mp1->b_rptr;
26904 		sin = (sin_t *)&lifr->lifr_addr;
26905 	} else {
26906 		sin = NULL;
26907 	}
26908 
26909 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26910 	    q, mp, ipip, mp1->b_rptr);
26911 
26912 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26913 }
26914 
26915 /*
26916  * ioctl processing
26917  *
26918  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26919  * the ioctl command in the ioctl tables, determines the copyin data size
26920  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26921  *
26922  * ioctl processing then continues when the M_IOCDATA makes its way down to
26923  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26924  * associated 'conn' is refheld till the end of the ioctl and the general
26925  * ioctl processing function ip_process_ioctl() is called to extract the
26926  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26927  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26928  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26929  * is used to extract the ioctl's arguments.
26930  *
26931  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26932  * so goes thru the serialization primitive ipsq_try_enter. Then the
26933  * appropriate function to handle the ioctl is called based on the entry in
26934  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26935  * which also refreleases the 'conn' that was refheld at the start of the
26936  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26937  *
26938  * Many exclusive ioctls go thru an internal down up sequence as part of
26939  * the operation. For example an attempt to change the IP address of an
26940  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26941  * does all the cleanup such as deleting all ires that use this address.
26942  * Then we need to wait till all references to the interface go away.
26943  */
26944 void
26945 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26946 {
26947 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26948 	ip_ioctl_cmd_t *ipip = arg;
26949 	ip_extract_func_t *extract_funcp;
26950 	cmd_info_t ci;
26951 	int err;
26952 	boolean_t entered_ipsq = B_FALSE;
26953 
26954 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26955 
26956 	if (ipip == NULL)
26957 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26958 
26959 	/*
26960 	 * SIOCLIFADDIF needs to go thru a special path since the
26961 	 * ill may not exist yet. This happens in the case of lo0
26962 	 * which is created using this ioctl.
26963 	 */
26964 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26965 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26966 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26967 		return;
26968 	}
26969 
26970 	ci.ci_ipif = NULL;
26971 	if (ipip->ipi_cmd_type == MISC_CMD) {
26972 		/*
26973 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26974 		 */
26975 		if (ipip->ipi_cmd == IF_UNITSEL) {
26976 			/* ioctl comes down the ill */
26977 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26978 			ipif_refhold(ci.ci_ipif);
26979 		}
26980 		err = 0;
26981 		ci.ci_sin = NULL;
26982 		ci.ci_sin6 = NULL;
26983 		ci.ci_lifr = NULL;
26984 	} else {
26985 		switch (ipip->ipi_cmd_type) {
26986 		case IF_CMD:
26987 		case LIF_CMD:
26988 			extract_funcp = ip_extract_lifreq;
26989 			break;
26990 
26991 		case ARP_CMD:
26992 		case XARP_CMD:
26993 			extract_funcp = ip_extract_arpreq;
26994 			break;
26995 
26996 		case TUN_CMD:
26997 			extract_funcp = ip_extract_tunreq;
26998 			break;
26999 
27000 		case MSFILT_CMD:
27001 			extract_funcp = ip_extract_msfilter;
27002 			break;
27003 
27004 		default:
27005 			ASSERT(0);
27006 		}
27007 
27008 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27009 		if (err != 0) {
27010 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27011 			return;
27012 		}
27013 
27014 		/*
27015 		 * All of the extraction functions return a refheld ipif.
27016 		 */
27017 		ASSERT(ci.ci_ipif != NULL);
27018 	}
27019 
27020 	if (!(ipip->ipi_flags & IPI_WR)) {
27021 		/*
27022 		 * A return value of EINPROGRESS means the ioctl is
27023 		 * either queued and waiting for some reason or has
27024 		 * already completed.
27025 		 */
27026 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27027 		    ci.ci_lifr);
27028 		if (ci.ci_ipif != NULL)
27029 			ipif_refrele(ci.ci_ipif);
27030 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27031 		return;
27032 	}
27033 
27034 	ASSERT(ci.ci_ipif != NULL);
27035 
27036 	/*
27037 	 * If ipsq is non-NULL, we are already being called exclusively.
27038 	 */
27039 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27040 	if (ipsq == NULL) {
27041 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27042 		    NEW_OP, B_TRUE);
27043 		if (ipsq == NULL) {
27044 			ipif_refrele(ci.ci_ipif);
27045 			return;
27046 		}
27047 		entered_ipsq = B_TRUE;
27048 	}
27049 
27050 	/*
27051 	 * Release the ipif so that ipif_down and friends that wait for
27052 	 * references to go away are not misled about the current ipif_refcnt
27053 	 * values. We are writer so we can access the ipif even after releasing
27054 	 * the ipif.
27055 	 */
27056 	ipif_refrele(ci.ci_ipif);
27057 
27058 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27059 
27060 	/*
27061 	 * A return value of EINPROGRESS means the ioctl is
27062 	 * either queued and waiting for some reason or has
27063 	 * already completed.
27064 	 */
27065 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27066 
27067 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27068 
27069 	if (entered_ipsq)
27070 		ipsq_exit(ipsq);
27071 }
27072 
27073 /*
27074  * Complete the ioctl. Typically ioctls use the mi package and need to
27075  * do mi_copyout/mi_copy_done.
27076  */
27077 void
27078 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27079 {
27080 	conn_t	*connp = NULL;
27081 
27082 	if (err == EINPROGRESS)
27083 		return;
27084 
27085 	if (CONN_Q(q)) {
27086 		connp = Q_TO_CONN(q);
27087 		ASSERT(connp->conn_ref >= 2);
27088 	}
27089 
27090 	switch (mode) {
27091 	case COPYOUT:
27092 		if (err == 0)
27093 			mi_copyout(q, mp);
27094 		else
27095 			mi_copy_done(q, mp, err);
27096 		break;
27097 
27098 	case NO_COPYOUT:
27099 		mi_copy_done(q, mp, err);
27100 		break;
27101 
27102 	default:
27103 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27104 		break;
27105 	}
27106 
27107 	/*
27108 	 * The refhold placed at the start of the ioctl is released here.
27109 	 */
27110 	if (connp != NULL)
27111 		CONN_OPER_PENDING_DONE(connp);
27112 
27113 	if (ipsq != NULL)
27114 		ipsq_current_finish(ipsq);
27115 }
27116 
27117 /* Called from ip_wput for all non data messages */
27118 /* ARGSUSED */
27119 void
27120 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27121 {
27122 	mblk_t		*mp1;
27123 	ire_t		*ire, *fake_ire;
27124 	ill_t		*ill;
27125 	struct iocblk	*iocp;
27126 	ip_ioctl_cmd_t	*ipip;
27127 	cred_t		*cr;
27128 	conn_t		*connp;
27129 	int		err;
27130 	nce_t		*nce;
27131 	ipif_t		*ipif;
27132 	ip_stack_t	*ipst;
27133 	char		*proto_str;
27134 
27135 	if (CONN_Q(q)) {
27136 		connp = Q_TO_CONN(q);
27137 		ipst = connp->conn_netstack->netstack_ip;
27138 	} else {
27139 		connp = NULL;
27140 		ipst = ILLQ_TO_IPST(q);
27141 	}
27142 
27143 	switch (DB_TYPE(mp)) {
27144 	case M_IOCTL:
27145 		/*
27146 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27147 		 * will arrange to copy in associated control structures.
27148 		 */
27149 		ip_sioctl_copyin_setup(q, mp);
27150 		return;
27151 	case M_IOCDATA:
27152 		/*
27153 		 * Ensure that this is associated with one of our trans-
27154 		 * parent ioctls.  If it's not ours, discard it if we're
27155 		 * running as a driver, or pass it on if we're a module.
27156 		 */
27157 		iocp = (struct iocblk *)mp->b_rptr;
27158 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27159 		if (ipip == NULL) {
27160 			if (q->q_next == NULL) {
27161 				goto nak;
27162 			} else {
27163 				putnext(q, mp);
27164 			}
27165 			return;
27166 		}
27167 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27168 			/*
27169 			 * the ioctl is one we recognise, but is not
27170 			 * consumed by IP as a module, pass M_IOCDATA
27171 			 * for processing downstream, but only for
27172 			 * common Streams ioctls.
27173 			 */
27174 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27175 				putnext(q, mp);
27176 				return;
27177 			} else {
27178 				goto nak;
27179 			}
27180 		}
27181 
27182 		/* IOCTL continuation following copyin or copyout. */
27183 		if (mi_copy_state(q, mp, NULL) == -1) {
27184 			/*
27185 			 * The copy operation failed.  mi_copy_state already
27186 			 * cleaned up, so we're out of here.
27187 			 */
27188 			return;
27189 		}
27190 		/*
27191 		 * If we just completed a copy in, we become writer and
27192 		 * continue processing in ip_sioctl_copyin_done.  If it
27193 		 * was a copy out, we call mi_copyout again.  If there is
27194 		 * nothing more to copy out, it will complete the IOCTL.
27195 		 */
27196 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27197 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27198 				mi_copy_done(q, mp, EPROTO);
27199 				return;
27200 			}
27201 			/*
27202 			 * Check for cases that need more copying.  A return
27203 			 * value of 0 means a second copyin has been started,
27204 			 * so we return; a return value of 1 means no more
27205 			 * copying is needed, so we continue.
27206 			 */
27207 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27208 			    MI_COPY_COUNT(mp) == 1) {
27209 				if (ip_copyin_msfilter(q, mp) == 0)
27210 					return;
27211 			}
27212 			/*
27213 			 * Refhold the conn, till the ioctl completes. This is
27214 			 * needed in case the ioctl ends up in the pending mp
27215 			 * list. Every mp in the ill_pending_mp list and
27216 			 * the ipx_pending_mp must have a refhold on the conn
27217 			 * to resume processing. The refhold is released when
27218 			 * the ioctl completes. (normally or abnormally)
27219 			 * In all cases ip_ioctl_finish is called to finish
27220 			 * the ioctl.
27221 			 */
27222 			if (connp != NULL) {
27223 				/* This is not a reentry */
27224 				ASSERT(ipsq == NULL);
27225 				CONN_INC_REF(connp);
27226 			} else {
27227 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27228 					mi_copy_done(q, mp, EINVAL);
27229 					return;
27230 				}
27231 			}
27232 
27233 			ip_process_ioctl(ipsq, q, mp, ipip);
27234 
27235 		} else {
27236 			mi_copyout(q, mp);
27237 		}
27238 		return;
27239 nak:
27240 		iocp->ioc_error = EINVAL;
27241 		mp->b_datap->db_type = M_IOCNAK;
27242 		iocp->ioc_count = 0;
27243 		qreply(q, mp);
27244 		return;
27245 
27246 	case M_IOCNAK:
27247 		/*
27248 		 * The only way we could get here is if a resolver didn't like
27249 		 * an IOCTL we sent it.	 This shouldn't happen.
27250 		 */
27251 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27252 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27253 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27254 		freemsg(mp);
27255 		return;
27256 	case M_IOCACK:
27257 		/* /dev/ip shouldn't see this */
27258 		if (CONN_Q(q))
27259 			goto nak;
27260 
27261 		/*
27262 		 * Finish socket ioctls passed through to ARP.  We use the
27263 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27264 		 * we need to become writer before calling ip_sioctl_iocack().
27265 		 * Note that qwriter_ip() will release the refhold, and that a
27266 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27267 		 * ill stream.
27268 		 */
27269 		iocp = (struct iocblk *)mp->b_rptr;
27270 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27271 			ip_sioctl_iocack(NULL, q, mp, NULL);
27272 			return;
27273 		}
27274 
27275 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27276 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27277 		ill = q->q_ptr;
27278 		ill_refhold(ill);
27279 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27280 		return;
27281 	case M_FLUSH:
27282 		if (*mp->b_rptr & FLUSHW)
27283 			flushq(q, FLUSHALL);
27284 		if (q->q_next) {
27285 			putnext(q, mp);
27286 			return;
27287 		}
27288 		if (*mp->b_rptr & FLUSHR) {
27289 			*mp->b_rptr &= ~FLUSHW;
27290 			qreply(q, mp);
27291 			return;
27292 		}
27293 		freemsg(mp);
27294 		return;
27295 	case IRE_DB_REQ_TYPE:
27296 		if (connp == NULL) {
27297 			proto_str = "IRE_DB_REQ_TYPE";
27298 			goto protonak;
27299 		}
27300 		/* An Upper Level Protocol wants a copy of an IRE. */
27301 		ip_ire_req(q, mp);
27302 		return;
27303 	case M_CTL:
27304 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27305 			break;
27306 
27307 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27308 		    TUN_HELLO) {
27309 			ASSERT(connp != NULL);
27310 			connp->conn_flags |= IPCL_IPTUN;
27311 			freeb(mp);
27312 			return;
27313 		}
27314 
27315 		/* M_CTL messages are used by ARP to tell us things. */
27316 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27317 			break;
27318 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27319 		case AR_ENTRY_SQUERY:
27320 			putnext(q, mp);
27321 			return;
27322 		case AR_CLIENT_NOTIFY:
27323 			ip_arp_news(q, mp);
27324 			return;
27325 		case AR_DLPIOP_DONE:
27326 			ASSERT(q->q_next != NULL);
27327 			ill = (ill_t *)q->q_ptr;
27328 			/* qwriter_ip releases the refhold */
27329 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27330 			ill_refhold(ill);
27331 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27332 			return;
27333 		case AR_ARP_CLOSING:
27334 			/*
27335 			 * ARP (above us) is closing. If no ARP bringup is
27336 			 * currently pending, ack the message so that ARP
27337 			 * can complete its close. Also mark ill_arp_closing
27338 			 * so that new ARP bringups will fail. If any
27339 			 * ARP bringup is currently in progress, we will
27340 			 * ack this when the current ARP bringup completes.
27341 			 */
27342 			ASSERT(q->q_next != NULL);
27343 			ill = (ill_t *)q->q_ptr;
27344 			mutex_enter(&ill->ill_lock);
27345 			ill->ill_arp_closing = 1;
27346 			if (!ill->ill_arp_bringup_pending) {
27347 				mutex_exit(&ill->ill_lock);
27348 				qreply(q, mp);
27349 			} else {
27350 				mutex_exit(&ill->ill_lock);
27351 				freemsg(mp);
27352 			}
27353 			return;
27354 		case AR_ARP_EXTEND:
27355 			/*
27356 			 * The ARP module above us is capable of duplicate
27357 			 * address detection.  Old ATM drivers will not send
27358 			 * this message.
27359 			 */
27360 			ASSERT(q->q_next != NULL);
27361 			ill = (ill_t *)q->q_ptr;
27362 			ill->ill_arp_extend = B_TRUE;
27363 			freemsg(mp);
27364 			return;
27365 		default:
27366 			break;
27367 		}
27368 		break;
27369 	case M_PROTO:
27370 	case M_PCPROTO:
27371 		/*
27372 		 * The only PROTO messages we expect are copies of option
27373 		 * negotiation acknowledgements, AH and ESP bind requests
27374 		 * are also expected.
27375 		 */
27376 		switch (((union T_primitives *)mp->b_rptr)->type) {
27377 		case O_T_BIND_REQ:
27378 		case T_BIND_REQ: {
27379 			/* Request can get queued in bind */
27380 			if (connp == NULL) {
27381 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27382 				goto protonak;
27383 			}
27384 			/*
27385 			 * The transports except SCTP call ip_bind_{v4,v6}()
27386 			 * directly instead of a a putnext. SCTP doesn't
27387 			 * generate any T_BIND_REQ since it has its own
27388 			 * fanout data structures. However, ESP and AH
27389 			 * come in for regular binds; all other cases are
27390 			 * bind retries.
27391 			 */
27392 			ASSERT(!IPCL_IS_SCTP(connp));
27393 
27394 			/* Don't increment refcnt if this is a re-entry */
27395 			if (ipsq == NULL)
27396 				CONN_INC_REF(connp);
27397 
27398 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27399 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27400 			ASSERT(mp != NULL);
27401 
27402 			ASSERT(!IPCL_IS_TCP(connp));
27403 			ASSERT(!IPCL_IS_UDP(connp));
27404 			ASSERT(!IPCL_IS_RAWIP(connp));
27405 
27406 			/* The case of AH and ESP */
27407 			qreply(q, mp);
27408 			CONN_OPER_PENDING_DONE(connp);
27409 			return;
27410 		}
27411 		case T_SVR4_OPTMGMT_REQ:
27412 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27413 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27414 
27415 			if (connp == NULL) {
27416 				proto_str = "T_SVR4_OPTMGMT_REQ";
27417 				goto protonak;
27418 			}
27419 
27420 			/*
27421 			 * All Solaris components should pass a db_credp
27422 			 * for this TPI message, hence we ASSERT.
27423 			 * But in case there is some other M_PROTO that looks
27424 			 * like a TPI message sent by some other kernel
27425 			 * component, we check and return an error.
27426 			 */
27427 			cr = msg_getcred(mp, NULL);
27428 			ASSERT(cr != NULL);
27429 			if (cr == NULL) {
27430 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27431 				if (mp != NULL)
27432 					qreply(q, mp);
27433 				return;
27434 			}
27435 
27436 			if (!snmpcom_req(q, mp, ip_snmp_set,
27437 			    ip_snmp_get, cr)) {
27438 				/*
27439 				 * Call svr4_optcom_req so that it can
27440 				 * generate the ack. We don't come here
27441 				 * if this operation is being restarted.
27442 				 * ip_restart_optmgmt will drop the conn ref.
27443 				 * In the case of ipsec option after the ipsec
27444 				 * load is complete conn_restart_ipsec_waiter
27445 				 * drops the conn ref.
27446 				 */
27447 				ASSERT(ipsq == NULL);
27448 				CONN_INC_REF(connp);
27449 				if (ip_check_for_ipsec_opt(q, mp))
27450 					return;
27451 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27452 				    B_FALSE);
27453 				if (err != EINPROGRESS) {
27454 					/* Operation is done */
27455 					CONN_OPER_PENDING_DONE(connp);
27456 				}
27457 			}
27458 			return;
27459 		case T_OPTMGMT_REQ:
27460 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27461 			/*
27462 			 * Note: No snmpcom_req support through new
27463 			 * T_OPTMGMT_REQ.
27464 			 * Call tpi_optcom_req so that it can
27465 			 * generate the ack.
27466 			 */
27467 			if (connp == NULL) {
27468 				proto_str = "T_OPTMGMT_REQ";
27469 				goto protonak;
27470 			}
27471 
27472 			/*
27473 			 * All Solaris components should pass a db_credp
27474 			 * for this TPI message, hence we ASSERT.
27475 			 * But in case there is some other M_PROTO that looks
27476 			 * like a TPI message sent by some other kernel
27477 			 * component, we check and return an error.
27478 			 */
27479 			cr = msg_getcred(mp, NULL);
27480 			ASSERT(cr != NULL);
27481 			if (cr == NULL) {
27482 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27483 				if (mp != NULL)
27484 					qreply(q, mp);
27485 				return;
27486 			}
27487 			ASSERT(ipsq == NULL);
27488 			/*
27489 			 * We don't come here for restart. ip_restart_optmgmt
27490 			 * will drop the conn ref. In the case of ipsec option
27491 			 * after the ipsec load is complete
27492 			 * conn_restart_ipsec_waiter drops the conn ref.
27493 			 */
27494 			CONN_INC_REF(connp);
27495 			if (ip_check_for_ipsec_opt(q, mp))
27496 				return;
27497 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27498 			if (err != EINPROGRESS) {
27499 				/* Operation is done */
27500 				CONN_OPER_PENDING_DONE(connp);
27501 			}
27502 			return;
27503 		case T_UNBIND_REQ:
27504 			if (connp == NULL) {
27505 				proto_str = "T_UNBIND_REQ";
27506 				goto protonak;
27507 			}
27508 			ip_unbind(Q_TO_CONN(q));
27509 			mp = mi_tpi_ok_ack_alloc(mp);
27510 			qreply(q, mp);
27511 			return;
27512 		default:
27513 			/*
27514 			 * Have to drop any DLPI messages coming down from
27515 			 * arp (such as an info_req which would cause ip
27516 			 * to receive an extra info_ack if it was passed
27517 			 * through.
27518 			 */
27519 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27520 			    (int)*(uint_t *)mp->b_rptr));
27521 			freemsg(mp);
27522 			return;
27523 		}
27524 		/* NOTREACHED */
27525 	case IRE_DB_TYPE: {
27526 		nce_t		*nce;
27527 		ill_t		*ill;
27528 		in6_addr_t	gw_addr_v6;
27529 
27530 		/*
27531 		 * This is a response back from a resolver.  It
27532 		 * consists of a message chain containing:
27533 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27534 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27535 		 * The LL_HDR_MBLK is the DLPI header to use to get
27536 		 * the attached packet, and subsequent ones for the
27537 		 * same destination, transmitted.
27538 		 */
27539 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27540 			break;
27541 		/*
27542 		 * First, check to make sure the resolution succeeded.
27543 		 * If it failed, the second mblk will be empty.
27544 		 * If it is, free the chain, dropping the packet.
27545 		 * (We must ire_delete the ire; that frees the ire mblk)
27546 		 * We're doing this now to support PVCs for ATM; it's
27547 		 * a partial xresolv implementation. When we fully implement
27548 		 * xresolv interfaces, instead of freeing everything here
27549 		 * we'll initiate neighbor discovery.
27550 		 *
27551 		 * For v4 (ARP and other external resolvers) the resolver
27552 		 * frees the message, so no check is needed. This check
27553 		 * is required, though, for a full xresolve implementation.
27554 		 * Including this code here now both shows how external
27555 		 * resolvers can NACK a resolution request using an
27556 		 * existing design that has no specific provisions for NACKs,
27557 		 * and also takes into account that the current non-ARP
27558 		 * external resolver has been coded to use this method of
27559 		 * NACKing for all IPv6 (xresolv) cases,
27560 		 * whether our xresolv implementation is complete or not.
27561 		 *
27562 		 */
27563 		ire = (ire_t *)mp->b_rptr;
27564 		ill = ire_to_ill(ire);
27565 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27566 		if (mp1->b_rptr == mp1->b_wptr) {
27567 			if (ire->ire_ipversion == IPV6_VERSION) {
27568 				/*
27569 				 * XRESOLV interface.
27570 				 */
27571 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27572 				mutex_enter(&ire->ire_lock);
27573 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27574 				mutex_exit(&ire->ire_lock);
27575 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27576 					nce = ndp_lookup_v6(ill, B_FALSE,
27577 					    &ire->ire_addr_v6, B_FALSE);
27578 				} else {
27579 					nce = ndp_lookup_v6(ill, B_FALSE,
27580 					    &gw_addr_v6, B_FALSE);
27581 				}
27582 				if (nce != NULL) {
27583 					nce_resolv_failed(nce);
27584 					ndp_delete(nce);
27585 					NCE_REFRELE(nce);
27586 				}
27587 			}
27588 			mp->b_cont = NULL;
27589 			freemsg(mp1);		/* frees the pkt as well */
27590 			ASSERT(ire->ire_nce == NULL);
27591 			ire_delete((ire_t *)mp->b_rptr);
27592 			return;
27593 		}
27594 
27595 		/*
27596 		 * Split them into IRE_MBLK and pkt and feed it into
27597 		 * ire_add_then_send. Then in ire_add_then_send
27598 		 * the IRE will be added, and then the packet will be
27599 		 * run back through ip_wput. This time it will make
27600 		 * it to the wire.
27601 		 */
27602 		mp->b_cont = NULL;
27603 		mp = mp1->b_cont;		/* now, mp points to pkt */
27604 		mp1->b_cont = NULL;
27605 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27606 		if (ire->ire_ipversion == IPV6_VERSION) {
27607 			/*
27608 			 * XRESOLV interface. Find the nce and put a copy
27609 			 * of the dl_unitdata_req in nce_res_mp
27610 			 */
27611 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27612 			mutex_enter(&ire->ire_lock);
27613 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27614 			mutex_exit(&ire->ire_lock);
27615 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27616 				nce = ndp_lookup_v6(ill, B_FALSE,
27617 				    &ire->ire_addr_v6, B_FALSE);
27618 			} else {
27619 				nce = ndp_lookup_v6(ill, B_FALSE,
27620 				    &gw_addr_v6, B_FALSE);
27621 			}
27622 			if (nce != NULL) {
27623 				/*
27624 				 * We have to protect nce_res_mp here
27625 				 * from being accessed by other threads
27626 				 * while we change the mblk pointer.
27627 				 * Other functions will also lock the nce when
27628 				 * accessing nce_res_mp.
27629 				 *
27630 				 * The reason we change the mblk pointer
27631 				 * here rather than copying the resolved address
27632 				 * into the template is that, unlike with
27633 				 * ethernet, we have no guarantee that the
27634 				 * resolved address length will be
27635 				 * smaller than or equal to the lla length
27636 				 * with which the template was allocated,
27637 				 * (for ethernet, they're equal)
27638 				 * so we have to use the actual resolved
27639 				 * address mblk - which holds the real
27640 				 * dl_unitdata_req with the resolved address.
27641 				 *
27642 				 * Doing this is the same behavior as was
27643 				 * previously used in the v4 ARP case.
27644 				 */
27645 				mutex_enter(&nce->nce_lock);
27646 				if (nce->nce_res_mp != NULL)
27647 					freemsg(nce->nce_res_mp);
27648 				nce->nce_res_mp = mp1;
27649 				mutex_exit(&nce->nce_lock);
27650 				/*
27651 				 * We do a fastpath probe here because
27652 				 * we have resolved the address without
27653 				 * using Neighbor Discovery.
27654 				 * In the non-XRESOLV v6 case, the fastpath
27655 				 * probe is done right after neighbor
27656 				 * discovery completes.
27657 				 */
27658 				if (nce->nce_res_mp != NULL) {
27659 					int res;
27660 					nce_fastpath_list_add(nce);
27661 					res = ill_fastpath_probe(ill,
27662 					    nce->nce_res_mp);
27663 					if (res != 0 && res != EAGAIN)
27664 						nce_fastpath_list_delete(nce);
27665 				}
27666 
27667 				ire_add_then_send(q, ire, mp);
27668 				/*
27669 				 * Now we have to clean out any packets
27670 				 * that may have been queued on the nce
27671 				 * while it was waiting for address resolution
27672 				 * to complete.
27673 				 */
27674 				mutex_enter(&nce->nce_lock);
27675 				mp1 = nce->nce_qd_mp;
27676 				nce->nce_qd_mp = NULL;
27677 				mutex_exit(&nce->nce_lock);
27678 				while (mp1 != NULL) {
27679 					mblk_t *nxt_mp;
27680 					queue_t *fwdq = NULL;
27681 					ill_t   *inbound_ill;
27682 					uint_t ifindex;
27683 
27684 					nxt_mp = mp1->b_next;
27685 					mp1->b_next = NULL;
27686 					/*
27687 					 * Retrieve ifindex stored in
27688 					 * ip_rput_data_v6()
27689 					 */
27690 					ifindex =
27691 					    (uint_t)(uintptr_t)mp1->b_prev;
27692 					inbound_ill =
27693 					    ill_lookup_on_ifindex(ifindex,
27694 					    B_TRUE, NULL, NULL, NULL,
27695 					    NULL, ipst);
27696 					mp1->b_prev = NULL;
27697 					if (inbound_ill != NULL)
27698 						fwdq = inbound_ill->ill_rq;
27699 
27700 					if (fwdq != NULL) {
27701 						put(fwdq, mp1);
27702 						ill_refrele(inbound_ill);
27703 					} else
27704 						put(WR(ill->ill_rq), mp1);
27705 					mp1 = nxt_mp;
27706 				}
27707 				NCE_REFRELE(nce);
27708 			} else {	/* nce is NULL; clean up */
27709 				ire_delete(ire);
27710 				freemsg(mp);
27711 				freemsg(mp1);
27712 				return;
27713 			}
27714 		} else {
27715 			nce_t *arpce;
27716 			/*
27717 			 * Link layer resolution succeeded. Recompute the
27718 			 * ire_nce.
27719 			 */
27720 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27721 			if ((arpce = ndp_lookup_v4(ill,
27722 			    (ire->ire_gateway_addr != INADDR_ANY ?
27723 			    &ire->ire_gateway_addr : &ire->ire_addr),
27724 			    B_FALSE)) == NULL) {
27725 				freeb(ire->ire_mp);
27726 				freeb(mp1);
27727 				freemsg(mp);
27728 				return;
27729 			}
27730 			mutex_enter(&arpce->nce_lock);
27731 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27732 			if (arpce->nce_state == ND_REACHABLE) {
27733 				/*
27734 				 * Someone resolved this before us;
27735 				 * cleanup the res_mp. Since ire has
27736 				 * not been added yet, the call to ire_add_v4
27737 				 * from ire_add_then_send (when a dup is
27738 				 * detected) will clean up the ire.
27739 				 */
27740 				freeb(mp1);
27741 			} else {
27742 				ASSERT(arpce->nce_res_mp == NULL);
27743 				arpce->nce_res_mp = mp1;
27744 				arpce->nce_state = ND_REACHABLE;
27745 			}
27746 			mutex_exit(&arpce->nce_lock);
27747 			if (ire->ire_marks & IRE_MARK_NOADD) {
27748 				/*
27749 				 * this ire will not be added to the ire
27750 				 * cache table, so we can set the ire_nce
27751 				 * here, as there are no atomicity constraints.
27752 				 */
27753 				ire->ire_nce = arpce;
27754 				/*
27755 				 * We are associating this nce with the ire
27756 				 * so change the nce ref taken in
27757 				 * ndp_lookup_v4() from
27758 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27759 				 */
27760 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27761 			} else {
27762 				NCE_REFRELE(arpce);
27763 			}
27764 			ire_add_then_send(q, ire, mp);
27765 		}
27766 		return;	/* All is well, the packet has been sent. */
27767 	}
27768 	case IRE_ARPRESOLVE_TYPE: {
27769 
27770 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27771 			break;
27772 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27773 		mp->b_cont = NULL;
27774 		/*
27775 		 * First, check to make sure the resolution succeeded.
27776 		 * If it failed, the second mblk will be empty.
27777 		 */
27778 		if (mp1->b_rptr == mp1->b_wptr) {
27779 			/* cleanup  the incomplete ire, free queued packets */
27780 			freemsg(mp); /* fake ire */
27781 			freeb(mp1);  /* dl_unitdata response */
27782 			return;
27783 		}
27784 
27785 		/*
27786 		 * Update any incomplete nce_t found. We search the ctable
27787 		 * and find the nce from the ire->ire_nce because we need
27788 		 * to pass the ire to ip_xmit_v4 later, and can find both
27789 		 * ire and nce in one lookup.
27790 		 */
27791 		fake_ire = (ire_t *)mp->b_rptr;
27792 
27793 		/*
27794 		 * By the time we come back here from ARP the logical outgoing
27795 		 * interface of the incomplete ire we added in ire_forward()
27796 		 * could have disappeared, causing the incomplete ire to also
27797 		 * disappear.  So we need to retreive the proper ipif for the
27798 		 * ire before looking in ctable.  In the case of IPMP, the
27799 		 * ipif may be on the IPMP ill, so look it up based on the
27800 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27801 		 * Then, we can verify that ire_ipif_seqid still exists.
27802 		 */
27803 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27804 		    NULL, NULL, NULL, NULL, ipst);
27805 		if (ill == NULL) {
27806 			ip1dbg(("ill for incomplete ire vanished\n"));
27807 			freemsg(mp); /* fake ire */
27808 			freeb(mp1);  /* dl_unitdata response */
27809 			return;
27810 		}
27811 
27812 		/* Get the outgoing ipif */
27813 		mutex_enter(&ill->ill_lock);
27814 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27815 		if (ipif == NULL) {
27816 			mutex_exit(&ill->ill_lock);
27817 			ill_refrele(ill);
27818 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27819 			freemsg(mp); /* fake_ire */
27820 			freeb(mp1);  /* dl_unitdata response */
27821 			return;
27822 		}
27823 
27824 		ipif_refhold_locked(ipif);
27825 		mutex_exit(&ill->ill_lock);
27826 		ill_refrele(ill);
27827 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27828 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27829 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27830 		ipif_refrele(ipif);
27831 		if (ire == NULL) {
27832 			/*
27833 			 * no ire was found; check if there is an nce
27834 			 * for this lookup; if it has no ire's pointing at it
27835 			 * cleanup.
27836 			 */
27837 			if ((nce = ndp_lookup_v4(q->q_ptr,
27838 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27839 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27840 			    B_FALSE)) != NULL) {
27841 				/*
27842 				 * cleanup:
27843 				 * We check for refcnt 2 (one for the nce
27844 				 * hash list + 1 for the ref taken by
27845 				 * ndp_lookup_v4) to check that there are
27846 				 * no ire's pointing at the nce.
27847 				 */
27848 				if (nce->nce_refcnt == 2)
27849 					ndp_delete(nce);
27850 				NCE_REFRELE(nce);
27851 			}
27852 			freeb(mp1);  /* dl_unitdata response */
27853 			freemsg(mp); /* fake ire */
27854 			return;
27855 		}
27856 
27857 		nce = ire->ire_nce;
27858 		DTRACE_PROBE2(ire__arpresolve__type,
27859 		    ire_t *, ire, nce_t *, nce);
27860 		mutex_enter(&nce->nce_lock);
27861 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27862 		if (nce->nce_state == ND_REACHABLE) {
27863 			/*
27864 			 * Someone resolved this before us;
27865 			 * our response is not needed any more.
27866 			 */
27867 			mutex_exit(&nce->nce_lock);
27868 			freeb(mp1);  /* dl_unitdata response */
27869 		} else {
27870 			ASSERT(nce->nce_res_mp == NULL);
27871 			nce->nce_res_mp = mp1;
27872 			nce->nce_state = ND_REACHABLE;
27873 			mutex_exit(&nce->nce_lock);
27874 			nce_fastpath(nce);
27875 		}
27876 		/*
27877 		 * The cached nce_t has been updated to be reachable;
27878 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27879 		 */
27880 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27881 		freemsg(mp);
27882 		/*
27883 		 * send out queued packets.
27884 		 */
27885 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27886 
27887 		IRE_REFRELE(ire);
27888 		return;
27889 	}
27890 	default:
27891 		break;
27892 	}
27893 	if (q->q_next) {
27894 		putnext(q, mp);
27895 	} else
27896 		freemsg(mp);
27897 	return;
27898 
27899 protonak:
27900 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27901 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27902 		qreply(q, mp);
27903 }
27904 
27905 /*
27906  * Process IP options in an outbound packet.  Modify the destination if there
27907  * is a source route option.
27908  * Returns non-zero if something fails in which case an ICMP error has been
27909  * sent and mp freed.
27910  */
27911 static int
27912 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27913     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27914 {
27915 	ipoptp_t	opts;
27916 	uchar_t		*opt;
27917 	uint8_t		optval;
27918 	uint8_t		optlen;
27919 	ipaddr_t	dst;
27920 	intptr_t	code = 0;
27921 	mblk_t		*mp;
27922 	ire_t		*ire = NULL;
27923 
27924 	ip2dbg(("ip_wput_options\n"));
27925 	mp = ipsec_mp;
27926 	if (mctl_present) {
27927 		mp = ipsec_mp->b_cont;
27928 	}
27929 
27930 	dst = ipha->ipha_dst;
27931 	for (optval = ipoptp_first(&opts, ipha);
27932 	    optval != IPOPT_EOL;
27933 	    optval = ipoptp_next(&opts)) {
27934 		opt = opts.ipoptp_cur;
27935 		optlen = opts.ipoptp_len;
27936 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27937 		    optval, optlen));
27938 		switch (optval) {
27939 			uint32_t off;
27940 		case IPOPT_SSRR:
27941 		case IPOPT_LSRR:
27942 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27943 				ip1dbg((
27944 				    "ip_wput_options: bad option offset\n"));
27945 				code = (char *)&opt[IPOPT_OLEN] -
27946 				    (char *)ipha;
27947 				goto param_prob;
27948 			}
27949 			off = opt[IPOPT_OFFSET];
27950 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27951 			    ntohl(dst)));
27952 			/*
27953 			 * For strict: verify that dst is directly
27954 			 * reachable.
27955 			 */
27956 			if (optval == IPOPT_SSRR) {
27957 				ire = ire_ftable_lookup(dst, 0, 0,
27958 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27959 				    msg_getlabel(mp),
27960 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27961 				if (ire == NULL) {
27962 					ip1dbg(("ip_wput_options: SSRR not"
27963 					    " directly reachable: 0x%x\n",
27964 					    ntohl(dst)));
27965 					goto bad_src_route;
27966 				}
27967 				ire_refrele(ire);
27968 			}
27969 			break;
27970 		case IPOPT_RR:
27971 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27972 				ip1dbg((
27973 				    "ip_wput_options: bad option offset\n"));
27974 				code = (char *)&opt[IPOPT_OLEN] -
27975 				    (char *)ipha;
27976 				goto param_prob;
27977 			}
27978 			break;
27979 		case IPOPT_TS:
27980 			/*
27981 			 * Verify that length >=5 and that there is either
27982 			 * room for another timestamp or that the overflow
27983 			 * counter is not maxed out.
27984 			 */
27985 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27986 			if (optlen < IPOPT_MINLEN_IT) {
27987 				goto param_prob;
27988 			}
27989 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27990 				ip1dbg((
27991 				    "ip_wput_options: bad option offset\n"));
27992 				code = (char *)&opt[IPOPT_OFFSET] -
27993 				    (char *)ipha;
27994 				goto param_prob;
27995 			}
27996 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27997 			case IPOPT_TS_TSONLY:
27998 				off = IPOPT_TS_TIMELEN;
27999 				break;
28000 			case IPOPT_TS_TSANDADDR:
28001 			case IPOPT_TS_PRESPEC:
28002 			case IPOPT_TS_PRESPEC_RFC791:
28003 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28004 				break;
28005 			default:
28006 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28007 				    (char *)ipha;
28008 				goto param_prob;
28009 			}
28010 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28011 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28012 				/*
28013 				 * No room and the overflow counter is 15
28014 				 * already.
28015 				 */
28016 				goto param_prob;
28017 			}
28018 			break;
28019 		}
28020 	}
28021 
28022 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28023 		return (0);
28024 
28025 	ip1dbg(("ip_wput_options: error processing IP options."));
28026 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28027 
28028 param_prob:
28029 	/*
28030 	 * Since ip_wput() isn't close to finished, we fill
28031 	 * in enough of the header for credible error reporting.
28032 	 */
28033 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28034 		/* Failed */
28035 		freemsg(ipsec_mp);
28036 		return (-1);
28037 	}
28038 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28039 	return (-1);
28040 
28041 bad_src_route:
28042 	/*
28043 	 * Since ip_wput() isn't close to finished, we fill
28044 	 * in enough of the header for credible error reporting.
28045 	 */
28046 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28047 		/* Failed */
28048 		freemsg(ipsec_mp);
28049 		return (-1);
28050 	}
28051 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28052 	return (-1);
28053 }
28054 
28055 /*
28056  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28057  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28058  * thru /etc/system.
28059  */
28060 #define	CONN_MAXDRAINCNT	64
28061 
28062 static void
28063 conn_drain_init(ip_stack_t *ipst)
28064 {
28065 	int i, j;
28066 	idl_tx_list_t *itl_tx;
28067 
28068 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28069 
28070 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28071 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28072 		/*
28073 		 * Default value of the number of drainers is the
28074 		 * number of cpus, subject to maximum of 8 drainers.
28075 		 */
28076 		if (boot_max_ncpus != -1)
28077 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28078 		else
28079 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28080 	}
28081 
28082 	ipst->ips_idl_tx_list =
28083 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28084 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28085 		itl_tx =  &ipst->ips_idl_tx_list[i];
28086 		itl_tx->txl_drain_list =
28087 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28088 		    sizeof (idl_t), KM_SLEEP);
28089 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28090 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28091 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28092 			    MUTEX_DEFAULT, NULL);
28093 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28094 		}
28095 	}
28096 }
28097 
28098 static void
28099 conn_drain_fini(ip_stack_t *ipst)
28100 {
28101 	int i;
28102 	idl_tx_list_t *itl_tx;
28103 
28104 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28105 		itl_tx =  &ipst->ips_idl_tx_list[i];
28106 		kmem_free(itl_tx->txl_drain_list,
28107 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28108 	}
28109 	kmem_free(ipst->ips_idl_tx_list,
28110 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28111 	ipst->ips_idl_tx_list = NULL;
28112 }
28113 
28114 /*
28115  * Note: For an overview of how flowcontrol is handled in IP please see the
28116  * IP Flowcontrol notes at the top of this file.
28117  *
28118  * Flow control has blocked us from proceeding. Insert the given conn in one
28119  * of the conn drain lists. These conn wq's will be qenabled later on when
28120  * STREAMS flow control does a backenable. conn_walk_drain will enable
28121  * the first conn in each of these drain lists. Each of these qenabled conns
28122  * in turn enables the next in the list, after it runs, or when it closes,
28123  * thus sustaining the drain process.
28124  */
28125 void
28126 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28127 {
28128 	idl_t	*idl = tx_list->txl_drain_list;
28129 	uint_t	index;
28130 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28131 
28132 	mutex_enter(&connp->conn_lock);
28133 	if (connp->conn_state_flags & CONN_CLOSING) {
28134 		/*
28135 		 * The conn is closing as a result of which CONN_CLOSING
28136 		 * is set. Return.
28137 		 */
28138 		mutex_exit(&connp->conn_lock);
28139 		return;
28140 	} else if (connp->conn_idl == NULL) {
28141 		/*
28142 		 * Assign the next drain list round robin. We dont' use
28143 		 * a lock, and thus it may not be strictly round robin.
28144 		 * Atomicity of load/stores is enough to make sure that
28145 		 * conn_drain_list_index is always within bounds.
28146 		 */
28147 		index = tx_list->txl_drain_index;
28148 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28149 		connp->conn_idl = &tx_list->txl_drain_list[index];
28150 		index++;
28151 		if (index == ipst->ips_conn_drain_list_cnt)
28152 			index = 0;
28153 		tx_list->txl_drain_index = index;
28154 	}
28155 	mutex_exit(&connp->conn_lock);
28156 
28157 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28158 	if ((connp->conn_drain_prev != NULL) ||
28159 	    (connp->conn_state_flags & CONN_CLOSING)) {
28160 		/*
28161 		 * The conn is already in the drain list, OR
28162 		 * the conn is closing. We need to check again for
28163 		 * the closing case again since close can happen
28164 		 * after we drop the conn_lock, and before we
28165 		 * acquire the CONN_DRAIN_LIST_LOCK.
28166 		 */
28167 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28168 		return;
28169 	} else {
28170 		idl = connp->conn_idl;
28171 	}
28172 
28173 	/*
28174 	 * The conn is not in the drain list. Insert it at the
28175 	 * tail of the drain list. The drain list is circular
28176 	 * and doubly linked. idl_conn points to the 1st element
28177 	 * in the list.
28178 	 */
28179 	if (idl->idl_conn == NULL) {
28180 		idl->idl_conn = connp;
28181 		connp->conn_drain_next = connp;
28182 		connp->conn_drain_prev = connp;
28183 	} else {
28184 		conn_t *head = idl->idl_conn;
28185 
28186 		connp->conn_drain_next = head;
28187 		connp->conn_drain_prev = head->conn_drain_prev;
28188 		head->conn_drain_prev->conn_drain_next = connp;
28189 		head->conn_drain_prev = connp;
28190 	}
28191 	/*
28192 	 * For non streams based sockets assert flow control.
28193 	 */
28194 	if (IPCL_IS_NONSTR(connp)) {
28195 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28196 		(*connp->conn_upcalls->su_txq_full)
28197 		    (connp->conn_upper_handle, B_TRUE);
28198 	} else {
28199 		conn_setqfull(connp);
28200 		noenable(connp->conn_wq);
28201 	}
28202 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28203 }
28204 
28205 /*
28206  * This conn is closing, and we are called from ip_close. OR
28207  * This conn has been serviced by ip_wsrv, and we need to do the tail
28208  * processing.
28209  * If this conn is part of the drain list, we may need to sustain the drain
28210  * process by qenabling the next conn in the drain list. We may also need to
28211  * remove this conn from the list, if it is done.
28212  */
28213 static void
28214 conn_drain_tail(conn_t *connp, boolean_t closing)
28215 {
28216 	idl_t *idl;
28217 
28218 	/*
28219 	 * connp->conn_idl is stable at this point, and no lock is needed
28220 	 * to check it. If we are called from ip_close, close has already
28221 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28222 	 * called us only because conn_idl is non-null. If we are called thru
28223 	 * service, conn_idl could be null, but it cannot change because
28224 	 * service is single-threaded per queue, and there cannot be another
28225 	 * instance of service trying to call conn_drain_insert on this conn
28226 	 * now.
28227 	 */
28228 	ASSERT(!closing || (connp->conn_idl != NULL));
28229 
28230 	/*
28231 	 * If connp->conn_idl is null, the conn has not been inserted into any
28232 	 * drain list even once since creation of the conn. Just return.
28233 	 */
28234 	if (connp->conn_idl == NULL)
28235 		return;
28236 
28237 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28238 
28239 	if (connp->conn_drain_prev == NULL) {
28240 		/* This conn is currently not in the drain list.  */
28241 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28242 		return;
28243 	}
28244 	idl = connp->conn_idl;
28245 	if (idl->idl_conn_draining == connp) {
28246 		/*
28247 		 * This conn is the current drainer. If this is the last conn
28248 		 * in the drain list, we need to do more checks, in the 'if'
28249 		 * below. Otherwwise we need to just qenable the next conn,
28250 		 * to sustain the draining, and is handled in the 'else'
28251 		 * below.
28252 		 */
28253 		if (connp->conn_drain_next == idl->idl_conn) {
28254 			/*
28255 			 * This conn is the last in this list. This round
28256 			 * of draining is complete. If idl_repeat is set,
28257 			 * it means another flow enabling has happened from
28258 			 * the driver/streams and we need to another round
28259 			 * of draining.
28260 			 * If there are more than 2 conns in the drain list,
28261 			 * do a left rotate by 1, so that all conns except the
28262 			 * conn at the head move towards the head by 1, and the
28263 			 * the conn at the head goes to the tail. This attempts
28264 			 * a more even share for all queues that are being
28265 			 * drained.
28266 			 */
28267 			if ((connp->conn_drain_next != connp) &&
28268 			    (idl->idl_conn->conn_drain_next != connp)) {
28269 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28270 			}
28271 			if (idl->idl_repeat) {
28272 				qenable(idl->idl_conn->conn_wq);
28273 				idl->idl_conn_draining = idl->idl_conn;
28274 				idl->idl_repeat = 0;
28275 			} else {
28276 				idl->idl_conn_draining = NULL;
28277 			}
28278 		} else {
28279 			/*
28280 			 * If the next queue that we are now qenable'ing,
28281 			 * is closing, it will remove itself from this list
28282 			 * and qenable the subsequent queue in ip_close().
28283 			 * Serialization is acheived thru idl_lock.
28284 			 */
28285 			qenable(connp->conn_drain_next->conn_wq);
28286 			idl->idl_conn_draining = connp->conn_drain_next;
28287 		}
28288 	}
28289 	if (!connp->conn_did_putbq || closing) {
28290 		/*
28291 		 * Remove ourself from the drain list, if we did not do
28292 		 * a putbq, or if the conn is closing.
28293 		 * Note: It is possible that q->q_first is non-null. It means
28294 		 * that these messages landed after we did a enableok() in
28295 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28296 		 * service them.
28297 		 */
28298 		if (connp->conn_drain_next == connp) {
28299 			/* Singleton in the list */
28300 			ASSERT(connp->conn_drain_prev == connp);
28301 			idl->idl_conn = NULL;
28302 			idl->idl_conn_draining = NULL;
28303 		} else {
28304 			connp->conn_drain_prev->conn_drain_next =
28305 			    connp->conn_drain_next;
28306 			connp->conn_drain_next->conn_drain_prev =
28307 			    connp->conn_drain_prev;
28308 			if (idl->idl_conn == connp)
28309 				idl->idl_conn = connp->conn_drain_next;
28310 			ASSERT(idl->idl_conn_draining != connp);
28311 
28312 		}
28313 		connp->conn_drain_next = NULL;
28314 		connp->conn_drain_prev = NULL;
28315 
28316 		/*
28317 		 * For non streams based sockets open up flow control.
28318 		 */
28319 		if (IPCL_IS_NONSTR(connp)) {
28320 			(*connp->conn_upcalls->su_txq_full)
28321 			    (connp->conn_upper_handle, B_FALSE);
28322 		} else {
28323 			conn_clrqfull(connp);
28324 			enableok(connp->conn_wq);
28325 		}
28326 	}
28327 
28328 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28329 }
28330 
28331 /*
28332  * Write service routine. Shared perimeter entry point.
28333  * ip_wsrv can be called in any of the following ways.
28334  * 1. The device queue's messages has fallen below the low water mark
28335  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28336  *    the drain lists and backenable the first conn in each list.
28337  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28338  *    qenabled non-tcp upper layers. We start dequeing messages and call
28339  *    ip_wput for each message.
28340  */
28341 
28342 void
28343 ip_wsrv(queue_t *q)
28344 {
28345 	conn_t	*connp;
28346 	ill_t	*ill;
28347 	mblk_t	*mp;
28348 
28349 	if (q->q_next) {
28350 		ill = (ill_t *)q->q_ptr;
28351 		if (ill->ill_state_flags == 0) {
28352 			ip_stack_t *ipst = ill->ill_ipst;
28353 
28354 			/*
28355 			 * The device flow control has opened up.
28356 			 * Walk through conn drain lists and qenable the
28357 			 * first conn in each list. This makes sense only
28358 			 * if the stream is fully plumbed and setup.
28359 			 * Hence the if check above.
28360 			 */
28361 			ip1dbg(("ip_wsrv: walking\n"));
28362 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28363 		}
28364 		return;
28365 	}
28366 
28367 	connp = Q_TO_CONN(q);
28368 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28369 
28370 	/*
28371 	 * 1. Set conn_draining flag to signal that service is active.
28372 	 *
28373 	 * 2. ip_output determines whether it has been called from service,
28374 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28375 	 *    has been called from service.
28376 	 *
28377 	 * 3. Message ordering is preserved by the following logic.
28378 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28379 	 *    the message at the tail, if conn_draining is set (i.e. service
28380 	 *    is running) or if q->q_first is non-null.
28381 	 *
28382 	 *    ii. If ip_output is called from service, and if ip_output cannot
28383 	 *    putnext due to flow control, it does a putbq.
28384 	 *
28385 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28386 	 *    (causing an infinite loop).
28387 	 */
28388 	ASSERT(!connp->conn_did_putbq);
28389 
28390 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28391 		connp->conn_draining = 1;
28392 		noenable(q);
28393 		while ((mp = getq(q)) != NULL) {
28394 			ASSERT(CONN_Q(q));
28395 
28396 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28397 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28398 			if (connp->conn_did_putbq) {
28399 				/* ip_wput did a putbq */
28400 				break;
28401 			}
28402 		}
28403 		/*
28404 		 * At this point, a thread coming down from top, calling
28405 		 * ip_wput, may end up queueing the message. We have not yet
28406 		 * enabled the queue, so ip_wsrv won't be called again.
28407 		 * To avoid this race, check q->q_first again (in the loop)
28408 		 * If the other thread queued the message before we call
28409 		 * enableok(), we will catch it in the q->q_first check.
28410 		 * If the other thread queues the message after we call
28411 		 * enableok(), ip_wsrv will be called again by STREAMS.
28412 		 */
28413 		connp->conn_draining = 0;
28414 		enableok(q);
28415 	}
28416 
28417 	/* Enable the next conn for draining */
28418 	conn_drain_tail(connp, B_FALSE);
28419 
28420 	/*
28421 	 * conn_direct_blocked is used to indicate blocked
28422 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28423 	 * This is the only place where it is set without
28424 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28425 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28426 	 */
28427 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28428 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28429 		connp->conn_direct_blocked = B_FALSE;
28430 	}
28431 
28432 	connp->conn_did_putbq = 0;
28433 }
28434 
28435 /*
28436  * Callback to disable flow control in IP.
28437  *
28438  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28439  * is enabled.
28440  *
28441  * When MAC_TX() is not able to send any more packets, dld sets its queue
28442  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28443  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28444  * function and wakes up corresponding mac worker threads, which in turn
28445  * calls this callback function, and disables flow control.
28446  */
28447 void
28448 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28449 {
28450 	ill_t *ill = (ill_t *)arg;
28451 	ip_stack_t *ipst = ill->ill_ipst;
28452 	idl_tx_list_t *idl_txl;
28453 
28454 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28455 	mutex_enter(&idl_txl->txl_lock);
28456 	/* add code to to set a flag to indicate idl_txl is enabled */
28457 	conn_walk_drain(ipst, idl_txl);
28458 	mutex_exit(&idl_txl->txl_lock);
28459 }
28460 
28461 /*
28462  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28463  * of conns that need to be drained, check if drain is already in progress.
28464  * If so set the idl_repeat bit, indicating that the last conn in the list
28465  * needs to reinitiate the drain once again, for the list. If drain is not
28466  * in progress for the list, initiate the draining, by qenabling the 1st
28467  * conn in the list. The drain is self-sustaining, each qenabled conn will
28468  * in turn qenable the next conn, when it is done/blocked/closing.
28469  */
28470 static void
28471 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28472 {
28473 	int i;
28474 	idl_t *idl;
28475 
28476 	IP_STAT(ipst, ip_conn_walk_drain);
28477 
28478 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28479 		idl = &tx_list->txl_drain_list[i];
28480 		mutex_enter(&idl->idl_lock);
28481 		if (idl->idl_conn == NULL) {
28482 			mutex_exit(&idl->idl_lock);
28483 			continue;
28484 		}
28485 		/*
28486 		 * If this list is not being drained currently by
28487 		 * an ip_wsrv thread, start the process.
28488 		 */
28489 		if (idl->idl_conn_draining == NULL) {
28490 			ASSERT(idl->idl_repeat == 0);
28491 			qenable(idl->idl_conn->conn_wq);
28492 			idl->idl_conn_draining = idl->idl_conn;
28493 		} else {
28494 			idl->idl_repeat = 1;
28495 		}
28496 		mutex_exit(&idl->idl_lock);
28497 	}
28498 }
28499 
28500 /*
28501  * Determine if the ill and multicast aspects of that packets
28502  * "matches" the conn.
28503  */
28504 boolean_t
28505 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28506     zoneid_t zoneid)
28507 {
28508 	ill_t *bound_ill;
28509 	boolean_t found;
28510 	ipif_t *ipif;
28511 	ire_t *ire;
28512 	ipaddr_t dst, src;
28513 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28514 
28515 	dst = ipha->ipha_dst;
28516 	src = ipha->ipha_src;
28517 
28518 	/*
28519 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28520 	 * unicast, broadcast and multicast reception to
28521 	 * conn_incoming_ill. conn_wantpacket itself is called
28522 	 * only for BROADCAST and multicast.
28523 	 */
28524 	bound_ill = connp->conn_incoming_ill;
28525 	if (bound_ill != NULL) {
28526 		if (IS_IPMP(bound_ill)) {
28527 			if (bound_ill->ill_grp != ill->ill_grp)
28528 				return (B_FALSE);
28529 		} else {
28530 			if (bound_ill != ill)
28531 				return (B_FALSE);
28532 		}
28533 	}
28534 
28535 	if (!CLASSD(dst)) {
28536 		if (IPCL_ZONE_MATCH(connp, zoneid))
28537 			return (B_TRUE);
28538 		/*
28539 		 * The conn is in a different zone; we need to check that this
28540 		 * broadcast address is configured in the application's zone.
28541 		 */
28542 		ipif = ipif_get_next_ipif(NULL, ill);
28543 		if (ipif == NULL)
28544 			return (B_FALSE);
28545 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28546 		    connp->conn_zoneid, NULL,
28547 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28548 		ipif_refrele(ipif);
28549 		if (ire != NULL) {
28550 			ire_refrele(ire);
28551 			return (B_TRUE);
28552 		} else {
28553 			return (B_FALSE);
28554 		}
28555 	}
28556 
28557 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28558 	    connp->conn_zoneid == zoneid) {
28559 		/*
28560 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28561 		 * disabled, therefore we don't dispatch the multicast packet to
28562 		 * the sending zone.
28563 		 */
28564 		return (B_FALSE);
28565 	}
28566 
28567 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28568 		/*
28569 		 * Multicast packet on the loopback interface: we only match
28570 		 * conns who joined the group in the specified zone.
28571 		 */
28572 		return (B_FALSE);
28573 	}
28574 
28575 	if (connp->conn_multi_router) {
28576 		/* multicast packet and multicast router socket: send up */
28577 		return (B_TRUE);
28578 	}
28579 
28580 	mutex_enter(&connp->conn_lock);
28581 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28582 	mutex_exit(&connp->conn_lock);
28583 	return (found);
28584 }
28585 
28586 static void
28587 conn_setqfull(conn_t *connp)
28588 {
28589 	queue_t *q = connp->conn_wq;
28590 
28591 	if (!(q->q_flag & QFULL)) {
28592 		mutex_enter(QLOCK(q));
28593 		if (!(q->q_flag & QFULL)) {
28594 			/* still need to set QFULL */
28595 			q->q_flag |= QFULL;
28596 			mutex_exit(QLOCK(q));
28597 		} else {
28598 			mutex_exit(QLOCK(q));
28599 		}
28600 	}
28601 }
28602 
28603 static void
28604 conn_clrqfull(conn_t *connp)
28605 {
28606 	queue_t *q = connp->conn_wq;
28607 
28608 	if (q->q_flag & QFULL) {
28609 		mutex_enter(QLOCK(q));
28610 		if (q->q_flag & QFULL) {
28611 			q->q_flag &= ~QFULL;
28612 			mutex_exit(QLOCK(q));
28613 			if (q->q_flag & QWANTW)
28614 				qbackenable(q, 0);
28615 		} else {
28616 			mutex_exit(QLOCK(q));
28617 		}
28618 	}
28619 }
28620 
28621 /*
28622  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28623  */
28624 /* ARGSUSED */
28625 static void
28626 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28627 {
28628 	ill_t *ill = (ill_t *)q->q_ptr;
28629 	mblk_t	*mp1, *mp2;
28630 	ipif_t  *ipif;
28631 	int err = 0;
28632 	conn_t *connp = NULL;
28633 	ipsq_t	*ipsq;
28634 	arc_t	*arc;
28635 
28636 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28637 
28638 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28639 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28640 
28641 	ASSERT(IAM_WRITER_ILL(ill));
28642 	mp2 = mp->b_cont;
28643 	mp->b_cont = NULL;
28644 
28645 	/*
28646 	 * We have now received the arp bringup completion message
28647 	 * from ARP. Mark the arp bringup as done. Also if the arp
28648 	 * stream has already started closing, send up the AR_ARP_CLOSING
28649 	 * ack now since ARP is waiting in close for this ack.
28650 	 */
28651 	mutex_enter(&ill->ill_lock);
28652 	ill->ill_arp_bringup_pending = 0;
28653 	if (ill->ill_arp_closing) {
28654 		mutex_exit(&ill->ill_lock);
28655 		/* Let's reuse the mp for sending the ack */
28656 		arc = (arc_t *)mp->b_rptr;
28657 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28658 		arc->arc_cmd = AR_ARP_CLOSING;
28659 		qreply(q, mp);
28660 	} else {
28661 		mutex_exit(&ill->ill_lock);
28662 		freeb(mp);
28663 	}
28664 
28665 	ipsq = ill->ill_phyint->phyint_ipsq;
28666 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28667 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28668 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28669 	if (mp1 == NULL) {
28670 		/* bringup was aborted by the user */
28671 		freemsg(mp2);
28672 		return;
28673 	}
28674 
28675 	/*
28676 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28677 	 * must have an associated conn_t.  Otherwise, we're bringing this
28678 	 * interface back up as part of handling an asynchronous event (e.g.,
28679 	 * physical address change).
28680 	 */
28681 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28682 		ASSERT(connp != NULL);
28683 		q = CONNP_TO_WQ(connp);
28684 	} else {
28685 		ASSERT(connp == NULL);
28686 		q = ill->ill_rq;
28687 	}
28688 
28689 	/*
28690 	 * If the DL_BIND_REQ fails, it is noted
28691 	 * in arc_name_offset.
28692 	 */
28693 	err = *((int *)mp2->b_rptr);
28694 	if (err == 0) {
28695 		if (ipif->ipif_isv6) {
28696 			if ((err = ipif_up_done_v6(ipif)) != 0)
28697 				ip0dbg(("ip_arp_done: init failed\n"));
28698 		} else {
28699 			if ((err = ipif_up_done(ipif)) != 0)
28700 				ip0dbg(("ip_arp_done: init failed\n"));
28701 		}
28702 	} else {
28703 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28704 	}
28705 
28706 	freemsg(mp2);
28707 
28708 	if ((err == 0) && (ill->ill_up_ipifs)) {
28709 		err = ill_up_ipifs(ill, q, mp1);
28710 		if (err == EINPROGRESS)
28711 			return;
28712 	}
28713 
28714 	/*
28715 	 * If we have a moved ipif to bring up, and everything has succeeded
28716 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28717 	 * down -- the admin can try to bring it up by hand if need be.
28718 	 */
28719 	if (ill->ill_move_ipif != NULL) {
28720 		ipif = ill->ill_move_ipif;
28721 		ill->ill_move_ipif = NULL;
28722 		if (err == 0) {
28723 			err = ipif_up(ipif, q, mp1);
28724 			if (err == EINPROGRESS)
28725 				return;
28726 		}
28727 	}
28728 
28729 	/*
28730 	 * The operation must complete without EINPROGRESS since
28731 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28732 	 * operation will be stuck forever in the ipsq.
28733 	 */
28734 	ASSERT(err != EINPROGRESS);
28735 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28736 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28737 	else
28738 		ipsq_current_finish(ipsq);
28739 }
28740 
28741 /* Allocate the private structure */
28742 static int
28743 ip_priv_alloc(void **bufp)
28744 {
28745 	void	*buf;
28746 
28747 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28748 		return (ENOMEM);
28749 
28750 	*bufp = buf;
28751 	return (0);
28752 }
28753 
28754 /* Function to delete the private structure */
28755 void
28756 ip_priv_free(void *buf)
28757 {
28758 	ASSERT(buf != NULL);
28759 	kmem_free(buf, sizeof (ip_priv_t));
28760 }
28761 
28762 /*
28763  * The entry point for IPPF processing.
28764  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28765  * routine just returns.
28766  *
28767  * When called, ip_process generates an ipp_packet_t structure
28768  * which holds the state information for this packet and invokes the
28769  * the classifier (via ipp_packet_process). The classification, depending on
28770  * configured filters, results in a list of actions for this packet. Invoking
28771  * an action may cause the packet to be dropped, in which case the resulting
28772  * mblk (*mpp) is NULL. proc indicates the callout position for
28773  * this packet and ill_index is the interface this packet on or will leave
28774  * on (inbound and outbound resp.).
28775  */
28776 void
28777 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28778 {
28779 	mblk_t		*mp;
28780 	ip_priv_t	*priv;
28781 	ipp_action_id_t	aid;
28782 	int		rc = 0;
28783 	ipp_packet_t	*pp;
28784 #define	IP_CLASS	"ip"
28785 
28786 	/* If the classifier is not loaded, return  */
28787 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28788 		return;
28789 	}
28790 
28791 	mp = *mpp;
28792 	ASSERT(mp != NULL);
28793 
28794 	/* Allocate the packet structure */
28795 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28796 	if (rc != 0) {
28797 		*mpp = NULL;
28798 		freemsg(mp);
28799 		return;
28800 	}
28801 
28802 	/* Allocate the private structure */
28803 	rc = ip_priv_alloc((void **)&priv);
28804 	if (rc != 0) {
28805 		*mpp = NULL;
28806 		freemsg(mp);
28807 		ipp_packet_free(pp);
28808 		return;
28809 	}
28810 	priv->proc = proc;
28811 	priv->ill_index = ill_index;
28812 	ipp_packet_set_private(pp, priv, ip_priv_free);
28813 	ipp_packet_set_data(pp, mp);
28814 
28815 	/* Invoke the classifier */
28816 	rc = ipp_packet_process(&pp);
28817 	if (pp != NULL) {
28818 		mp = ipp_packet_get_data(pp);
28819 		ipp_packet_free(pp);
28820 		if (rc != 0) {
28821 			freemsg(mp);
28822 			*mpp = NULL;
28823 		}
28824 	} else {
28825 		*mpp = NULL;
28826 	}
28827 #undef	IP_CLASS
28828 }
28829 
28830 /*
28831  * Propagate a multicast group membership operation (add/drop) on
28832  * all the interfaces crossed by the related multirt routes.
28833  * The call is considered successful if the operation succeeds
28834  * on at least one interface.
28835  */
28836 static int
28837 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28838     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28839     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28840     mblk_t *first_mp)
28841 {
28842 	ire_t		*ire_gw;
28843 	irb_t		*irb;
28844 	int		error = 0;
28845 	opt_restart_t	*or;
28846 	ip_stack_t	*ipst = ire->ire_ipst;
28847 
28848 	irb = ire->ire_bucket;
28849 	ASSERT(irb != NULL);
28850 
28851 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28852 
28853 	or = (opt_restart_t *)first_mp->b_rptr;
28854 	IRB_REFHOLD(irb);
28855 	for (; ire != NULL; ire = ire->ire_next) {
28856 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28857 			continue;
28858 		if (ire->ire_addr != group)
28859 			continue;
28860 
28861 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28862 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28863 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28864 		/* No resolver exists for the gateway; skip this ire. */
28865 		if (ire_gw == NULL)
28866 			continue;
28867 
28868 		/*
28869 		 * This function can return EINPROGRESS. If so the operation
28870 		 * will be restarted from ip_restart_optmgmt which will
28871 		 * call ip_opt_set and option processing will restart for
28872 		 * this option. So we may end up calling 'fn' more than once.
28873 		 * This requires that 'fn' is idempotent except for the
28874 		 * return value. The operation is considered a success if
28875 		 * it succeeds at least once on any one interface.
28876 		 */
28877 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28878 		    NULL, fmode, src, first_mp);
28879 		if (error == 0)
28880 			or->or_private = CGTP_MCAST_SUCCESS;
28881 
28882 		if (ip_debug > 0) {
28883 			ulong_t	off;
28884 			char	*ksym;
28885 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28886 			ip2dbg(("ip_multirt_apply_membership: "
28887 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28888 			    "error %d [success %u]\n",
28889 			    ksym ? ksym : "?",
28890 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28891 			    error, or->or_private));
28892 		}
28893 
28894 		ire_refrele(ire_gw);
28895 		if (error == EINPROGRESS) {
28896 			IRB_REFRELE(irb);
28897 			return (error);
28898 		}
28899 	}
28900 	IRB_REFRELE(irb);
28901 	/*
28902 	 * Consider the call as successful if we succeeded on at least
28903 	 * one interface. Otherwise, return the last encountered error.
28904 	 */
28905 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28906 }
28907 
28908 /*
28909  * Issue a warning regarding a route crossing an interface with an
28910  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28911  * amount of time is logged.
28912  */
28913 static void
28914 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28915 {
28916 	hrtime_t	current = gethrtime();
28917 	char		buf[INET_ADDRSTRLEN];
28918 	ip_stack_t	*ipst = ire->ire_ipst;
28919 
28920 	/* Convert interval in ms to hrtime in ns */
28921 	if (ipst->ips_multirt_bad_mtu_last_time +
28922 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28923 	    current) {
28924 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28925 		    "to %s, incorrect MTU %u (expected %u)\n",
28926 		    ip_dot_addr(ire->ire_addr, buf),
28927 		    ire->ire_max_frag, max_frag);
28928 
28929 		ipst->ips_multirt_bad_mtu_last_time = current;
28930 	}
28931 }
28932 
28933 /*
28934  * Get the CGTP (multirouting) filtering status.
28935  * If 0, the CGTP hooks are transparent.
28936  */
28937 /* ARGSUSED */
28938 static int
28939 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28940 {
28941 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28942 
28943 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28944 	return (0);
28945 }
28946 
28947 /*
28948  * Set the CGTP (multirouting) filtering status.
28949  * If the status is changed from active to transparent
28950  * or from transparent to active, forward the new status
28951  * to the filtering module (if loaded).
28952  */
28953 /* ARGSUSED */
28954 static int
28955 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28956     cred_t *ioc_cr)
28957 {
28958 	long		new_value;
28959 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28960 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28961 
28962 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28963 		return (EPERM);
28964 
28965 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28966 	    new_value < 0 || new_value > 1) {
28967 		return (EINVAL);
28968 	}
28969 
28970 	if ((!*ip_cgtp_filter_value) && new_value) {
28971 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28972 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28973 		    " (module not loaded)" : "");
28974 	}
28975 	if (*ip_cgtp_filter_value && (!new_value)) {
28976 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28977 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28978 		    " (module not loaded)" : "");
28979 	}
28980 
28981 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28982 		int	res;
28983 		netstackid_t stackid;
28984 
28985 		stackid = ipst->ips_netstack->netstack_stackid;
28986 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28987 		    new_value);
28988 		if (res)
28989 			return (res);
28990 	}
28991 
28992 	*ip_cgtp_filter_value = (boolean_t)new_value;
28993 
28994 	return (0);
28995 }
28996 
28997 /*
28998  * Return the expected CGTP hooks version number.
28999  */
29000 int
29001 ip_cgtp_filter_supported(void)
29002 {
29003 	return (ip_cgtp_filter_rev);
29004 }
29005 
29006 /*
29007  * CGTP hooks can be registered by invoking this function.
29008  * Checks that the version number matches.
29009  */
29010 int
29011 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29012 {
29013 	netstack_t *ns;
29014 	ip_stack_t *ipst;
29015 
29016 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29017 		return (ENOTSUP);
29018 
29019 	ns = netstack_find_by_stackid(stackid);
29020 	if (ns == NULL)
29021 		return (EINVAL);
29022 	ipst = ns->netstack_ip;
29023 	ASSERT(ipst != NULL);
29024 
29025 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29026 		netstack_rele(ns);
29027 		return (EALREADY);
29028 	}
29029 
29030 	ipst->ips_ip_cgtp_filter_ops = ops;
29031 	netstack_rele(ns);
29032 	return (0);
29033 }
29034 
29035 /*
29036  * CGTP hooks can be unregistered by invoking this function.
29037  * Returns ENXIO if there was no registration.
29038  * Returns EBUSY if the ndd variable has not been turned off.
29039  */
29040 int
29041 ip_cgtp_filter_unregister(netstackid_t stackid)
29042 {
29043 	netstack_t *ns;
29044 	ip_stack_t *ipst;
29045 
29046 	ns = netstack_find_by_stackid(stackid);
29047 	if (ns == NULL)
29048 		return (EINVAL);
29049 	ipst = ns->netstack_ip;
29050 	ASSERT(ipst != NULL);
29051 
29052 	if (ipst->ips_ip_cgtp_filter) {
29053 		netstack_rele(ns);
29054 		return (EBUSY);
29055 	}
29056 
29057 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29058 		netstack_rele(ns);
29059 		return (ENXIO);
29060 	}
29061 	ipst->ips_ip_cgtp_filter_ops = NULL;
29062 	netstack_rele(ns);
29063 	return (0);
29064 }
29065 
29066 /*
29067  * Check whether there is a CGTP filter registration.
29068  * Returns non-zero if there is a registration, otherwise returns zero.
29069  * Note: returns zero if bad stackid.
29070  */
29071 int
29072 ip_cgtp_filter_is_registered(netstackid_t stackid)
29073 {
29074 	netstack_t *ns;
29075 	ip_stack_t *ipst;
29076 	int ret;
29077 
29078 	ns = netstack_find_by_stackid(stackid);
29079 	if (ns == NULL)
29080 		return (0);
29081 	ipst = ns->netstack_ip;
29082 	ASSERT(ipst != NULL);
29083 
29084 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29085 		ret = 1;
29086 	else
29087 		ret = 0;
29088 
29089 	netstack_rele(ns);
29090 	return (ret);
29091 }
29092 
29093 static int
29094 ip_squeue_switch(int val)
29095 {
29096 	int rval = SQ_FILL;
29097 
29098 	switch (val) {
29099 	case IP_SQUEUE_ENTER_NODRAIN:
29100 		rval = SQ_NODRAIN;
29101 		break;
29102 	case IP_SQUEUE_ENTER:
29103 		rval = SQ_PROCESS;
29104 		break;
29105 	default:
29106 		break;
29107 	}
29108 	return (rval);
29109 }
29110 
29111 /* ARGSUSED */
29112 static int
29113 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29114     caddr_t addr, cred_t *cr)
29115 {
29116 	int *v = (int *)addr;
29117 	long new_value;
29118 
29119 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29120 		return (EPERM);
29121 
29122 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29123 		return (EINVAL);
29124 
29125 	ip_squeue_flag = ip_squeue_switch(new_value);
29126 	*v = new_value;
29127 	return (0);
29128 }
29129 
29130 /*
29131  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29132  * ip_debug.
29133  */
29134 /* ARGSUSED */
29135 static int
29136 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29137     caddr_t addr, cred_t *cr)
29138 {
29139 	int *v = (int *)addr;
29140 	long new_value;
29141 
29142 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29143 		return (EPERM);
29144 
29145 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29146 		return (EINVAL);
29147 
29148 	*v = new_value;
29149 	return (0);
29150 }
29151 
29152 static void *
29153 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29154 {
29155 	kstat_t *ksp;
29156 
29157 	ip_stat_t template = {
29158 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29159 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29160 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29161 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29162 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29163 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29164 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29165 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29166 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29167 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29168 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29169 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29170 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29171 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29172 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29173 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29174 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29175 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29176 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29177 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29178 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29179 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29180 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29181 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29182 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29183 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29184 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29185 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29186 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29187 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29188 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29189 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29190 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29191 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29192 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29193 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29194 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29195 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29196 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29197 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29198 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29199 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29200 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29201 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29202 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29203 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29204 	};
29205 
29206 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29207 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29208 	    KSTAT_FLAG_VIRTUAL, stackid);
29209 
29210 	if (ksp == NULL)
29211 		return (NULL);
29212 
29213 	bcopy(&template, ip_statisticsp, sizeof (template));
29214 	ksp->ks_data = (void *)ip_statisticsp;
29215 	ksp->ks_private = (void *)(uintptr_t)stackid;
29216 
29217 	kstat_install(ksp);
29218 	return (ksp);
29219 }
29220 
29221 static void
29222 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29223 {
29224 	if (ksp != NULL) {
29225 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29226 		kstat_delete_netstack(ksp, stackid);
29227 	}
29228 }
29229 
29230 static void *
29231 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29232 {
29233 	kstat_t	*ksp;
29234 
29235 	ip_named_kstat_t template = {
29236 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29237 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29238 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29239 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29240 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29241 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29242 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29243 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29244 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29245 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29246 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29247 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29248 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29249 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29250 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29251 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29252 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29253 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29254 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29255 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29256 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29257 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29258 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29259 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29260 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29261 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29262 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29263 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29264 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29265 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29266 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29267 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29268 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29269 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29270 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29271 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29272 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29273 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29274 	};
29275 
29276 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29277 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29278 	if (ksp == NULL || ksp->ks_data == NULL)
29279 		return (NULL);
29280 
29281 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29282 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29283 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29284 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29285 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29286 
29287 	template.netToMediaEntrySize.value.i32 =
29288 	    sizeof (mib2_ipNetToMediaEntry_t);
29289 
29290 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29291 
29292 	bcopy(&template, ksp->ks_data, sizeof (template));
29293 	ksp->ks_update = ip_kstat_update;
29294 	ksp->ks_private = (void *)(uintptr_t)stackid;
29295 
29296 	kstat_install(ksp);
29297 	return (ksp);
29298 }
29299 
29300 static void
29301 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29302 {
29303 	if (ksp != NULL) {
29304 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29305 		kstat_delete_netstack(ksp, stackid);
29306 	}
29307 }
29308 
29309 static int
29310 ip_kstat_update(kstat_t *kp, int rw)
29311 {
29312 	ip_named_kstat_t *ipkp;
29313 	mib2_ipIfStatsEntry_t ipmib;
29314 	ill_walk_context_t ctx;
29315 	ill_t *ill;
29316 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29317 	netstack_t	*ns;
29318 	ip_stack_t	*ipst;
29319 
29320 	if (kp == NULL || kp->ks_data == NULL)
29321 		return (EIO);
29322 
29323 	if (rw == KSTAT_WRITE)
29324 		return (EACCES);
29325 
29326 	ns = netstack_find_by_stackid(stackid);
29327 	if (ns == NULL)
29328 		return (-1);
29329 	ipst = ns->netstack_ip;
29330 	if (ipst == NULL) {
29331 		netstack_rele(ns);
29332 		return (-1);
29333 	}
29334 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29335 
29336 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29337 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29338 	ill = ILL_START_WALK_V4(&ctx, ipst);
29339 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29340 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29341 	rw_exit(&ipst->ips_ill_g_lock);
29342 
29343 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29344 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29345 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29346 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29347 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29348 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29349 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29350 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29351 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29352 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29353 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29354 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29355 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29356 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29357 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29358 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29359 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29360 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29361 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29362 
29363 	ipkp->routingDiscards.value.ui32 =	0;
29364 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29365 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29366 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29367 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29368 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29369 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29370 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29371 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29372 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29373 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29374 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29375 
29376 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29377 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29378 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29379 
29380 	netstack_rele(ns);
29381 
29382 	return (0);
29383 }
29384 
29385 static void *
29386 icmp_kstat_init(netstackid_t stackid)
29387 {
29388 	kstat_t	*ksp;
29389 
29390 	icmp_named_kstat_t template = {
29391 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29392 		{ "inErrors",		KSTAT_DATA_UINT32 },
29393 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29394 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29395 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29396 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29397 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29398 		{ "inEchos",		KSTAT_DATA_UINT32 },
29399 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29400 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29401 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29402 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29403 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29404 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29405 		{ "outErrors",		KSTAT_DATA_UINT32 },
29406 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29407 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29408 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29409 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29410 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29411 		{ "outEchos",		KSTAT_DATA_UINT32 },
29412 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29413 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29414 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29415 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29416 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29417 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29418 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29419 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29420 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29421 		{ "outDrops",		KSTAT_DATA_UINT32 },
29422 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29423 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29424 	};
29425 
29426 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29427 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29428 	if (ksp == NULL || ksp->ks_data == NULL)
29429 		return (NULL);
29430 
29431 	bcopy(&template, ksp->ks_data, sizeof (template));
29432 
29433 	ksp->ks_update = icmp_kstat_update;
29434 	ksp->ks_private = (void *)(uintptr_t)stackid;
29435 
29436 	kstat_install(ksp);
29437 	return (ksp);
29438 }
29439 
29440 static void
29441 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29442 {
29443 	if (ksp != NULL) {
29444 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29445 		kstat_delete_netstack(ksp, stackid);
29446 	}
29447 }
29448 
29449 static int
29450 icmp_kstat_update(kstat_t *kp, int rw)
29451 {
29452 	icmp_named_kstat_t *icmpkp;
29453 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29454 	netstack_t	*ns;
29455 	ip_stack_t	*ipst;
29456 
29457 	if ((kp == NULL) || (kp->ks_data == NULL))
29458 		return (EIO);
29459 
29460 	if (rw == KSTAT_WRITE)
29461 		return (EACCES);
29462 
29463 	ns = netstack_find_by_stackid(stackid);
29464 	if (ns == NULL)
29465 		return (-1);
29466 	ipst = ns->netstack_ip;
29467 	if (ipst == NULL) {
29468 		netstack_rele(ns);
29469 		return (-1);
29470 	}
29471 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29472 
29473 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29474 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29475 	icmpkp->inDestUnreachs.value.ui32 =
29476 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29477 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29478 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29479 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29480 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29481 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29482 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29483 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29484 	icmpkp->inTimestampReps.value.ui32 =
29485 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29486 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29487 	icmpkp->inAddrMaskReps.value.ui32 =
29488 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29489 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29490 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29491 	icmpkp->outDestUnreachs.value.ui32 =
29492 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29493 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29494 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29495 	icmpkp->outSrcQuenchs.value.ui32 =
29496 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29497 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29498 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29499 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29500 	icmpkp->outTimestamps.value.ui32 =
29501 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29502 	icmpkp->outTimestampReps.value.ui32 =
29503 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29504 	icmpkp->outAddrMasks.value.ui32 =
29505 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29506 	icmpkp->outAddrMaskReps.value.ui32 =
29507 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29508 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29509 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29510 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29511 	icmpkp->outFragNeeded.value.ui32 =
29512 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29513 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29514 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29515 	icmpkp->inBadRedirects.value.ui32 =
29516 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29517 
29518 	netstack_rele(ns);
29519 	return (0);
29520 }
29521 
29522 /*
29523  * This is the fanout function for raw socket opened for SCTP.  Note
29524  * that it is called after SCTP checks that there is no socket which
29525  * wants a packet.  Then before SCTP handles this out of the blue packet,
29526  * this function is called to see if there is any raw socket for SCTP.
29527  * If there is and it is bound to the correct address, the packet will
29528  * be sent to that socket.  Note that only one raw socket can be bound to
29529  * a port.  This is assured in ipcl_sctp_hash_insert();
29530  */
29531 void
29532 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29533     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29534     zoneid_t zoneid)
29535 {
29536 	conn_t		*connp;
29537 	queue_t		*rq;
29538 	mblk_t		*first_mp;
29539 	boolean_t	secure;
29540 	ip6_t		*ip6h;
29541 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29542 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29543 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29544 	boolean_t	sctp_csum_err = B_FALSE;
29545 
29546 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29547 		sctp_csum_err = B_TRUE;
29548 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29549 	}
29550 
29551 	first_mp = mp;
29552 	if (mctl_present) {
29553 		mp = first_mp->b_cont;
29554 		secure = ipsec_in_is_secure(first_mp);
29555 		ASSERT(mp != NULL);
29556 	} else {
29557 		secure = B_FALSE;
29558 	}
29559 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29560 
29561 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29562 	if (connp == NULL) {
29563 		/*
29564 		 * Although raw sctp is not summed, OOB chunks must be.
29565 		 * Drop the packet here if the sctp checksum failed.
29566 		 */
29567 		if (sctp_csum_err) {
29568 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29569 			freemsg(first_mp);
29570 			return;
29571 		}
29572 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29573 		return;
29574 	}
29575 	rq = connp->conn_rq;
29576 	if (!canputnext(rq)) {
29577 		CONN_DEC_REF(connp);
29578 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29579 		freemsg(first_mp);
29580 		return;
29581 	}
29582 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29583 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29584 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29585 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29586 		if (first_mp == NULL) {
29587 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29588 			CONN_DEC_REF(connp);
29589 			return;
29590 		}
29591 	}
29592 	/*
29593 	 * We probably should not send M_CTL message up to
29594 	 * raw socket.
29595 	 */
29596 	if (mctl_present)
29597 		freeb(first_mp);
29598 
29599 	/* Initiate IPPF processing here if needed. */
29600 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29601 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29602 		ip_process(IPP_LOCAL_IN, &mp,
29603 		    recv_ill->ill_phyint->phyint_ifindex);
29604 		if (mp == NULL) {
29605 			CONN_DEC_REF(connp);
29606 			return;
29607 		}
29608 	}
29609 
29610 	if (connp->conn_recvif || connp->conn_recvslla ||
29611 	    ((connp->conn_ip_recvpktinfo ||
29612 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29613 	    (flags & IP_FF_IPINFO))) {
29614 		int in_flags = 0;
29615 
29616 		/*
29617 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29618 		 * IPF_RECVIF.
29619 		 */
29620 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29621 			in_flags = IPF_RECVIF;
29622 		}
29623 		if (connp->conn_recvslla) {
29624 			in_flags |= IPF_RECVSLLA;
29625 		}
29626 		if (isv4) {
29627 			mp = ip_add_info(mp, recv_ill, in_flags,
29628 			    IPCL_ZONEID(connp), ipst);
29629 		} else {
29630 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29631 			if (mp == NULL) {
29632 				BUMP_MIB(recv_ill->ill_ip_mib,
29633 				    ipIfStatsInDiscards);
29634 				CONN_DEC_REF(connp);
29635 				return;
29636 			}
29637 		}
29638 	}
29639 
29640 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29641 	/*
29642 	 * We are sending the IPSEC_IN message also up. Refer
29643 	 * to comments above this function.
29644 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29645 	 */
29646 	(connp->conn_recv)(connp, mp, NULL);
29647 	CONN_DEC_REF(connp);
29648 }
29649 
29650 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29651 {									\
29652 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29653 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29654 }
29655 /*
29656  * This function should be called only if all packet processing
29657  * including fragmentation is complete. Callers of this function
29658  * must set mp->b_prev to one of these values:
29659  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29660  * prior to handing over the mp as first argument to this function.
29661  *
29662  * If the ire passed by caller is incomplete, this function
29663  * queues the packet and if necessary, sends ARP request and bails.
29664  * If the ire passed is fully resolved, we simply prepend
29665  * the link-layer header to the packet, do ipsec hw acceleration
29666  * work if necessary, and send the packet out on the wire.
29667  *
29668  * NOTE: IPsec will only call this function with fully resolved
29669  * ires if hw acceleration is involved.
29670  * TODO list :
29671  * 	a Handle M_MULTIDATA so that
29672  *	  tcp_multisend->tcp_multisend_data can
29673  *	  call ip_xmit_v4 directly
29674  *	b Handle post-ARP work for fragments so that
29675  *	  ip_wput_frag can call this function.
29676  */
29677 ipxmit_state_t
29678 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29679     boolean_t flow_ctl_enabled, conn_t *connp)
29680 {
29681 	nce_t		*arpce;
29682 	ipha_t		*ipha;
29683 	queue_t		*q;
29684 	int		ill_index;
29685 	mblk_t		*nxt_mp, *first_mp;
29686 	boolean_t	xmit_drop = B_FALSE;
29687 	ip_proc_t	proc;
29688 	ill_t		*out_ill;
29689 	int		pkt_len;
29690 
29691 	arpce = ire->ire_nce;
29692 	ASSERT(arpce != NULL);
29693 
29694 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29695 
29696 	mutex_enter(&arpce->nce_lock);
29697 	switch (arpce->nce_state) {
29698 	case ND_REACHABLE:
29699 		/* If there are other queued packets, queue this packet */
29700 		if (arpce->nce_qd_mp != NULL) {
29701 			if (mp != NULL)
29702 				nce_queue_mp_common(arpce, mp, B_FALSE);
29703 			mp = arpce->nce_qd_mp;
29704 		}
29705 		arpce->nce_qd_mp = NULL;
29706 		mutex_exit(&arpce->nce_lock);
29707 
29708 		/*
29709 		 * Flush the queue.  In the common case, where the
29710 		 * ARP is already resolved,  it will go through the
29711 		 * while loop only once.
29712 		 */
29713 		while (mp != NULL) {
29714 
29715 			nxt_mp = mp->b_next;
29716 			mp->b_next = NULL;
29717 			ASSERT(mp->b_datap->db_type != M_CTL);
29718 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29719 			/*
29720 			 * This info is needed for IPQOS to do COS marking
29721 			 * in ip_wput_attach_llhdr->ip_process.
29722 			 */
29723 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29724 			mp->b_prev = NULL;
29725 
29726 			/* set up ill index for outbound qos processing */
29727 			out_ill = ire_to_ill(ire);
29728 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29729 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29730 			    ill_index, &ipha);
29731 			if (first_mp == NULL) {
29732 				xmit_drop = B_TRUE;
29733 				BUMP_MIB(out_ill->ill_ip_mib,
29734 				    ipIfStatsOutDiscards);
29735 				goto next_mp;
29736 			}
29737 
29738 			/* non-ipsec hw accel case */
29739 			if (io == NULL || !io->ipsec_out_accelerated) {
29740 				/* send it */
29741 				q = ire->ire_stq;
29742 				if (proc == IPP_FWD_OUT) {
29743 					UPDATE_IB_PKT_COUNT(ire);
29744 				} else {
29745 					UPDATE_OB_PKT_COUNT(ire);
29746 				}
29747 				ire->ire_last_used_time = lbolt;
29748 
29749 				if (flow_ctl_enabled || canputnext(q)) {
29750 					if (proc == IPP_FWD_OUT) {
29751 
29752 					BUMP_MIB(out_ill->ill_ip_mib,
29753 					    ipIfStatsHCOutForwDatagrams);
29754 
29755 					}
29756 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29757 					    pkt_len);
29758 
29759 					DTRACE_IP7(send, mblk_t *, first_mp,
29760 					    conn_t *, NULL, void_ip_t *, ipha,
29761 					    __dtrace_ipsr_ill_t *, out_ill,
29762 					    ipha_t *, ipha, ip6_t *, NULL, int,
29763 					    0);
29764 
29765 					ILL_SEND_TX(out_ill,
29766 					    ire, connp, first_mp, 0, connp);
29767 				} else {
29768 					BUMP_MIB(out_ill->ill_ip_mib,
29769 					    ipIfStatsOutDiscards);
29770 					xmit_drop = B_TRUE;
29771 					freemsg(first_mp);
29772 				}
29773 			} else {
29774 				/*
29775 				 * Safety Pup says: make sure this
29776 				 *  is going to the right interface!
29777 				 */
29778 				ill_t *ill1 =
29779 				    (ill_t *)ire->ire_stq->q_ptr;
29780 				int ifindex =
29781 				    ill1->ill_phyint->phyint_ifindex;
29782 				if (ifindex !=
29783 				    io->ipsec_out_capab_ill_index) {
29784 					xmit_drop = B_TRUE;
29785 					freemsg(mp);
29786 				} else {
29787 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29788 					    pkt_len);
29789 
29790 					DTRACE_IP7(send, mblk_t *, first_mp,
29791 					    conn_t *, NULL, void_ip_t *, ipha,
29792 					    __dtrace_ipsr_ill_t *, ill1,
29793 					    ipha_t *, ipha, ip6_t *, NULL,
29794 					    int, 0);
29795 
29796 					ipsec_hw_putnext(ire->ire_stq, mp);
29797 				}
29798 			}
29799 next_mp:
29800 			mp = nxt_mp;
29801 		} /* while (mp != NULL) */
29802 		if (xmit_drop)
29803 			return (SEND_FAILED);
29804 		else
29805 			return (SEND_PASSED);
29806 
29807 	case ND_INITIAL:
29808 	case ND_INCOMPLETE:
29809 
29810 		/*
29811 		 * While we do send off packets to dests that
29812 		 * use fully-resolved CGTP routes, we do not
29813 		 * handle unresolved CGTP routes.
29814 		 */
29815 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29816 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29817 
29818 		if (mp != NULL) {
29819 			/* queue the packet */
29820 			nce_queue_mp_common(arpce, mp, B_FALSE);
29821 		}
29822 
29823 		if (arpce->nce_state == ND_INCOMPLETE) {
29824 			mutex_exit(&arpce->nce_lock);
29825 			DTRACE_PROBE3(ip__xmit__incomplete,
29826 			    (ire_t *), ire, (mblk_t *), mp,
29827 			    (ipsec_out_t *), io);
29828 			return (LOOKUP_IN_PROGRESS);
29829 		}
29830 
29831 		arpce->nce_state = ND_INCOMPLETE;
29832 		mutex_exit(&arpce->nce_lock);
29833 
29834 		/*
29835 		 * Note that ire_add() (called from ire_forward())
29836 		 * holds a ref on the ire until ARP is completed.
29837 		 */
29838 		ire_arpresolve(ire);
29839 		return (LOOKUP_IN_PROGRESS);
29840 	default:
29841 		ASSERT(0);
29842 		mutex_exit(&arpce->nce_lock);
29843 		return (LLHDR_RESLV_FAILED);
29844 	}
29845 }
29846 
29847 #undef	UPDATE_IP_MIB_OB_COUNTERS
29848 
29849 /*
29850  * Return B_TRUE if the buffers differ in length or content.
29851  * This is used for comparing extension header buffers.
29852  * Note that an extension header would be declared different
29853  * even if all that changed was the next header value in that header i.e.
29854  * what really changed is the next extension header.
29855  */
29856 boolean_t
29857 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29858     uint_t blen)
29859 {
29860 	if (!b_valid)
29861 		blen = 0;
29862 
29863 	if (alen != blen)
29864 		return (B_TRUE);
29865 	if (alen == 0)
29866 		return (B_FALSE);	/* Both zero length */
29867 	return (bcmp(abuf, bbuf, alen));
29868 }
29869 
29870 /*
29871  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29872  * Return B_FALSE if memory allocation fails - don't change any state!
29873  */
29874 boolean_t
29875 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29876     const void *src, uint_t srclen)
29877 {
29878 	void *dst;
29879 
29880 	if (!src_valid)
29881 		srclen = 0;
29882 
29883 	ASSERT(*dstlenp == 0);
29884 	if (src != NULL && srclen != 0) {
29885 		dst = mi_alloc(srclen, BPRI_MED);
29886 		if (dst == NULL)
29887 			return (B_FALSE);
29888 	} else {
29889 		dst = NULL;
29890 	}
29891 	if (*dstp != NULL)
29892 		mi_free(*dstp);
29893 	*dstp = dst;
29894 	*dstlenp = dst == NULL ? 0 : srclen;
29895 	return (B_TRUE);
29896 }
29897 
29898 /*
29899  * Replace what is in *dst, *dstlen with the source.
29900  * Assumes ip_allocbuf has already been called.
29901  */
29902 void
29903 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29904     const void *src, uint_t srclen)
29905 {
29906 	if (!src_valid)
29907 		srclen = 0;
29908 
29909 	ASSERT(*dstlenp == srclen);
29910 	if (src != NULL && srclen != 0)
29911 		bcopy(src, *dstp, srclen);
29912 }
29913 
29914 /*
29915  * Free the storage pointed to by the members of an ip6_pkt_t.
29916  */
29917 void
29918 ip6_pkt_free(ip6_pkt_t *ipp)
29919 {
29920 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29921 
29922 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29923 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29924 		ipp->ipp_hopopts = NULL;
29925 		ipp->ipp_hopoptslen = 0;
29926 	}
29927 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29928 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29929 		ipp->ipp_rtdstopts = NULL;
29930 		ipp->ipp_rtdstoptslen = 0;
29931 	}
29932 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29933 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29934 		ipp->ipp_dstopts = NULL;
29935 		ipp->ipp_dstoptslen = 0;
29936 	}
29937 	if (ipp->ipp_fields & IPPF_RTHDR) {
29938 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29939 		ipp->ipp_rthdr = NULL;
29940 		ipp->ipp_rthdrlen = 0;
29941 	}
29942 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29943 	    IPPF_RTHDR);
29944 }
29945 
29946 zoneid_t
29947 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29948     zoneid_t lookup_zoneid)
29949 {
29950 	ire_t		*ire;
29951 	int		ire_flags = MATCH_IRE_TYPE;
29952 	zoneid_t	zoneid = ALL_ZONES;
29953 
29954 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29955 		return (ALL_ZONES);
29956 
29957 	if (lookup_zoneid != ALL_ZONES)
29958 		ire_flags |= MATCH_IRE_ZONEONLY;
29959 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29960 	    lookup_zoneid, NULL, ire_flags, ipst);
29961 	if (ire != NULL) {
29962 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29963 		ire_refrele(ire);
29964 	}
29965 	return (zoneid);
29966 }
29967 
29968 zoneid_t
29969 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29970     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29971 {
29972 	ire_t		*ire;
29973 	int		ire_flags = MATCH_IRE_TYPE;
29974 	zoneid_t	zoneid = ALL_ZONES;
29975 	ipif_t		*ipif_arg = NULL;
29976 
29977 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29978 		return (ALL_ZONES);
29979 
29980 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29981 		ire_flags |= MATCH_IRE_ILL;
29982 		ipif_arg = ill->ill_ipif;
29983 	}
29984 	if (lookup_zoneid != ALL_ZONES)
29985 		ire_flags |= MATCH_IRE_ZONEONLY;
29986 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29987 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29988 	if (ire != NULL) {
29989 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29990 		ire_refrele(ire);
29991 	}
29992 	return (zoneid);
29993 }
29994 
29995 /*
29996  * IP obserability hook support functions.
29997  */
29998 
29999 static void
30000 ipobs_init(ip_stack_t *ipst)
30001 {
30002 	ipst->ips_ipobs_enabled = B_FALSE;
30003 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30004 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30005 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30006 	ipst->ips_ipobs_cb_nwalkers = 0;
30007 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30008 }
30009 
30010 static void
30011 ipobs_fini(ip_stack_t *ipst)
30012 {
30013 	ipobs_cb_t *cb;
30014 
30015 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30016 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30017 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30018 
30019 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30020 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30021 		kmem_free(cb, sizeof (*cb));
30022 	}
30023 	list_destroy(&ipst->ips_ipobs_cb_list);
30024 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30025 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30026 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30027 }
30028 
30029 void
30030 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30031     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30032 {
30033 	mblk_t *mp2;
30034 	ipobs_cb_t *ipobs_cb;
30035 	ipobs_hook_data_t *ihd;
30036 	uint64_t grifindex = 0;
30037 
30038 	ASSERT(DB_TYPE(mp) == M_DATA);
30039 
30040 	if (IS_UNDER_IPMP(ill))
30041 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30042 
30043 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30044 	ipst->ips_ipobs_cb_nwalkers++;
30045 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30046 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30047 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30048 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30049 		if (mp2 != NULL) {
30050 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30051 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30052 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30053 				freemsg(mp2);
30054 				continue;
30055 			}
30056 			ihd->ihd_mp->b_rptr += hlen;
30057 			ihd->ihd_htype = htype;
30058 			ihd->ihd_ipver = ipver;
30059 			ihd->ihd_zsrc = zsrc;
30060 			ihd->ihd_zdst = zdst;
30061 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30062 			ihd->ihd_grifindex = grifindex;
30063 			ihd->ihd_stack = ipst->ips_netstack;
30064 			mp2->b_wptr += sizeof (*ihd);
30065 			ipobs_cb->ipobs_cbfunc(mp2);
30066 		}
30067 	}
30068 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30069 	ipst->ips_ipobs_cb_nwalkers--;
30070 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30071 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30072 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30073 }
30074 
30075 void
30076 ipobs_register_hook(netstack_t *ns, pfv_t func)
30077 {
30078 	ipobs_cb_t   *cb;
30079 	ip_stack_t *ipst = ns->netstack_ip;
30080 
30081 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30082 
30083 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30084 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30085 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30086 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30087 
30088 	cb->ipobs_cbfunc = func;
30089 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30090 	ipst->ips_ipobs_enabled = B_TRUE;
30091 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30092 }
30093 
30094 void
30095 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30096 {
30097 	ipobs_cb_t	*curcb;
30098 	ip_stack_t	*ipst = ns->netstack_ip;
30099 
30100 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30101 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30102 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30103 
30104 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30105 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30106 		if (func == curcb->ipobs_cbfunc) {
30107 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30108 			kmem_free(curcb, sizeof (*curcb));
30109 			break;
30110 		}
30111 	}
30112 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30113 		ipst->ips_ipobs_enabled = B_FALSE;
30114 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30115 }
30116