xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 753a6d45)
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 
874 /*
875  * Threshold which determines whether MDT should be used when
876  * generating IP fragments; payload size must be greater than
877  * this threshold for MDT to take place.
878  */
879 #define	IP_WPUT_FRAG_MDT_MIN	32768
880 
881 /* Setable in /etc/system only */
882 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
883 
884 static long ip_rput_pullups;
885 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
886 
887 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
888 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
889 
890 int	ip_debug;
891 
892 #ifdef DEBUG
893 uint32_t ipsechw_debug = 0;
894 #endif
895 
896 /*
897  * Multirouting/CGTP stuff
898  */
899 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
900 
901 /*
902  * XXX following really should only be in a header. Would need more
903  * header and .c clean up first.
904  */
905 extern optdb_obj_t	ip_opt_obj;
906 
907 ulong_t ip_squeue_enter_unbound = 0;
908 
909 /*
910  * Named Dispatch Parameter Table.
911  * All of these are alterable, within the min/max values given, at run time.
912  */
913 static ipparam_t	lcl_param_arr[] = {
914 	/* min	max	value	name */
915 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
916 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
918 	{  0,	1,	0,	"ip_respond_to_timestamp"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
920 	{  0,	1,	1,	"ip_send_redirects"},
921 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
922 	{  0,	10,	0,	"ip_mrtdebug"},
923 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
924 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
925 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
926 	{  1,	255,	255,	"ip_def_ttl" },
927 	{  0,	1,	0,	"ip_forward_src_routed"},
928 	{  0,	256,	32,	"ip_wroff_extra" },
929 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
930 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
931 	{  0,	1,	1,	"ip_path_mtu_discovery" },
932 	{  0,	240,	30,	"ip_ignore_delete_time" },
933 	{  0,	1,	0,	"ip_ignore_redirect" },
934 	{  0,	1,	1,	"ip_output_queue" },
935 	{  1,	254,	1,	"ip_broadcast_ttl" },
936 	{  0,	99999,	100,	"ip_icmp_err_interval" },
937 	{  1,	99999,	10,	"ip_icmp_err_burst" },
938 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
939 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
940 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
941 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
942 	{  0,	1,	1,	"icmp_accept_clear_messages" },
943 	{  0,	1,	1,	"igmp_accept_clear_messages" },
944 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
945 				"ip_ndp_delay_first_probe_time"},
946 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
947 				"ip_ndp_max_unicast_solicit"},
948 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
949 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
950 	{  0,	1,	0,	"ip6_forward_src_routed"},
951 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
952 	{  0,	1,	1,	"ip6_send_redirects"},
953 	{  0,	1,	0,	"ip6_ignore_redirect" },
954 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
955 
956 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
957 
958 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
959 
960 	{  0,	1,	1,	"pim_accept_clear_messages" },
961 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
962 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
963 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
964 	{  0,	15,	0,	"ip_policy_mask" },
965 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
966 	{  0,	255,	1,	"ip_multirt_ttl" },
967 	{  0,	1,	1,	"ip_multidata_outbound" },
968 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
969 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
970 	{  0,	1000,	1,	"ip_max_temp_defend" },
971 	{  0,	1000,	3,	"ip_max_defend" },
972 	{  0,	999999,	30,	"ip_defend_interval" },
973 	{  0,	3600000, 300000, "ip_dup_recovery" },
974 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
975 	{  0,	1,	1,	"ip_lso_outbound" },
976 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
977 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
978 	{ 68,	65535,	576,	"ip_pmtu_min" },
979 #ifdef DEBUG
980 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
981 #else
982 	{  0,	0,	0,	"" },
983 #endif
984 };
985 
986 /*
987  * Extended NDP table
988  * The addresses for the first two are filled in to be ips_ip_g_forward
989  * and ips_ipv6_forward at init time.
990  */
991 static ipndp_t	lcl_ndp_arr[] = {
992 	/* getf			setf		data			name */
993 #define	IPNDP_IP_FORWARDING_OFFSET	0
994 	{  ip_param_generic_get,	ip_forward_set,	NULL,
995 	    "ip_forwarding" },
996 #define	IPNDP_IP6_FORWARDING_OFFSET	1
997 	{  ip_param_generic_get,	ip_forward_set,	NULL,
998 	    "ip6_forwarding" },
999 	{ ip_param_generic_get, ip_input_proc_set,
1000 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1001 	{ ip_param_generic_get, ip_int_set,
1002 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1003 #define	IPNDP_CGTP_FILTER_OFFSET	4
1004 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1005 	    "ip_cgtp_filter" },
1006 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1007 	    "ip_debug" },
1008 };
1009 
1010 /*
1011  * Table of IP ioctls encoding the various properties of the ioctl and
1012  * indexed based on the last byte of the ioctl command. Occasionally there
1013  * is a clash, and there is more than 1 ioctl with the same last byte.
1014  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1015  * ioctls are encoded in the misc table. An entry in the ndx table is
1016  * retrieved by indexing on the last byte of the ioctl command and comparing
1017  * the ioctl command with the value in the ndx table. In the event of a
1018  * mismatch the misc table is then searched sequentially for the desired
1019  * ioctl command.
1020  *
1021  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1022  */
1023 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1024 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 
1035 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1036 			MISC_CMD, ip_siocaddrt, NULL },
1037 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1038 			MISC_CMD, ip_siocdelrt, NULL },
1039 
1040 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1041 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1042 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1043 			IF_CMD, ip_sioctl_get_addr, NULL },
1044 
1045 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1046 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1047 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1048 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1049 
1050 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1051 			IPI_PRIV | IPI_WR,
1052 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1053 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1054 			IPI_MODOK | IPI_GET_CMD,
1055 			IF_CMD, ip_sioctl_get_flags, NULL },
1056 
1057 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 
1060 	/* copyin size cannot be coded for SIOCGIFCONF */
1061 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1062 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1063 
1064 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1065 			IF_CMD, ip_sioctl_mtu, NULL },
1066 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1067 			IF_CMD, ip_sioctl_get_mtu, NULL },
1068 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1069 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1070 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1071 			IF_CMD, ip_sioctl_brdaddr, NULL },
1072 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1073 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1074 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1075 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1076 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1077 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1078 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1079 			IF_CMD, ip_sioctl_metric, NULL },
1080 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 
1082 	/* See 166-168 below for extended SIOC*XARP ioctls */
1083 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1084 			ARP_CMD, ip_sioctl_arp, NULL },
1085 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1086 			ARP_CMD, ip_sioctl_arp, NULL },
1087 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1088 			ARP_CMD, ip_sioctl_arp, NULL },
1089 
1090 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 
1112 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1113 			MISC_CMD, if_unitsel, if_unitsel_restart },
1114 
1115 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 
1134 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1135 			IPI_PRIV | IPI_WR | IPI_MODOK,
1136 			IF_CMD, ip_sioctl_sifname, NULL },
1137 
1138 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 
1152 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1153 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1154 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1155 			IF_CMD, ip_sioctl_get_muxid, NULL },
1156 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1157 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1158 
1159 	/* Both if and lif variants share same func */
1160 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1161 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1162 	/* Both if and lif variants share same func */
1163 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1164 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1165 
1166 	/* copyin size cannot be coded for SIOCGIFCONF */
1167 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1168 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1169 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 
1187 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1188 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1189 			ip_sioctl_removeif_restart },
1190 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1191 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1192 			LIF_CMD, ip_sioctl_addif, NULL },
1193 #define	SIOCLIFADDR_NDX 112
1194 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1195 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1196 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1197 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1198 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1199 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1200 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1201 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1202 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1203 			IPI_PRIV | IPI_WR,
1204 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1205 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1206 			IPI_GET_CMD | IPI_MODOK,
1207 			LIF_CMD, ip_sioctl_get_flags, NULL },
1208 
1209 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1210 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 
1212 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1213 			ip_sioctl_get_lifconf, NULL },
1214 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1215 			LIF_CMD, ip_sioctl_mtu, NULL },
1216 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1217 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1218 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1219 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1220 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1221 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1222 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1223 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1224 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1225 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1226 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1227 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1228 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_metric, NULL },
1230 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR | IPI_MODOK,
1232 			LIF_CMD, ip_sioctl_slifname,
1233 			ip_sioctl_slifname_restart },
1234 
1235 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1236 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1237 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1238 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1239 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1240 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1241 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1242 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1243 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1244 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1245 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1246 			LIF_CMD, ip_sioctl_token, NULL },
1247 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1248 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1249 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1250 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1251 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1252 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1253 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1254 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1255 
1256 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1257 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1258 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1259 			LIF_CMD, ip_siocdelndp_v6, NULL },
1260 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1261 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1262 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1263 			LIF_CMD, ip_siocsetndp_v6, NULL },
1264 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1265 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1266 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1267 			MISC_CMD, ip_sioctl_tonlink, NULL },
1268 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1269 			MISC_CMD, ip_sioctl_tmysite, NULL },
1270 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1271 			TUN_CMD, ip_sioctl_tunparam, NULL },
1272 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1273 		    IPI_PRIV | IPI_WR,
1274 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1275 
1276 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1277 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1278 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1279 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1280 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1281 
1282 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1283 
1284 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1285 			LIF_CMD, ip_sioctl_get_binding, NULL },
1286 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1287 			IPI_PRIV | IPI_WR,
1288 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1289 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1290 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1291 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1292 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1293 
1294 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1295 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1296 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 
1299 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1300 
1301 	/* These are handled in ip_sioctl_copyin_setup itself */
1302 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1303 			MISC_CMD, NULL, NULL },
1304 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1305 			MISC_CMD, NULL, NULL },
1306 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1307 
1308 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1309 			ip_sioctl_get_lifconf, NULL },
1310 
1311 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1312 			XARP_CMD, ip_sioctl_arp, NULL },
1313 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1314 			XARP_CMD, ip_sioctl_arp, NULL },
1315 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1316 			XARP_CMD, ip_sioctl_arp, NULL },
1317 
1318 	/* SIOCPOPSOCKFS is not handled by IP */
1319 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1320 
1321 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1322 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1323 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1324 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1325 			ip_sioctl_slifzone_restart },
1326 	/* 172-174 are SCTP ioctls and not handled by IP */
1327 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1328 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1329 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1330 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1331 			IPI_GET_CMD, LIF_CMD,
1332 			ip_sioctl_get_lifusesrc, 0 },
1333 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1334 			IPI_PRIV | IPI_WR,
1335 			LIF_CMD, ip_sioctl_slifusesrc,
1336 			NULL },
1337 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1338 			ip_sioctl_get_lifsrcof, NULL },
1339 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1340 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1341 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1342 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1343 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1344 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1345 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1346 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1347 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1348 	/* SIOCSENABLESDP is handled by SDP */
1349 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1350 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1351 };
1352 
1353 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1354 
1355 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1356 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1357 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1358 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1359 		TUN_CMD, ip_sioctl_tunparam, NULL },
1360 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1361 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1362 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1363 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1364 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1365 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1366 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1367 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1368 		MISC_CMD, mrt_ioctl},
1369 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1370 		MISC_CMD, mrt_ioctl},
1371 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1372 		MISC_CMD, mrt_ioctl}
1373 };
1374 
1375 int ip_misc_ioctl_count =
1376     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1377 
1378 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1379 					/* Settable in /etc/system */
1380 /* Defined in ip_ire.c */
1381 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1382 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1383 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1384 
1385 static nv_t	ire_nv_arr[] = {
1386 	{ IRE_BROADCAST, "BROADCAST" },
1387 	{ IRE_LOCAL, "LOCAL" },
1388 	{ IRE_LOOPBACK, "LOOPBACK" },
1389 	{ IRE_CACHE, "CACHE" },
1390 	{ IRE_DEFAULT, "DEFAULT" },
1391 	{ IRE_PREFIX, "PREFIX" },
1392 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1393 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1394 	{ IRE_HOST, "HOST" },
1395 	{ 0 }
1396 };
1397 
1398 nv_t	*ire_nv_tbl = ire_nv_arr;
1399 
1400 /* Simple ICMP IP Header Template */
1401 static ipha_t icmp_ipha = {
1402 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1403 };
1404 
1405 struct module_info ip_mod_info = {
1406 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1407 	IP_MOD_LOWAT
1408 };
1409 
1410 /*
1411  * Duplicate static symbols within a module confuses mdb; so we avoid the
1412  * problem by making the symbols here distinct from those in udp.c.
1413  */
1414 
1415 /*
1416  * Entry points for IP as a device and as a module.
1417  * FIXME: down the road we might want a separate module and driver qinit.
1418  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1419  */
1420 static struct qinit iprinitv4 = {
1421 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1422 	&ip_mod_info
1423 };
1424 
1425 struct qinit iprinitv6 = {
1426 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1427 	&ip_mod_info
1428 };
1429 
1430 static struct qinit ipwinitv4 = {
1431 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1432 	&ip_mod_info
1433 };
1434 
1435 struct qinit ipwinitv6 = {
1436 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1437 	&ip_mod_info
1438 };
1439 
1440 static struct qinit iplrinit = {
1441 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1442 	&ip_mod_info
1443 };
1444 
1445 static struct qinit iplwinit = {
1446 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1447 	&ip_mod_info
1448 };
1449 
1450 /* For AF_INET aka /dev/ip */
1451 struct streamtab ipinfov4 = {
1452 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1453 };
1454 
1455 /* For AF_INET6 aka /dev/ip6 */
1456 struct streamtab ipinfov6 = {
1457 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1458 };
1459 
1460 #ifdef	DEBUG
1461 static boolean_t skip_sctp_cksum = B_FALSE;
1462 #endif
1463 
1464 /*
1465  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1466  * ip_rput_v6(), ip_output(), etc.  If the message
1467  * block already has a M_CTL at the front of it, then simply set the zoneid
1468  * appropriately.
1469  */
1470 mblk_t *
1471 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1472 {
1473 	mblk_t		*first_mp;
1474 	ipsec_out_t	*io;
1475 
1476 	ASSERT(zoneid != ALL_ZONES);
1477 	if (mp->b_datap->db_type == M_CTL) {
1478 		io = (ipsec_out_t *)mp->b_rptr;
1479 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1480 		io->ipsec_out_zoneid = zoneid;
1481 		return (mp);
1482 	}
1483 
1484 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1485 	if (first_mp == NULL)
1486 		return (NULL);
1487 	io = (ipsec_out_t *)first_mp->b_rptr;
1488 	/* This is not a secure packet */
1489 	io->ipsec_out_secure = B_FALSE;
1490 	io->ipsec_out_zoneid = zoneid;
1491 	first_mp->b_cont = mp;
1492 	return (first_mp);
1493 }
1494 
1495 /*
1496  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1497  */
1498 mblk_t *
1499 ip_copymsg(mblk_t *mp)
1500 {
1501 	mblk_t *nmp;
1502 	ipsec_info_t *in;
1503 
1504 	if (mp->b_datap->db_type != M_CTL)
1505 		return (copymsg(mp));
1506 
1507 	in = (ipsec_info_t *)mp->b_rptr;
1508 
1509 	/*
1510 	 * Note that M_CTL is also used for delivering ICMP error messages
1511 	 * upstream to transport layers.
1512 	 */
1513 	if (in->ipsec_info_type != IPSEC_OUT &&
1514 	    in->ipsec_info_type != IPSEC_IN)
1515 		return (copymsg(mp));
1516 
1517 	nmp = copymsg(mp->b_cont);
1518 
1519 	if (in->ipsec_info_type == IPSEC_OUT) {
1520 		return (ipsec_out_tag(mp, nmp,
1521 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1522 	} else {
1523 		return (ipsec_in_tag(mp, nmp,
1524 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1525 	}
1526 }
1527 
1528 /* Generate an ICMP fragmentation needed message. */
1529 static void
1530 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1531     ip_stack_t *ipst)
1532 {
1533 	icmph_t	icmph;
1534 	mblk_t *first_mp;
1535 	boolean_t mctl_present;
1536 
1537 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1538 
1539 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1540 		if (mctl_present)
1541 			freeb(first_mp);
1542 		return;
1543 	}
1544 
1545 	bzero(&icmph, sizeof (icmph_t));
1546 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1547 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1548 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1549 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1550 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1551 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1552 	    ipst);
1553 }
1554 
1555 /*
1556  * icmp_inbound deals with ICMP messages in the following ways.
1557  *
1558  * 1) It needs to send a reply back and possibly delivering it
1559  *    to the "interested" upper clients.
1560  * 2) It needs to send it to the upper clients only.
1561  * 3) It needs to change some values in IP only.
1562  * 4) It needs to change some values in IP and upper layers e.g TCP.
1563  *
1564  * We need to accomodate icmp messages coming in clear until we get
1565  * everything secure from the wire. If icmp_accept_clear_messages
1566  * is zero we check with the global policy and act accordingly. If
1567  * it is non-zero, we accept the message without any checks. But
1568  * *this does not mean* that this will be delivered to the upper
1569  * clients. By accepting we might send replies back, change our MTU
1570  * value etc. but delivery to the ULP/clients depends on their policy
1571  * dispositions.
1572  *
1573  * We handle the above 4 cases in the context of IPsec in the
1574  * following way :
1575  *
1576  * 1) Send the reply back in the same way as the request came in.
1577  *    If it came in encrypted, it goes out encrypted. If it came in
1578  *    clear, it goes out in clear. Thus, this will prevent chosen
1579  *    plain text attack.
1580  * 2) The client may or may not expect things to come in secure.
1581  *    If it comes in secure, the policy constraints are checked
1582  *    before delivering it to the upper layers. If it comes in
1583  *    clear, ipsec_inbound_accept_clear will decide whether to
1584  *    accept this in clear or not. In both the cases, if the returned
1585  *    message (IP header + 8 bytes) that caused the icmp message has
1586  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1587  *    sending up. If there are only 8 bytes of returned message, then
1588  *    upper client will not be notified.
1589  * 3) Check with global policy to see whether it matches the constaints.
1590  *    But this will be done only if icmp_accept_messages_in_clear is
1591  *    zero.
1592  * 4) If we need to change both in IP and ULP, then the decision taken
1593  *    while affecting the values in IP and while delivering up to TCP
1594  *    should be the same.
1595  *
1596  * 	There are two cases.
1597  *
1598  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1599  *	   failed), we will not deliver it to the ULP, even though they
1600  *	   are *willing* to accept in *clear*. This is fine as our global
1601  *	   disposition to icmp messages asks us reject the datagram.
1602  *
1603  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1604  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1605  *	   to deliver it to ULP (policy failed), it can lead to
1606  *	   consistency problems. The cases known at this time are
1607  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1608  *	   values :
1609  *
1610  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1611  *	     and Upper layer rejects. Then the communication will
1612  *	     come to a stop. This is solved by making similar decisions
1613  *	     at both levels. Currently, when we are unable to deliver
1614  *	     to the Upper Layer (due to policy failures) while IP has
1615  *	     adjusted ire_max_frag, the next outbound datagram would
1616  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1617  *	     will be with the right level of protection. Thus the right
1618  *	     value will be communicated even if we are not able to
1619  *	     communicate when we get from the wire initially. But this
1620  *	     assumes there would be at least one outbound datagram after
1621  *	     IP has adjusted its ire_max_frag value. To make things
1622  *	     simpler, we accept in clear after the validation of
1623  *	     AH/ESP headers.
1624  *
1625  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1626  *	     upper layer depending on the level of protection the upper
1627  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1628  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1629  *	     should be accepted in clear when the Upper layer expects secure.
1630  *	     Thus the communication may get aborted by some bad ICMP
1631  *	     packets.
1632  *
1633  * IPQoS Notes:
1634  * The only instance when a packet is sent for processing is when there
1635  * isn't an ICMP client and if we are interested in it.
1636  * If there is a client, IPPF processing will take place in the
1637  * ip_fanout_proto routine.
1638  *
1639  * Zones notes:
1640  * The packet is only processed in the context of the specified zone: typically
1641  * only this zone will reply to an echo request, and only interested clients in
1642  * this zone will receive a copy of the packet. This means that the caller must
1643  * call icmp_inbound() for each relevant zone.
1644  */
1645 static void
1646 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1647     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1648     ill_t *recv_ill, zoneid_t zoneid)
1649 {
1650 	icmph_t	*icmph;
1651 	ipha_t	*ipha;
1652 	int	iph_hdr_length;
1653 	int	hdr_length;
1654 	boolean_t	interested;
1655 	uint32_t	ts;
1656 	uchar_t	*wptr;
1657 	ipif_t	*ipif;
1658 	mblk_t *first_mp;
1659 	ipsec_in_t *ii;
1660 	timestruc_t now;
1661 	uint32_t ill_index;
1662 	ip_stack_t *ipst;
1663 
1664 	ASSERT(ill != NULL);
1665 	ipst = ill->ill_ipst;
1666 
1667 	first_mp = mp;
1668 	if (mctl_present) {
1669 		mp = first_mp->b_cont;
1670 		ASSERT(mp != NULL);
1671 	}
1672 
1673 	ipha = (ipha_t *)mp->b_rptr;
1674 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1675 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1676 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1677 		if (first_mp == NULL)
1678 			return;
1679 	}
1680 
1681 	/*
1682 	 * On a labeled system, we have to check whether the zone itself is
1683 	 * permitted to receive raw traffic.
1684 	 */
1685 	if (is_system_labeled()) {
1686 		if (zoneid == ALL_ZONES)
1687 			zoneid = tsol_packet_to_zoneid(mp);
1688 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1689 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1690 			    zoneid));
1691 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1692 			freemsg(first_mp);
1693 			return;
1694 		}
1695 	}
1696 
1697 	/*
1698 	 * We have accepted the ICMP message. It means that we will
1699 	 * respond to the packet if needed. It may not be delivered
1700 	 * to the upper client depending on the policy constraints
1701 	 * and the disposition in ipsec_inbound_accept_clear.
1702 	 */
1703 
1704 	ASSERT(ill != NULL);
1705 
1706 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1707 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1708 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1709 		/* Last chance to get real. */
1710 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1711 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1712 			freemsg(first_mp);
1713 			return;
1714 		}
1715 		/* Refresh iph following the pullup. */
1716 		ipha = (ipha_t *)mp->b_rptr;
1717 	}
1718 	/* ICMP header checksum, including checksum field, should be zero. */
1719 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1720 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1721 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1722 		freemsg(first_mp);
1723 		return;
1724 	}
1725 	/* The IP header will always be a multiple of four bytes */
1726 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1727 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1728 	    icmph->icmph_code));
1729 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1730 	/* We will set "interested" to "true" if we want a copy */
1731 	interested = B_FALSE;
1732 	switch (icmph->icmph_type) {
1733 	case ICMP_ECHO_REPLY:
1734 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1735 		break;
1736 	case ICMP_DEST_UNREACHABLE:
1737 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1738 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1739 		interested = B_TRUE;	/* Pass up to transport */
1740 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1741 		break;
1742 	case ICMP_SOURCE_QUENCH:
1743 		interested = B_TRUE;	/* Pass up to transport */
1744 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1745 		break;
1746 	case ICMP_REDIRECT:
1747 		if (!ipst->ips_ip_ignore_redirect)
1748 			interested = B_TRUE;
1749 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1750 		break;
1751 	case ICMP_ECHO_REQUEST:
1752 		/*
1753 		 * Whether to respond to echo requests that come in as IP
1754 		 * broadcasts or as IP multicast is subject to debate
1755 		 * (what isn't?).  We aim to please, you pick it.
1756 		 * Default is do it.
1757 		 */
1758 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1759 			/* unicast: always respond */
1760 			interested = B_TRUE;
1761 		} else if (CLASSD(ipha->ipha_dst)) {
1762 			/* multicast: respond based on tunable */
1763 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1764 		} else if (broadcast) {
1765 			/* broadcast: respond based on tunable */
1766 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1767 		}
1768 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1769 		break;
1770 	case ICMP_ROUTER_ADVERTISEMENT:
1771 	case ICMP_ROUTER_SOLICITATION:
1772 		break;
1773 	case ICMP_TIME_EXCEEDED:
1774 		interested = B_TRUE;	/* Pass up to transport */
1775 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1776 		break;
1777 	case ICMP_PARAM_PROBLEM:
1778 		interested = B_TRUE;	/* Pass up to transport */
1779 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1780 		break;
1781 	case ICMP_TIME_STAMP_REQUEST:
1782 		/* Response to Time Stamp Requests is local policy. */
1783 		if (ipst->ips_ip_g_resp_to_timestamp &&
1784 		    /* So is whether to respond if it was an IP broadcast. */
1785 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1786 			int tstamp_len = 3 * sizeof (uint32_t);
1787 
1788 			if (wptr +  tstamp_len > mp->b_wptr) {
1789 				if (!pullupmsg(mp, wptr + tstamp_len -
1790 				    mp->b_rptr)) {
1791 					BUMP_MIB(ill->ill_ip_mib,
1792 					    ipIfStatsInDiscards);
1793 					freemsg(first_mp);
1794 					return;
1795 				}
1796 				/* Refresh ipha following the pullup. */
1797 				ipha = (ipha_t *)mp->b_rptr;
1798 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1799 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1800 			}
1801 			interested = B_TRUE;
1802 		}
1803 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1804 		break;
1805 	case ICMP_TIME_STAMP_REPLY:
1806 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1807 		break;
1808 	case ICMP_INFO_REQUEST:
1809 		/* Per RFC 1122 3.2.2.7, ignore this. */
1810 	case ICMP_INFO_REPLY:
1811 		break;
1812 	case ICMP_ADDRESS_MASK_REQUEST:
1813 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1814 		    !broadcast) &&
1815 		    /* TODO m_pullup of complete header? */
1816 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1817 			interested = B_TRUE;
1818 		}
1819 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1820 		break;
1821 	case ICMP_ADDRESS_MASK_REPLY:
1822 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1823 		break;
1824 	default:
1825 		interested = B_TRUE;	/* Pass up to transport */
1826 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1827 		break;
1828 	}
1829 	/* See if there is an ICMP client. */
1830 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1831 		/* If there is an ICMP client and we want one too, copy it. */
1832 		mblk_t *first_mp1;
1833 
1834 		if (!interested) {
1835 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1836 			    ip_policy, recv_ill, zoneid);
1837 			return;
1838 		}
1839 		first_mp1 = ip_copymsg(first_mp);
1840 		if (first_mp1 != NULL) {
1841 			ip_fanout_proto(q, first_mp1, ill, ipha,
1842 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1843 		}
1844 	} else if (!interested) {
1845 		freemsg(first_mp);
1846 		return;
1847 	} else {
1848 		/*
1849 		 * Initiate policy processing for this packet if ip_policy
1850 		 * is true.
1851 		 */
1852 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1853 			ill_index = ill->ill_phyint->phyint_ifindex;
1854 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1855 			if (mp == NULL) {
1856 				if (mctl_present) {
1857 					freeb(first_mp);
1858 				}
1859 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1860 				return;
1861 			}
1862 		}
1863 	}
1864 	/* We want to do something with it. */
1865 	/* Check db_ref to make sure we can modify the packet. */
1866 	if (mp->b_datap->db_ref > 1) {
1867 		mblk_t	*first_mp1;
1868 
1869 		first_mp1 = ip_copymsg(first_mp);
1870 		freemsg(first_mp);
1871 		if (!first_mp1) {
1872 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1873 			return;
1874 		}
1875 		first_mp = first_mp1;
1876 		if (mctl_present) {
1877 			mp = first_mp->b_cont;
1878 			ASSERT(mp != NULL);
1879 		} else {
1880 			mp = first_mp;
1881 		}
1882 		ipha = (ipha_t *)mp->b_rptr;
1883 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1884 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1885 	}
1886 	switch (icmph->icmph_type) {
1887 	case ICMP_ADDRESS_MASK_REQUEST:
1888 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1889 		if (ipif == NULL) {
1890 			freemsg(first_mp);
1891 			return;
1892 		}
1893 		/*
1894 		 * outging interface must be IPv4
1895 		 */
1896 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1897 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1898 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1899 		ipif_refrele(ipif);
1900 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1901 		break;
1902 	case ICMP_ECHO_REQUEST:
1903 		icmph->icmph_type = ICMP_ECHO_REPLY;
1904 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1905 		break;
1906 	case ICMP_TIME_STAMP_REQUEST: {
1907 		uint32_t *tsp;
1908 
1909 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1910 		tsp = (uint32_t *)wptr;
1911 		tsp++;		/* Skip past 'originate time' */
1912 		/* Compute # of milliseconds since midnight */
1913 		gethrestime(&now);
1914 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1915 		    now.tv_nsec / (NANOSEC / MILLISEC);
1916 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1917 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1918 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1919 		break;
1920 	}
1921 	default:
1922 		ipha = (ipha_t *)&icmph[1];
1923 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1924 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1925 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1926 				freemsg(first_mp);
1927 				return;
1928 			}
1929 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1930 			ipha = (ipha_t *)&icmph[1];
1931 		}
1932 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1933 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1934 			freemsg(first_mp);
1935 			return;
1936 		}
1937 		hdr_length = IPH_HDR_LENGTH(ipha);
1938 		if (hdr_length < sizeof (ipha_t)) {
1939 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1940 			freemsg(first_mp);
1941 			return;
1942 		}
1943 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1944 			if (!pullupmsg(mp,
1945 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1946 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1947 				freemsg(first_mp);
1948 				return;
1949 			}
1950 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1951 			ipha = (ipha_t *)&icmph[1];
1952 		}
1953 		switch (icmph->icmph_type) {
1954 		case ICMP_REDIRECT:
1955 			/*
1956 			 * As there is no upper client to deliver, we don't
1957 			 * need the first_mp any more.
1958 			 */
1959 			if (mctl_present) {
1960 				freeb(first_mp);
1961 			}
1962 			icmp_redirect(ill, mp);
1963 			return;
1964 		case ICMP_DEST_UNREACHABLE:
1965 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1966 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1967 				    zoneid, mp, iph_hdr_length, ipst)) {
1968 					freemsg(first_mp);
1969 					return;
1970 				}
1971 				/*
1972 				 * icmp_inbound_too_big() may alter mp.
1973 				 * Resynch ipha and icmph accordingly.
1974 				 */
1975 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1976 				ipha = (ipha_t *)&icmph[1];
1977 			}
1978 			/* FALLTHRU */
1979 		default :
1980 			/*
1981 			 * IPQoS notes: Since we have already done IPQoS
1982 			 * processing we don't want to do it again in
1983 			 * the fanout routines called by
1984 			 * icmp_inbound_error_fanout, hence the last
1985 			 * argument, ip_policy, is B_FALSE.
1986 			 */
1987 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1988 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1989 			    B_FALSE, recv_ill, zoneid);
1990 		}
1991 		return;
1992 	}
1993 	/* Send out an ICMP packet */
1994 	icmph->icmph_checksum = 0;
1995 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1996 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1997 		ipif_t	*ipif_chosen;
1998 		/*
1999 		 * Make it look like it was directed to us, so we don't look
2000 		 * like a fool with a broadcast or multicast source address.
2001 		 */
2002 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2003 		/*
2004 		 * Make sure that we haven't grabbed an interface that's DOWN.
2005 		 */
2006 		if (ipif != NULL) {
2007 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2008 			    ipha->ipha_src, zoneid);
2009 			if (ipif_chosen != NULL) {
2010 				ipif_refrele(ipif);
2011 				ipif = ipif_chosen;
2012 			}
2013 		}
2014 		if (ipif == NULL) {
2015 			ip0dbg(("icmp_inbound: "
2016 			    "No source for broadcast/multicast:\n"
2017 			    "\tsrc 0x%x dst 0x%x ill %p "
2018 			    "ipif_lcl_addr 0x%x\n",
2019 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2020 			    (void *)ill,
2021 			    ill->ill_ipif->ipif_lcl_addr));
2022 			freemsg(first_mp);
2023 			return;
2024 		}
2025 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2026 		ipha->ipha_dst = ipif->ipif_src_addr;
2027 		ipif_refrele(ipif);
2028 	}
2029 	/* Reset time to live. */
2030 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2031 	{
2032 		/* Swap source and destination addresses */
2033 		ipaddr_t tmp;
2034 
2035 		tmp = ipha->ipha_src;
2036 		ipha->ipha_src = ipha->ipha_dst;
2037 		ipha->ipha_dst = tmp;
2038 	}
2039 	ipha->ipha_ident = 0;
2040 	if (!IS_SIMPLE_IPH(ipha))
2041 		icmp_options_update(ipha);
2042 
2043 	if (!mctl_present) {
2044 		/*
2045 		 * This packet should go out the same way as it
2046 		 * came in i.e in clear. To make sure that global
2047 		 * policy will not be applied to this in ip_wput_ire,
2048 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2049 		 */
2050 		ASSERT(first_mp == mp);
2051 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2052 		if (first_mp == NULL) {
2053 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2054 			freemsg(mp);
2055 			return;
2056 		}
2057 		ii = (ipsec_in_t *)first_mp->b_rptr;
2058 
2059 		/* This is not a secure packet */
2060 		ii->ipsec_in_secure = B_FALSE;
2061 		first_mp->b_cont = mp;
2062 	} else {
2063 		ii = (ipsec_in_t *)first_mp->b_rptr;
2064 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2065 	}
2066 	ii->ipsec_in_zoneid = zoneid;
2067 	ASSERT(zoneid != ALL_ZONES);
2068 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2069 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2070 		return;
2071 	}
2072 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2073 	put(WR(q), first_mp);
2074 }
2075 
2076 static ipaddr_t
2077 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2078 {
2079 	conn_t *connp;
2080 	connf_t *connfp;
2081 	ipaddr_t nexthop_addr = INADDR_ANY;
2082 	int hdr_length = IPH_HDR_LENGTH(ipha);
2083 	uint16_t *up;
2084 	uint32_t ports;
2085 	ip_stack_t *ipst = ill->ill_ipst;
2086 
2087 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2088 	switch (ipha->ipha_protocol) {
2089 		case IPPROTO_TCP:
2090 		{
2091 			tcph_t *tcph;
2092 
2093 			/* do a reverse lookup */
2094 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2095 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2096 			    TCPS_LISTEN, ipst);
2097 			break;
2098 		}
2099 		case IPPROTO_UDP:
2100 		{
2101 			uint32_t dstport, srcport;
2102 
2103 			((uint16_t *)&ports)[0] = up[1];
2104 			((uint16_t *)&ports)[1] = up[0];
2105 
2106 			/* Extract ports in net byte order */
2107 			dstport = htons(ntohl(ports) & 0xFFFF);
2108 			srcport = htons(ntohl(ports) >> 16);
2109 
2110 			connfp = &ipst->ips_ipcl_udp_fanout[
2111 			    IPCL_UDP_HASH(dstport, ipst)];
2112 			mutex_enter(&connfp->connf_lock);
2113 			connp = connfp->connf_head;
2114 
2115 			/* do a reverse lookup */
2116 			while ((connp != NULL) &&
2117 			    (!IPCL_UDP_MATCH(connp, dstport,
2118 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2119 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2120 				connp = connp->conn_next;
2121 			}
2122 			if (connp != NULL)
2123 				CONN_INC_REF(connp);
2124 			mutex_exit(&connfp->connf_lock);
2125 			break;
2126 		}
2127 		case IPPROTO_SCTP:
2128 		{
2129 			in6_addr_t map_src, map_dst;
2130 
2131 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2132 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2133 			((uint16_t *)&ports)[0] = up[1];
2134 			((uint16_t *)&ports)[1] = up[0];
2135 
2136 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2137 			    zoneid, ipst->ips_netstack->netstack_sctp);
2138 			if (connp == NULL) {
2139 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2140 				    zoneid, ports, ipha, ipst);
2141 			} else {
2142 				CONN_INC_REF(connp);
2143 				SCTP_REFRELE(CONN2SCTP(connp));
2144 			}
2145 			break;
2146 		}
2147 		default:
2148 		{
2149 			ipha_t ripha;
2150 
2151 			ripha.ipha_src = ipha->ipha_dst;
2152 			ripha.ipha_dst = ipha->ipha_src;
2153 			ripha.ipha_protocol = ipha->ipha_protocol;
2154 
2155 			connfp = &ipst->ips_ipcl_proto_fanout[
2156 			    ipha->ipha_protocol];
2157 			mutex_enter(&connfp->connf_lock);
2158 			connp = connfp->connf_head;
2159 			for (connp = connfp->connf_head; connp != NULL;
2160 			    connp = connp->conn_next) {
2161 				if (IPCL_PROTO_MATCH(connp,
2162 				    ipha->ipha_protocol, &ripha, ill,
2163 				    0, zoneid)) {
2164 					CONN_INC_REF(connp);
2165 					break;
2166 				}
2167 			}
2168 			mutex_exit(&connfp->connf_lock);
2169 		}
2170 	}
2171 	if (connp != NULL) {
2172 		if (connp->conn_nexthop_set)
2173 			nexthop_addr = connp->conn_nexthop_v4;
2174 		CONN_DEC_REF(connp);
2175 	}
2176 	return (nexthop_addr);
2177 }
2178 
2179 /* Table from RFC 1191 */
2180 static int icmp_frag_size_table[] =
2181 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2182 
2183 /*
2184  * Process received ICMP Packet too big.
2185  * After updating any IRE it does the fanout to any matching transport streams.
2186  * Assumes the message has been pulled up till the IP header that caused
2187  * the error.
2188  *
2189  * Returns B_FALSE on failure and B_TRUE on success.
2190  */
2191 static boolean_t
2192 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2193     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2194     ip_stack_t *ipst)
2195 {
2196 	ire_t	*ire, *first_ire;
2197 	int	mtu, orig_mtu;
2198 	int	hdr_length;
2199 	ipaddr_t nexthop_addr;
2200 	boolean_t disable_pmtud;
2201 
2202 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2203 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2204 	ASSERT(ill != NULL);
2205 
2206 	hdr_length = IPH_HDR_LENGTH(ipha);
2207 
2208 	/* Drop if the original packet contained a source route */
2209 	if (ip_source_route_included(ipha)) {
2210 		return (B_FALSE);
2211 	}
2212 	/*
2213 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2214 	 * header.
2215 	 */
2216 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2217 	    mp->b_wptr) {
2218 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2219 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2220 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2221 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2222 			return (B_FALSE);
2223 		}
2224 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2225 		ipha = (ipha_t *)&icmph[1];
2226 	}
2227 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2228 	if (nexthop_addr != INADDR_ANY) {
2229 		/* nexthop set */
2230 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2231 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2232 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2233 	} else {
2234 		/* nexthop not set */
2235 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2236 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2237 	}
2238 
2239 	if (!first_ire) {
2240 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2241 		    ntohl(ipha->ipha_dst)));
2242 		return (B_FALSE);
2243 	}
2244 
2245 	/* Check for MTU discovery advice as described in RFC 1191 */
2246 	mtu = ntohs(icmph->icmph_du_mtu);
2247 	orig_mtu = mtu;
2248 	disable_pmtud = B_FALSE;
2249 
2250 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2251 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2252 	    ire = ire->ire_next) {
2253 		/*
2254 		 * Look for the connection to which this ICMP message is
2255 		 * directed. If it has the IP_NEXTHOP option set, then the
2256 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2257 		 * option. Else the search is limited to regular IREs.
2258 		 */
2259 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2260 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2261 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2262 		    (nexthop_addr != INADDR_ANY)))
2263 			continue;
2264 
2265 		mutex_enter(&ire->ire_lock);
2266 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2267 			uint32_t length;
2268 			int	i;
2269 
2270 			/*
2271 			 * Use the table from RFC 1191 to figure out
2272 			 * the next "plateau" based on the length in
2273 			 * the original IP packet.
2274 			 */
2275 			length = ntohs(ipha->ipha_length);
2276 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2277 			    uint32_t, length);
2278 			if (ire->ire_max_frag <= length &&
2279 			    ire->ire_max_frag >= length - hdr_length) {
2280 				/*
2281 				 * Handle broken BSD 4.2 systems that
2282 				 * return the wrong iph_length in ICMP
2283 				 * errors.
2284 				 */
2285 				length -= hdr_length;
2286 			}
2287 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2288 				if (length > icmp_frag_size_table[i])
2289 					break;
2290 			}
2291 			if (i == A_CNT(icmp_frag_size_table)) {
2292 				/* Smaller than 68! */
2293 				disable_pmtud = B_TRUE;
2294 				mtu = ipst->ips_ip_pmtu_min;
2295 			} else {
2296 				mtu = icmp_frag_size_table[i];
2297 				if (mtu < ipst->ips_ip_pmtu_min) {
2298 					mtu = ipst->ips_ip_pmtu_min;
2299 					disable_pmtud = B_TRUE;
2300 				}
2301 			}
2302 			/* Fool the ULP into believing our guessed PMTU. */
2303 			icmph->icmph_du_zero = 0;
2304 			icmph->icmph_du_mtu = htons(mtu);
2305 		}
2306 		if (disable_pmtud)
2307 			ire->ire_frag_flag = 0;
2308 		/* Reduce the IRE max frag value as advised. */
2309 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2310 		mutex_exit(&ire->ire_lock);
2311 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2312 		    ire, int, orig_mtu, int, mtu);
2313 	}
2314 	rw_exit(&first_ire->ire_bucket->irb_lock);
2315 	ire_refrele(first_ire);
2316 	return (B_TRUE);
2317 }
2318 
2319 /*
2320  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2321  * calls this function.
2322  */
2323 static mblk_t *
2324 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2325 {
2326 	ipha_t *ipha;
2327 	icmph_t *icmph;
2328 	ipha_t *in_ipha;
2329 	int length;
2330 
2331 	ASSERT(mp->b_datap->db_type == M_DATA);
2332 
2333 	/*
2334 	 * For Self-encapsulated packets, we added an extra IP header
2335 	 * without the options. Inner IP header is the one from which
2336 	 * the outer IP header was formed. Thus, we need to remove the
2337 	 * outer IP header. To do this, we pullup the whole message
2338 	 * and overlay whatever follows the outer IP header over the
2339 	 * outer IP header.
2340 	 */
2341 
2342 	if (!pullupmsg(mp, -1))
2343 		return (NULL);
2344 
2345 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2346 	ipha = (ipha_t *)&icmph[1];
2347 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2348 
2349 	/*
2350 	 * The length that we want to overlay is following the inner
2351 	 * IP header. Subtracting the IP header + icmp header + outer
2352 	 * IP header's length should give us the length that we want to
2353 	 * overlay.
2354 	 */
2355 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2356 	    hdr_length;
2357 	/*
2358 	 * Overlay whatever follows the inner header over the
2359 	 * outer header.
2360 	 */
2361 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2362 
2363 	/* Set the wptr to account for the outer header */
2364 	mp->b_wptr -= hdr_length;
2365 	return (mp);
2366 }
2367 
2368 /*
2369  * Try to pass the ICMP message upstream in case the ULP cares.
2370  *
2371  * If the packet that caused the ICMP error is secure, we send
2372  * it to AH/ESP to make sure that the attached packet has a
2373  * valid association. ipha in the code below points to the
2374  * IP header of the packet that caused the error.
2375  *
2376  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2377  * in the context of IPsec. Normally we tell the upper layer
2378  * whenever we send the ire (including ip_bind), the IPsec header
2379  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2380  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2381  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2382  * same thing. As TCP has the IPsec options size that needs to be
2383  * adjusted, we just pass the MTU unchanged.
2384  *
2385  * IFN could have been generated locally or by some router.
2386  *
2387  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2388  *	    This happens because IP adjusted its value of MTU on an
2389  *	    earlier IFN message and could not tell the upper layer,
2390  *	    the new adjusted value of MTU e.g. Packet was encrypted
2391  *	    or there was not enough information to fanout to upper
2392  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2393  *	    generates the IFN, where IPsec processing has *not* been
2394  *	    done.
2395  *
2396  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2397  *	    could have generated this. This happens because ire_max_frag
2398  *	    value in IP was set to a new value, while the IPsec processing
2399  *	    was being done and after we made the fragmentation check in
2400  *	    ip_wput_ire. Thus on return from IPsec processing,
2401  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2402  *	    and generates the IFN. As IPsec processing is over, we fanout
2403  *	    to AH/ESP to remove the header.
2404  *
2405  *	    In both these cases, ipsec_in_loopback will be set indicating
2406  *	    that IFN was generated locally.
2407  *
2408  * ROUTER : IFN could be secure or non-secure.
2409  *
2410  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2411  *	      packet in error has AH/ESP headers to validate the AH/ESP
2412  *	      headers. AH/ESP will verify whether there is a valid SA or
2413  *	      not and send it back. We will fanout again if we have more
2414  *	      data in the packet.
2415  *
2416  *	      If the packet in error does not have AH/ESP, we handle it
2417  *	      like any other case.
2418  *
2419  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2420  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2421  *	      for validation. AH/ESP will verify whether there is a
2422  *	      valid SA or not and send it back. We will fanout again if
2423  *	      we have more data in the packet.
2424  *
2425  *	      If the packet in error does not have AH/ESP, we handle it
2426  *	      like any other case.
2427  */
2428 static void
2429 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2430     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2431     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2432     zoneid_t zoneid)
2433 {
2434 	uint16_t *up;	/* Pointer to ports in ULP header */
2435 	uint32_t ports;	/* reversed ports for fanout */
2436 	ipha_t ripha;	/* With reversed addresses */
2437 	mblk_t *first_mp;
2438 	ipsec_in_t *ii;
2439 	tcph_t	*tcph;
2440 	conn_t	*connp;
2441 	ip_stack_t *ipst;
2442 
2443 	ASSERT(ill != NULL);
2444 
2445 	ASSERT(recv_ill != NULL);
2446 	ipst = recv_ill->ill_ipst;
2447 
2448 	first_mp = mp;
2449 	if (mctl_present) {
2450 		mp = first_mp->b_cont;
2451 		ASSERT(mp != NULL);
2452 
2453 		ii = (ipsec_in_t *)first_mp->b_rptr;
2454 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2455 	} else {
2456 		ii = NULL;
2457 	}
2458 
2459 	switch (ipha->ipha_protocol) {
2460 	case IPPROTO_UDP:
2461 		/*
2462 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2463 		 * transport header.
2464 		 */
2465 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2466 		    mp->b_wptr) {
2467 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2468 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2469 				goto discard_pkt;
2470 			}
2471 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2472 			ipha = (ipha_t *)&icmph[1];
2473 		}
2474 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2475 
2476 		/*
2477 		 * Attempt to find a client stream based on port.
2478 		 * Note that we do a reverse lookup since the header is
2479 		 * in the form we sent it out.
2480 		 * The ripha header is only used for the IP_UDP_MATCH and we
2481 		 * only set the src and dst addresses and protocol.
2482 		 */
2483 		ripha.ipha_src = ipha->ipha_dst;
2484 		ripha.ipha_dst = ipha->ipha_src;
2485 		ripha.ipha_protocol = ipha->ipha_protocol;
2486 		((uint16_t *)&ports)[0] = up[1];
2487 		((uint16_t *)&ports)[1] = up[0];
2488 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2489 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2490 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2491 		    icmph->icmph_type, icmph->icmph_code));
2492 
2493 		/* Have to change db_type after any pullupmsg */
2494 		DB_TYPE(mp) = M_CTL;
2495 
2496 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2497 		    mctl_present, ip_policy, recv_ill, zoneid);
2498 		return;
2499 
2500 	case IPPROTO_TCP:
2501 		/*
2502 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2503 		 * transport header.
2504 		 */
2505 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2506 		    mp->b_wptr) {
2507 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2508 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2509 				goto discard_pkt;
2510 			}
2511 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2512 			ipha = (ipha_t *)&icmph[1];
2513 		}
2514 		/*
2515 		 * Find a TCP client stream for this packet.
2516 		 * Note that we do a reverse lookup since the header is
2517 		 * in the form we sent it out.
2518 		 */
2519 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2520 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2521 		    ipst);
2522 		if (connp == NULL)
2523 			goto discard_pkt;
2524 
2525 		/* Have to change db_type after any pullupmsg */
2526 		DB_TYPE(mp) = M_CTL;
2527 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2528 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2529 		return;
2530 
2531 	case IPPROTO_SCTP:
2532 		/*
2533 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2534 		 * transport header.
2535 		 */
2536 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2537 		    mp->b_wptr) {
2538 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2539 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2540 				goto discard_pkt;
2541 			}
2542 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2543 			ipha = (ipha_t *)&icmph[1];
2544 		}
2545 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2546 		/*
2547 		 * Find a SCTP client stream for this packet.
2548 		 * Note that we do a reverse lookup since the header is
2549 		 * in the form we sent it out.
2550 		 * The ripha header is only used for the matching and we
2551 		 * only set the src and dst addresses, protocol, and version.
2552 		 */
2553 		ripha.ipha_src = ipha->ipha_dst;
2554 		ripha.ipha_dst = ipha->ipha_src;
2555 		ripha.ipha_protocol = ipha->ipha_protocol;
2556 		ripha.ipha_version_and_hdr_length =
2557 		    ipha->ipha_version_and_hdr_length;
2558 		((uint16_t *)&ports)[0] = up[1];
2559 		((uint16_t *)&ports)[1] = up[0];
2560 
2561 		/* Have to change db_type after any pullupmsg */
2562 		DB_TYPE(mp) = M_CTL;
2563 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2564 		    mctl_present, ip_policy, zoneid);
2565 		return;
2566 
2567 	case IPPROTO_ESP:
2568 	case IPPROTO_AH: {
2569 		int ipsec_rc;
2570 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2571 
2572 		/*
2573 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2574 		 * We will re-use the IPSEC_IN if it is already present as
2575 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2576 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2577 		 * one and attach it in the front.
2578 		 */
2579 		if (ii != NULL) {
2580 			/*
2581 			 * ip_fanout_proto_again converts the ICMP errors
2582 			 * that come back from AH/ESP to M_DATA so that
2583 			 * if it is non-AH/ESP and we do a pullupmsg in
2584 			 * this function, it would work. Convert it back
2585 			 * to M_CTL before we send up as this is a ICMP
2586 			 * error. This could have been generated locally or
2587 			 * by some router. Validate the inner IPsec
2588 			 * headers.
2589 			 *
2590 			 * NOTE : ill_index is used by ip_fanout_proto_again
2591 			 * to locate the ill.
2592 			 */
2593 			ASSERT(ill != NULL);
2594 			ii->ipsec_in_ill_index =
2595 			    ill->ill_phyint->phyint_ifindex;
2596 			ii->ipsec_in_rill_index =
2597 			    recv_ill->ill_phyint->phyint_ifindex;
2598 			DB_TYPE(first_mp->b_cont) = M_CTL;
2599 		} else {
2600 			/*
2601 			 * IPSEC_IN is not present. We attach a ipsec_in
2602 			 * message and send up to IPsec for validating
2603 			 * and removing the IPsec headers. Clear
2604 			 * ipsec_in_secure so that when we return
2605 			 * from IPsec, we don't mistakenly think that this
2606 			 * is a secure packet came from the network.
2607 			 *
2608 			 * NOTE : ill_index is used by ip_fanout_proto_again
2609 			 * to locate the ill.
2610 			 */
2611 			ASSERT(first_mp == mp);
2612 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2613 			if (first_mp == NULL) {
2614 				freemsg(mp);
2615 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2616 				return;
2617 			}
2618 			ii = (ipsec_in_t *)first_mp->b_rptr;
2619 
2620 			/* This is not a secure packet */
2621 			ii->ipsec_in_secure = B_FALSE;
2622 			first_mp->b_cont = mp;
2623 			DB_TYPE(mp) = M_CTL;
2624 			ASSERT(ill != NULL);
2625 			ii->ipsec_in_ill_index =
2626 			    ill->ill_phyint->phyint_ifindex;
2627 			ii->ipsec_in_rill_index =
2628 			    recv_ill->ill_phyint->phyint_ifindex;
2629 		}
2630 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2631 
2632 		if (!ipsec_loaded(ipss)) {
2633 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2634 			return;
2635 		}
2636 
2637 		if (ipha->ipha_protocol == IPPROTO_ESP)
2638 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2639 		else
2640 			ipsec_rc = ipsecah_icmp_error(first_mp);
2641 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2642 			return;
2643 
2644 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2645 		return;
2646 	}
2647 	default:
2648 		/*
2649 		 * The ripha header is only used for the lookup and we
2650 		 * only set the src and dst addresses and protocol.
2651 		 */
2652 		ripha.ipha_src = ipha->ipha_dst;
2653 		ripha.ipha_dst = ipha->ipha_src;
2654 		ripha.ipha_protocol = ipha->ipha_protocol;
2655 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2656 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2657 		    ntohl(ipha->ipha_dst),
2658 		    icmph->icmph_type, icmph->icmph_code));
2659 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2660 			ipha_t *in_ipha;
2661 
2662 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2663 			    mp->b_wptr) {
2664 				if (!pullupmsg(mp, (uchar_t *)ipha +
2665 				    hdr_length + sizeof (ipha_t) -
2666 				    mp->b_rptr)) {
2667 					goto discard_pkt;
2668 				}
2669 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2670 				ipha = (ipha_t *)&icmph[1];
2671 			}
2672 			/*
2673 			 * Caller has verified that length has to be
2674 			 * at least the size of IP header.
2675 			 */
2676 			ASSERT(hdr_length >= sizeof (ipha_t));
2677 			/*
2678 			 * Check the sanity of the inner IP header like
2679 			 * we did for the outer header.
2680 			 */
2681 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2682 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2683 				goto discard_pkt;
2684 			}
2685 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2686 				goto discard_pkt;
2687 			}
2688 			/* Check for Self-encapsulated tunnels */
2689 			if (in_ipha->ipha_src == ipha->ipha_src &&
2690 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2691 
2692 				mp = icmp_inbound_self_encap_error(mp,
2693 				    iph_hdr_length, hdr_length);
2694 				if (mp == NULL)
2695 					goto discard_pkt;
2696 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2697 				ipha = (ipha_t *)&icmph[1];
2698 				hdr_length = IPH_HDR_LENGTH(ipha);
2699 				/*
2700 				 * The packet in error is self-encapsualted.
2701 				 * And we are finding it further encapsulated
2702 				 * which we could not have possibly generated.
2703 				 */
2704 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2705 					goto discard_pkt;
2706 				}
2707 				icmp_inbound_error_fanout(q, ill, first_mp,
2708 				    icmph, ipha, iph_hdr_length, hdr_length,
2709 				    mctl_present, ip_policy, recv_ill, zoneid);
2710 				return;
2711 			}
2712 		}
2713 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2714 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2715 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2716 		    ii != NULL &&
2717 		    ii->ipsec_in_loopback &&
2718 		    ii->ipsec_in_secure) {
2719 			/*
2720 			 * For IP tunnels that get a looped-back
2721 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2722 			 * reported new MTU to take into account the IPsec
2723 			 * headers protecting this configured tunnel.
2724 			 *
2725 			 * This allows the tunnel module (tun.c) to blindly
2726 			 * accept the MTU reported in an ICMP "too big"
2727 			 * message.
2728 			 *
2729 			 * Non-looped back ICMP messages will just be
2730 			 * handled by the security protocols (if needed),
2731 			 * and the first subsequent packet will hit this
2732 			 * path.
2733 			 */
2734 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2735 			    ipsec_in_extra_length(first_mp));
2736 		}
2737 		/* Have to change db_type after any pullupmsg */
2738 		DB_TYPE(mp) = M_CTL;
2739 
2740 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2741 		    ip_policy, recv_ill, zoneid);
2742 		return;
2743 	}
2744 	/* NOTREACHED */
2745 discard_pkt:
2746 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2747 drop_pkt:;
2748 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2749 	freemsg(first_mp);
2750 }
2751 
2752 /*
2753  * Common IP options parser.
2754  *
2755  * Setup routine: fill in *optp with options-parsing state, then
2756  * tail-call ipoptp_next to return the first option.
2757  */
2758 uint8_t
2759 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2760 {
2761 	uint32_t totallen; /* total length of all options */
2762 
2763 	totallen = ipha->ipha_version_and_hdr_length -
2764 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2765 	totallen <<= 2;
2766 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2767 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2768 	optp->ipoptp_flags = 0;
2769 	return (ipoptp_next(optp));
2770 }
2771 
2772 /*
2773  * Common IP options parser: extract next option.
2774  */
2775 uint8_t
2776 ipoptp_next(ipoptp_t *optp)
2777 {
2778 	uint8_t *end = optp->ipoptp_end;
2779 	uint8_t *cur = optp->ipoptp_next;
2780 	uint8_t opt, len, pointer;
2781 
2782 	/*
2783 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2784 	 * has been corrupted.
2785 	 */
2786 	ASSERT(cur <= end);
2787 
2788 	if (cur == end)
2789 		return (IPOPT_EOL);
2790 
2791 	opt = cur[IPOPT_OPTVAL];
2792 
2793 	/*
2794 	 * Skip any NOP options.
2795 	 */
2796 	while (opt == IPOPT_NOP) {
2797 		cur++;
2798 		if (cur == end)
2799 			return (IPOPT_EOL);
2800 		opt = cur[IPOPT_OPTVAL];
2801 	}
2802 
2803 	if (opt == IPOPT_EOL)
2804 		return (IPOPT_EOL);
2805 
2806 	/*
2807 	 * Option requiring a length.
2808 	 */
2809 	if ((cur + 1) >= end) {
2810 		optp->ipoptp_flags |= IPOPTP_ERROR;
2811 		return (IPOPT_EOL);
2812 	}
2813 	len = cur[IPOPT_OLEN];
2814 	if (len < 2) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 	optp->ipoptp_cur = cur;
2819 	optp->ipoptp_len = len;
2820 	optp->ipoptp_next = cur + len;
2821 	if (cur + len > end) {
2822 		optp->ipoptp_flags |= IPOPTP_ERROR;
2823 		return (IPOPT_EOL);
2824 	}
2825 
2826 	/*
2827 	 * For the options which require a pointer field, make sure
2828 	 * its there, and make sure it points to either something
2829 	 * inside this option, or the end of the option.
2830 	 */
2831 	switch (opt) {
2832 	case IPOPT_RR:
2833 	case IPOPT_TS:
2834 	case IPOPT_LSRR:
2835 	case IPOPT_SSRR:
2836 		if (len <= IPOPT_OFFSET) {
2837 			optp->ipoptp_flags |= IPOPTP_ERROR;
2838 			return (opt);
2839 		}
2840 		pointer = cur[IPOPT_OFFSET];
2841 		if (pointer - 1 > len) {
2842 			optp->ipoptp_flags |= IPOPTP_ERROR;
2843 			return (opt);
2844 		}
2845 		break;
2846 	}
2847 
2848 	/*
2849 	 * Sanity check the pointer field based on the type of the
2850 	 * option.
2851 	 */
2852 	switch (opt) {
2853 	case IPOPT_RR:
2854 	case IPOPT_SSRR:
2855 	case IPOPT_LSRR:
2856 		if (pointer < IPOPT_MINOFF_SR)
2857 			optp->ipoptp_flags |= IPOPTP_ERROR;
2858 		break;
2859 	case IPOPT_TS:
2860 		if (pointer < IPOPT_MINOFF_IT)
2861 			optp->ipoptp_flags |= IPOPTP_ERROR;
2862 		/*
2863 		 * Note that the Internet Timestamp option also
2864 		 * contains two four bit fields (the Overflow field,
2865 		 * and the Flag field), which follow the pointer
2866 		 * field.  We don't need to check that these fields
2867 		 * fall within the length of the option because this
2868 		 * was implicitely done above.  We've checked that the
2869 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2870 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2871 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2872 		 */
2873 		ASSERT(len > IPOPT_POS_OV_FLG);
2874 		break;
2875 	}
2876 
2877 	return (opt);
2878 }
2879 
2880 /*
2881  * Use the outgoing IP header to create an IP_OPTIONS option the way
2882  * it was passed down from the application.
2883  */
2884 int
2885 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2886 {
2887 	ipoptp_t	opts;
2888 	const uchar_t	*opt;
2889 	uint8_t		optval;
2890 	uint8_t		optlen;
2891 	uint32_t	len = 0;
2892 	uchar_t	*buf1 = buf;
2893 
2894 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2895 	len += IP_ADDR_LEN;
2896 	bzero(buf1, IP_ADDR_LEN);
2897 
2898 	/*
2899 	 * OK to cast away const here, as we don't store through the returned
2900 	 * opts.ipoptp_cur pointer.
2901 	 */
2902 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2903 	    optval != IPOPT_EOL;
2904 	    optval = ipoptp_next(&opts)) {
2905 		int	off;
2906 
2907 		opt = opts.ipoptp_cur;
2908 		optlen = opts.ipoptp_len;
2909 		switch (optval) {
2910 		case IPOPT_SSRR:
2911 		case IPOPT_LSRR:
2912 
2913 			/*
2914 			 * Insert ipha_dst as the first entry in the source
2915 			 * route and move down the entries on step.
2916 			 * The last entry gets placed at buf1.
2917 			 */
2918 			buf[IPOPT_OPTVAL] = optval;
2919 			buf[IPOPT_OLEN] = optlen;
2920 			buf[IPOPT_OFFSET] = optlen;
2921 
2922 			off = optlen - IP_ADDR_LEN;
2923 			if (off < 0) {
2924 				/* No entries in source route */
2925 				break;
2926 			}
2927 			/* Last entry in source route */
2928 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2929 			off -= IP_ADDR_LEN;
2930 
2931 			while (off > 0) {
2932 				bcopy(opt + off,
2933 				    buf + off + IP_ADDR_LEN,
2934 				    IP_ADDR_LEN);
2935 				off -= IP_ADDR_LEN;
2936 			}
2937 			/* ipha_dst into first slot */
2938 			bcopy(&ipha->ipha_dst,
2939 			    buf + off + IP_ADDR_LEN,
2940 			    IP_ADDR_LEN);
2941 			buf += optlen;
2942 			len += optlen;
2943 			break;
2944 
2945 		case IPOPT_COMSEC:
2946 		case IPOPT_SECURITY:
2947 			/* if passing up a label is not ok, then remove */
2948 			if (is_system_labeled())
2949 				break;
2950 			/* FALLTHROUGH */
2951 		default:
2952 			bcopy(opt, buf, optlen);
2953 			buf += optlen;
2954 			len += optlen;
2955 			break;
2956 		}
2957 	}
2958 done:
2959 	/* Pad the resulting options */
2960 	while (len & 0x3) {
2961 		*buf++ = IPOPT_EOL;
2962 		len++;
2963 	}
2964 	return (len);
2965 }
2966 
2967 /*
2968  * Update any record route or timestamp options to include this host.
2969  * Reverse any source route option.
2970  * This routine assumes that the options are well formed i.e. that they
2971  * have already been checked.
2972  */
2973 static void
2974 icmp_options_update(ipha_t *ipha)
2975 {
2976 	ipoptp_t	opts;
2977 	uchar_t		*opt;
2978 	uint8_t		optval;
2979 	ipaddr_t	src;		/* Our local address */
2980 	ipaddr_t	dst;
2981 
2982 	ip2dbg(("icmp_options_update\n"));
2983 	src = ipha->ipha_src;
2984 	dst = ipha->ipha_dst;
2985 
2986 	for (optval = ipoptp_first(&opts, ipha);
2987 	    optval != IPOPT_EOL;
2988 	    optval = ipoptp_next(&opts)) {
2989 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2990 		opt = opts.ipoptp_cur;
2991 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2992 		    optval, opts.ipoptp_len));
2993 		switch (optval) {
2994 			int off1, off2;
2995 		case IPOPT_SSRR:
2996 		case IPOPT_LSRR:
2997 			/*
2998 			 * Reverse the source route.  The first entry
2999 			 * should be the next to last one in the current
3000 			 * source route (the last entry is our address).
3001 			 * The last entry should be the final destination.
3002 			 */
3003 			off1 = IPOPT_MINOFF_SR - 1;
3004 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3005 			if (off2 < 0) {
3006 				/* No entries in source route */
3007 				ip1dbg((
3008 				    "icmp_options_update: bad src route\n"));
3009 				break;
3010 			}
3011 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3012 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3013 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3014 			off2 -= IP_ADDR_LEN;
3015 
3016 			while (off1 < off2) {
3017 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3018 				bcopy((char *)opt + off2, (char *)opt + off1,
3019 				    IP_ADDR_LEN);
3020 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3021 				off1 += IP_ADDR_LEN;
3022 				off2 -= IP_ADDR_LEN;
3023 			}
3024 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3025 			break;
3026 		}
3027 	}
3028 }
3029 
3030 /*
3031  * Process received ICMP Redirect messages.
3032  */
3033 static void
3034 icmp_redirect(ill_t *ill, mblk_t *mp)
3035 {
3036 	ipha_t	*ipha;
3037 	int	iph_hdr_length;
3038 	icmph_t	*icmph;
3039 	ipha_t	*ipha_err;
3040 	ire_t	*ire;
3041 	ire_t	*prev_ire;
3042 	ire_t	*save_ire;
3043 	ipaddr_t  src, dst, gateway;
3044 	iulp_t	ulp_info = { 0 };
3045 	int	error;
3046 	ip_stack_t *ipst;
3047 
3048 	ASSERT(ill != NULL);
3049 	ipst = ill->ill_ipst;
3050 
3051 	ipha = (ipha_t *)mp->b_rptr;
3052 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3053 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3054 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3055 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3056 		freemsg(mp);
3057 		return;
3058 	}
3059 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3060 	ipha_err = (ipha_t *)&icmph[1];
3061 	src = ipha->ipha_src;
3062 	dst = ipha_err->ipha_dst;
3063 	gateway = icmph->icmph_rd_gateway;
3064 	/* Make sure the new gateway is reachable somehow. */
3065 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3066 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3067 	/*
3068 	 * Make sure we had a route for the dest in question and that
3069 	 * that route was pointing to the old gateway (the source of the
3070 	 * redirect packet.)
3071 	 */
3072 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3073 	    NULL, MATCH_IRE_GW, ipst);
3074 	/*
3075 	 * Check that
3076 	 *	the redirect was not from ourselves
3077 	 *	the new gateway and the old gateway are directly reachable
3078 	 */
3079 	if (!prev_ire ||
3080 	    !ire ||
3081 	    ire->ire_type == IRE_LOCAL) {
3082 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3083 		freemsg(mp);
3084 		if (ire != NULL)
3085 			ire_refrele(ire);
3086 		if (prev_ire != NULL)
3087 			ire_refrele(prev_ire);
3088 		return;
3089 	}
3090 
3091 	/*
3092 	 * Should we use the old ULP info to create the new gateway?  From
3093 	 * a user's perspective, we should inherit the info so that it
3094 	 * is a "smooth" transition.  If we do not do that, then new
3095 	 * connections going thru the new gateway will have no route metrics,
3096 	 * which is counter-intuitive to user.  From a network point of
3097 	 * view, this may or may not make sense even though the new gateway
3098 	 * is still directly connected to us so the route metrics should not
3099 	 * change much.
3100 	 *
3101 	 * But if the old ire_uinfo is not initialized, we do another
3102 	 * recursive lookup on the dest using the new gateway.  There may
3103 	 * be a route to that.  If so, use it to initialize the redirect
3104 	 * route.
3105 	 */
3106 	if (prev_ire->ire_uinfo.iulp_set) {
3107 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3108 	} else {
3109 		ire_t *tmp_ire;
3110 		ire_t *sire;
3111 
3112 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3113 		    ALL_ZONES, 0, NULL,
3114 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3115 		    ipst);
3116 		if (sire != NULL) {
3117 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3118 			/*
3119 			 * If sire != NULL, ire_ftable_lookup() should not
3120 			 * return a NULL value.
3121 			 */
3122 			ASSERT(tmp_ire != NULL);
3123 			ire_refrele(tmp_ire);
3124 			ire_refrele(sire);
3125 		} else if (tmp_ire != NULL) {
3126 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3127 			    sizeof (iulp_t));
3128 			ire_refrele(tmp_ire);
3129 		}
3130 	}
3131 	if (prev_ire->ire_type == IRE_CACHE)
3132 		ire_delete(prev_ire);
3133 	ire_refrele(prev_ire);
3134 	/*
3135 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3136 	 * require TOS routing
3137 	 */
3138 	switch (icmph->icmph_code) {
3139 	case 0:
3140 	case 1:
3141 		/* TODO: TOS specificity for cases 2 and 3 */
3142 	case 2:
3143 	case 3:
3144 		break;
3145 	default:
3146 		freemsg(mp);
3147 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3148 		ire_refrele(ire);
3149 		return;
3150 	}
3151 	/*
3152 	 * Create a Route Association.  This will allow us to remember that
3153 	 * someone we believe told us to use the particular gateway.
3154 	 */
3155 	save_ire = ire;
3156 	ire = ire_create(
3157 	    (uchar_t *)&dst,			/* dest addr */
3158 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3159 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3160 	    (uchar_t *)&gateway,		/* gateway addr */
3161 	    &save_ire->ire_max_frag,		/* max frag */
3162 	    NULL,				/* no src nce */
3163 	    NULL,				/* no rfq */
3164 	    NULL,				/* no stq */
3165 	    IRE_HOST,
3166 	    NULL,				/* ipif */
3167 	    0,					/* cmask */
3168 	    0,					/* phandle */
3169 	    0,					/* ihandle */
3170 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3171 	    &ulp_info,
3172 	    NULL,				/* tsol_gc_t */
3173 	    NULL,				/* gcgrp */
3174 	    ipst);
3175 
3176 	if (ire == NULL) {
3177 		freemsg(mp);
3178 		ire_refrele(save_ire);
3179 		return;
3180 	}
3181 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3182 	ire_refrele(save_ire);
3183 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3184 
3185 	if (error == 0) {
3186 		ire_refrele(ire);		/* Held in ire_add_v4 */
3187 		/* tell routing sockets that we received a redirect */
3188 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3189 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3190 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3191 	}
3192 
3193 	/*
3194 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3195 	 * This together with the added IRE has the effect of
3196 	 * modifying an existing redirect.
3197 	 */
3198 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3199 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3200 	if (prev_ire != NULL) {
3201 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3202 			ire_delete(prev_ire);
3203 		ire_refrele(prev_ire);
3204 	}
3205 
3206 	freemsg(mp);
3207 }
3208 
3209 /*
3210  * Generate an ICMP parameter problem message.
3211  */
3212 static void
3213 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3214 	ip_stack_t *ipst)
3215 {
3216 	icmph_t	icmph;
3217 	boolean_t mctl_present;
3218 	mblk_t *first_mp;
3219 
3220 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3221 
3222 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3223 		if (mctl_present)
3224 			freeb(first_mp);
3225 		return;
3226 	}
3227 
3228 	bzero(&icmph, sizeof (icmph_t));
3229 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3230 	icmph.icmph_pp_ptr = ptr;
3231 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3232 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3233 	    ipst);
3234 }
3235 
3236 /*
3237  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3238  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3239  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3240  * an icmp error packet can be sent.
3241  * Assigns an appropriate source address to the packet. If ipha_dst is
3242  * one of our addresses use it for source. Otherwise pick a source based
3243  * on a route lookup back to ipha_src.
3244  * Note that ipha_src must be set here since the
3245  * packet is likely to arrive on an ill queue in ip_wput() which will
3246  * not set a source address.
3247  */
3248 static void
3249 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3250     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3251 {
3252 	ipaddr_t dst;
3253 	icmph_t	*icmph;
3254 	ipha_t	*ipha;
3255 	uint_t	len_needed;
3256 	size_t	msg_len;
3257 	mblk_t	*mp1;
3258 	ipaddr_t src;
3259 	ire_t	*ire;
3260 	mblk_t *ipsec_mp;
3261 	ipsec_out_t	*io = NULL;
3262 
3263 	if (mctl_present) {
3264 		/*
3265 		 * If it is :
3266 		 *
3267 		 * 1) a IPSEC_OUT, then this is caused by outbound
3268 		 *    datagram originating on this host. IPsec processing
3269 		 *    may or may not have been done. Refer to comments above
3270 		 *    icmp_inbound_error_fanout for details.
3271 		 *
3272 		 * 2) a IPSEC_IN if we are generating a icmp_message
3273 		 *    for an incoming datagram destined for us i.e called
3274 		 *    from ip_fanout_send_icmp.
3275 		 */
3276 		ipsec_info_t *in;
3277 		ipsec_mp = mp;
3278 		mp = ipsec_mp->b_cont;
3279 
3280 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3281 		ipha = (ipha_t *)mp->b_rptr;
3282 
3283 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3284 		    in->ipsec_info_type == IPSEC_IN);
3285 
3286 		if (in->ipsec_info_type == IPSEC_IN) {
3287 			/*
3288 			 * Convert the IPSEC_IN to IPSEC_OUT.
3289 			 */
3290 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3291 				BUMP_MIB(&ipst->ips_ip_mib,
3292 				    ipIfStatsOutDiscards);
3293 				return;
3294 			}
3295 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3296 		} else {
3297 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3298 			io = (ipsec_out_t *)in;
3299 			/*
3300 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3301 			 * ire lookup.
3302 			 */
3303 			io->ipsec_out_proc_begin = B_FALSE;
3304 		}
3305 		ASSERT(zoneid == io->ipsec_out_zoneid);
3306 		ASSERT(zoneid != ALL_ZONES);
3307 	} else {
3308 		/*
3309 		 * This is in clear. The icmp message we are building
3310 		 * here should go out in clear.
3311 		 *
3312 		 * Pardon the convolution of it all, but it's easier to
3313 		 * allocate a "use cleartext" IPSEC_IN message and convert
3314 		 * it than it is to allocate a new one.
3315 		 */
3316 		ipsec_in_t *ii;
3317 		ASSERT(DB_TYPE(mp) == M_DATA);
3318 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3319 		if (ipsec_mp == NULL) {
3320 			freemsg(mp);
3321 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3322 			return;
3323 		}
3324 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3325 
3326 		/* This is not a secure packet */
3327 		ii->ipsec_in_secure = B_FALSE;
3328 		/*
3329 		 * For trusted extensions using a shared IP address we can
3330 		 * send using any zoneid.
3331 		 */
3332 		if (zoneid == ALL_ZONES)
3333 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3334 		else
3335 			ii->ipsec_in_zoneid = zoneid;
3336 		ipsec_mp->b_cont = mp;
3337 		ipha = (ipha_t *)mp->b_rptr;
3338 		/*
3339 		 * Convert the IPSEC_IN to IPSEC_OUT.
3340 		 */
3341 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3342 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3343 			return;
3344 		}
3345 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3346 	}
3347 
3348 	/* Remember our eventual destination */
3349 	dst = ipha->ipha_src;
3350 
3351 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3352 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3353 	if (ire != NULL &&
3354 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3355 		src = ipha->ipha_dst;
3356 	} else {
3357 		if (ire != NULL)
3358 			ire_refrele(ire);
3359 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3360 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3361 		    ipst);
3362 		if (ire == NULL) {
3363 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3364 			freemsg(ipsec_mp);
3365 			return;
3366 		}
3367 		src = ire->ire_src_addr;
3368 	}
3369 
3370 	if (ire != NULL)
3371 		ire_refrele(ire);
3372 
3373 	/*
3374 	 * Check if we can send back more then 8 bytes in addition to
3375 	 * the IP header.  We try to send 64 bytes of data and the internal
3376 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3377 	 */
3378 	len_needed = IPH_HDR_LENGTH(ipha);
3379 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3380 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3381 
3382 		if (!pullupmsg(mp, -1)) {
3383 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3384 			freemsg(ipsec_mp);
3385 			return;
3386 		}
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3390 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3391 			    len_needed));
3392 		} else {
3393 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3394 
3395 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3396 			len_needed += ip_hdr_length_v6(mp, ip6h);
3397 		}
3398 	}
3399 	len_needed += ipst->ips_ip_icmp_return;
3400 	msg_len = msgdsize(mp);
3401 	if (msg_len > len_needed) {
3402 		(void) adjmsg(mp, len_needed - msg_len);
3403 		msg_len = len_needed;
3404 	}
3405 	/* Make sure we propagate the cred/label for TX */
3406 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3407 	if (mp1 == NULL) {
3408 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3409 		freemsg(ipsec_mp);
3410 		return;
3411 	}
3412 	mp1->b_cont = mp;
3413 	mp = mp1;
3414 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3415 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3416 	    io->ipsec_out_type == IPSEC_OUT);
3417 	ipsec_mp->b_cont = mp;
3418 
3419 	/*
3420 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3421 	 * node generates be accepted in peace by all on-host destinations.
3422 	 * If we do NOT assume that all on-host destinations trust
3423 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3424 	 * (Look for ipsec_out_icmp_loopback).
3425 	 */
3426 	io->ipsec_out_icmp_loopback = B_TRUE;
3427 
3428 	ipha = (ipha_t *)mp->b_rptr;
3429 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3430 	*ipha = icmp_ipha;
3431 	ipha->ipha_src = src;
3432 	ipha->ipha_dst = dst;
3433 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3434 	msg_len += sizeof (icmp_ipha) + len;
3435 	if (msg_len > IP_MAXPACKET) {
3436 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3437 		msg_len = IP_MAXPACKET;
3438 	}
3439 	ipha->ipha_length = htons((uint16_t)msg_len);
3440 	icmph = (icmph_t *)&ipha[1];
3441 	bcopy(stuff, icmph, len);
3442 	icmph->icmph_checksum = 0;
3443 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3444 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3445 	put(q, ipsec_mp);
3446 }
3447 
3448 /*
3449  * Determine if an ICMP error packet can be sent given the rate limit.
3450  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3451  * in milliseconds) and a burst size. Burst size number of packets can
3452  * be sent arbitrarely closely spaced.
3453  * The state is tracked using two variables to implement an approximate
3454  * token bucket filter:
3455  *	icmp_pkt_err_last - lbolt value when the last burst started
3456  *	icmp_pkt_err_sent - number of packets sent in current burst
3457  */
3458 boolean_t
3459 icmp_err_rate_limit(ip_stack_t *ipst)
3460 {
3461 	clock_t now = TICK_TO_MSEC(lbolt);
3462 	uint_t refilled; /* Number of packets refilled in tbf since last */
3463 	/* Guard against changes by loading into local variable */
3464 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3465 
3466 	if (err_interval == 0)
3467 		return (B_FALSE);
3468 
3469 	if (ipst->ips_icmp_pkt_err_last > now) {
3470 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3471 		ipst->ips_icmp_pkt_err_last = 0;
3472 		ipst->ips_icmp_pkt_err_sent = 0;
3473 	}
3474 	/*
3475 	 * If we are in a burst update the token bucket filter.
3476 	 * Update the "last" time to be close to "now" but make sure
3477 	 * we don't loose precision.
3478 	 */
3479 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3480 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3481 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3482 			ipst->ips_icmp_pkt_err_sent = 0;
3483 		} else {
3484 			ipst->ips_icmp_pkt_err_sent -= refilled;
3485 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3486 		}
3487 	}
3488 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3489 		/* Start of new burst */
3490 		ipst->ips_icmp_pkt_err_last = now;
3491 	}
3492 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3493 		ipst->ips_icmp_pkt_err_sent++;
3494 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3495 		    ipst->ips_icmp_pkt_err_sent));
3496 		return (B_FALSE);
3497 	}
3498 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3499 	return (B_TRUE);
3500 }
3501 
3502 /*
3503  * Check if it is ok to send an IPv4 ICMP error packet in
3504  * response to the IPv4 packet in mp.
3505  * Free the message and return null if no
3506  * ICMP error packet should be sent.
3507  */
3508 static mblk_t *
3509 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3510 {
3511 	icmph_t	*icmph;
3512 	ipha_t	*ipha;
3513 	uint_t	len_needed;
3514 	ire_t	*src_ire;
3515 	ire_t	*dst_ire;
3516 
3517 	if (!mp)
3518 		return (NULL);
3519 	ipha = (ipha_t *)mp->b_rptr;
3520 	if (ip_csum_hdr(ipha)) {
3521 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3522 		freemsg(mp);
3523 		return (NULL);
3524 	}
3525 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3526 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3527 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3528 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3529 	if (src_ire != NULL || dst_ire != NULL ||
3530 	    CLASSD(ipha->ipha_dst) ||
3531 	    CLASSD(ipha->ipha_src) ||
3532 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3533 		/* Note: only errors to the fragment with offset 0 */
3534 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3535 		freemsg(mp);
3536 		if (src_ire != NULL)
3537 			ire_refrele(src_ire);
3538 		if (dst_ire != NULL)
3539 			ire_refrele(dst_ire);
3540 		return (NULL);
3541 	}
3542 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3543 		/*
3544 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3545 		 * errors in response to any ICMP errors.
3546 		 */
3547 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3548 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3549 			if (!pullupmsg(mp, len_needed)) {
3550 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3551 				freemsg(mp);
3552 				return (NULL);
3553 			}
3554 			ipha = (ipha_t *)mp->b_rptr;
3555 		}
3556 		icmph = (icmph_t *)
3557 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3558 		switch (icmph->icmph_type) {
3559 		case ICMP_DEST_UNREACHABLE:
3560 		case ICMP_SOURCE_QUENCH:
3561 		case ICMP_TIME_EXCEEDED:
3562 		case ICMP_PARAM_PROBLEM:
3563 		case ICMP_REDIRECT:
3564 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3565 			freemsg(mp);
3566 			return (NULL);
3567 		default:
3568 			break;
3569 		}
3570 	}
3571 	/*
3572 	 * If this is a labeled system, then check to see if we're allowed to
3573 	 * send a response to this particular sender.  If not, then just drop.
3574 	 */
3575 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3576 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3577 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3578 		freemsg(mp);
3579 		return (NULL);
3580 	}
3581 	if (icmp_err_rate_limit(ipst)) {
3582 		/*
3583 		 * Only send ICMP error packets every so often.
3584 		 * This should be done on a per port/source basis,
3585 		 * but for now this will suffice.
3586 		 */
3587 		freemsg(mp);
3588 		return (NULL);
3589 	}
3590 	return (mp);
3591 }
3592 
3593 /*
3594  * Generate an ICMP redirect message.
3595  */
3596 static void
3597 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3598 {
3599 	icmph_t	icmph;
3600 
3601 	/*
3602 	 * We are called from ip_rput where we could
3603 	 * not have attached an IPSEC_IN.
3604 	 */
3605 	ASSERT(mp->b_datap->db_type == M_DATA);
3606 
3607 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3608 		return;
3609 	}
3610 
3611 	bzero(&icmph, sizeof (icmph_t));
3612 	icmph.icmph_type = ICMP_REDIRECT;
3613 	icmph.icmph_code = 1;
3614 	icmph.icmph_rd_gateway = gateway;
3615 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3616 	/* Redirects sent by router, and router is global zone */
3617 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3618 }
3619 
3620 /*
3621  * Generate an ICMP time exceeded message.
3622  */
3623 void
3624 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3625     ip_stack_t *ipst)
3626 {
3627 	icmph_t	icmph;
3628 	boolean_t mctl_present;
3629 	mblk_t *first_mp;
3630 
3631 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3632 
3633 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3634 		if (mctl_present)
3635 			freeb(first_mp);
3636 		return;
3637 	}
3638 
3639 	bzero(&icmph, sizeof (icmph_t));
3640 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3641 	icmph.icmph_code = code;
3642 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3643 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3644 	    ipst);
3645 }
3646 
3647 /*
3648  * Generate an ICMP unreachable message.
3649  */
3650 void
3651 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3652     ip_stack_t *ipst)
3653 {
3654 	icmph_t	icmph;
3655 	mblk_t *first_mp;
3656 	boolean_t mctl_present;
3657 
3658 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3659 
3660 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3661 		if (mctl_present)
3662 			freeb(first_mp);
3663 		return;
3664 	}
3665 
3666 	bzero(&icmph, sizeof (icmph_t));
3667 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3668 	icmph.icmph_code = code;
3669 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3670 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3671 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3672 	    zoneid, ipst);
3673 }
3674 
3675 /*
3676  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3677  * duplicate.  As long as someone else holds the address, the interface will
3678  * stay down.  When that conflict goes away, the interface is brought back up.
3679  * This is done so that accidental shutdowns of addresses aren't made
3680  * permanent.  Your server will recover from a failure.
3681  *
3682  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3683  * user space process (dhcpagent).
3684  *
3685  * Recovery completes if ARP reports that the address is now ours (via
3686  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3687  *
3688  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3689  */
3690 static void
3691 ipif_dup_recovery(void *arg)
3692 {
3693 	ipif_t *ipif = arg;
3694 	ill_t *ill = ipif->ipif_ill;
3695 	mblk_t *arp_add_mp;
3696 	mblk_t *arp_del_mp;
3697 	ip_stack_t *ipst = ill->ill_ipst;
3698 
3699 	ipif->ipif_recovery_id = 0;
3700 
3701 	/*
3702 	 * No lock needed for moving or condemned check, as this is just an
3703 	 * optimization.
3704 	 */
3705 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3706 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3707 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3708 		/* No reason to try to bring this address back. */
3709 		return;
3710 	}
3711 
3712 	/* ACE_F_UNVERIFIED restarts DAD */
3713 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3714 		goto alloc_fail;
3715 
3716 	if (ipif->ipif_arp_del_mp == NULL) {
3717 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3718 			goto alloc_fail;
3719 		ipif->ipif_arp_del_mp = arp_del_mp;
3720 	}
3721 
3722 	putnext(ill->ill_rq, arp_add_mp);
3723 	return;
3724 
3725 alloc_fail:
3726 	/*
3727 	 * On allocation failure, just restart the timer.  Note that the ipif
3728 	 * is down here, so no other thread could be trying to start a recovery
3729 	 * timer.  The ill_lock protects the condemned flag and the recovery
3730 	 * timer ID.
3731 	 */
3732 	freemsg(arp_add_mp);
3733 	mutex_enter(&ill->ill_lock);
3734 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3735 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3736 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3737 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3738 	}
3739 	mutex_exit(&ill->ill_lock);
3740 }
3741 
3742 /*
3743  * This is for exclusive changes due to ARP.  Either tear down an interface due
3744  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3745  */
3746 /* ARGSUSED */
3747 static void
3748 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3749 {
3750 	ill_t	*ill = rq->q_ptr;
3751 	arh_t *arh;
3752 	ipaddr_t src;
3753 	ipif_t	*ipif;
3754 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3755 	char hbuf[MAC_STR_LEN];
3756 	char sbuf[INET_ADDRSTRLEN];
3757 	const char *failtype;
3758 	boolean_t bring_up;
3759 	ip_stack_t *ipst = ill->ill_ipst;
3760 
3761 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3762 	case AR_CN_READY:
3763 		failtype = NULL;
3764 		bring_up = B_TRUE;
3765 		break;
3766 	case AR_CN_FAILED:
3767 		failtype = "in use";
3768 		bring_up = B_FALSE;
3769 		break;
3770 	default:
3771 		failtype = "claimed";
3772 		bring_up = B_FALSE;
3773 		break;
3774 	}
3775 
3776 	arh = (arh_t *)mp->b_cont->b_rptr;
3777 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3778 
3779 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3780 	    sizeof (hbuf));
3781 	(void) ip_dot_addr(src, sbuf);
3782 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3783 
3784 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3785 		    ipif->ipif_lcl_addr != src) {
3786 			continue;
3787 		}
3788 
3789 		/*
3790 		 * If we failed on a recovery probe, then restart the timer to
3791 		 * try again later.
3792 		 */
3793 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3794 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3795 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3796 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3797 		    ipst->ips_ip_dup_recovery > 0 &&
3798 		    ipif->ipif_recovery_id == 0) {
3799 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3800 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3801 			continue;
3802 		}
3803 
3804 		/*
3805 		 * If what we're trying to do has already been done, then do
3806 		 * nothing.
3807 		 */
3808 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3809 			continue;
3810 
3811 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3812 
3813 		if (failtype == NULL) {
3814 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3815 			    ibuf);
3816 		} else {
3817 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3818 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3819 		}
3820 
3821 		if (bring_up) {
3822 			ASSERT(ill->ill_dl_up);
3823 			/*
3824 			 * Free up the ARP delete message so we can allocate
3825 			 * a fresh one through the normal path.
3826 			 */
3827 			freemsg(ipif->ipif_arp_del_mp);
3828 			ipif->ipif_arp_del_mp = NULL;
3829 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3830 			    EINPROGRESS) {
3831 				ipif->ipif_addr_ready = 1;
3832 				(void) ipif_up_done(ipif);
3833 				ASSERT(ill->ill_move_ipif == NULL);
3834 			}
3835 			continue;
3836 		}
3837 
3838 		mutex_enter(&ill->ill_lock);
3839 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3840 		ipif->ipif_flags |= IPIF_DUPLICATE;
3841 		ill->ill_ipif_dup_count++;
3842 		mutex_exit(&ill->ill_lock);
3843 		/*
3844 		 * Already exclusive on the ill; no need to handle deferred
3845 		 * processing here.
3846 		 */
3847 		(void) ipif_down(ipif, NULL, NULL);
3848 		ipif_down_tail(ipif);
3849 		mutex_enter(&ill->ill_lock);
3850 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3851 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3852 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3853 		    ipst->ips_ip_dup_recovery > 0) {
3854 			ASSERT(ipif->ipif_recovery_id == 0);
3855 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3856 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3857 		}
3858 		mutex_exit(&ill->ill_lock);
3859 	}
3860 	freemsg(mp);
3861 }
3862 
3863 /* ARGSUSED */
3864 static void
3865 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3866 {
3867 	ill_t	*ill = rq->q_ptr;
3868 	arh_t *arh;
3869 	ipaddr_t src;
3870 	ipif_t	*ipif;
3871 
3872 	arh = (arh_t *)mp->b_cont->b_rptr;
3873 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3874 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3875 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3876 			(void) ipif_resolver_up(ipif, Res_act_defend);
3877 	}
3878 	freemsg(mp);
3879 }
3880 
3881 /*
3882  * News from ARP.  ARP sends notification of interesting events down
3883  * to its clients using M_CTL messages with the interesting ARP packet
3884  * attached via b_cont.
3885  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3886  * queue as opposed to ARP sending the message to all the clients, i.e. all
3887  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3888  * table if a cache IRE is found to delete all the entries for the address in
3889  * the packet.
3890  */
3891 static void
3892 ip_arp_news(queue_t *q, mblk_t *mp)
3893 {
3894 	arcn_t		*arcn;
3895 	arh_t		*arh;
3896 	ire_t		*ire = NULL;
3897 	char		hbuf[MAC_STR_LEN];
3898 	char		sbuf[INET_ADDRSTRLEN];
3899 	ipaddr_t	src;
3900 	in6_addr_t	v6src;
3901 	boolean_t	isv6 = B_FALSE;
3902 	ipif_t		*ipif;
3903 	ill_t		*ill;
3904 	ip_stack_t	*ipst;
3905 
3906 	if (CONN_Q(q)) {
3907 		conn_t *connp = Q_TO_CONN(q);
3908 
3909 		ipst = connp->conn_netstack->netstack_ip;
3910 	} else {
3911 		ill_t *ill = (ill_t *)q->q_ptr;
3912 
3913 		ipst = ill->ill_ipst;
3914 	}
3915 
3916 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3917 		if (q->q_next) {
3918 			putnext(q, mp);
3919 		} else
3920 			freemsg(mp);
3921 		return;
3922 	}
3923 	arh = (arh_t *)mp->b_cont->b_rptr;
3924 	/* Is it one we are interested in? */
3925 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3926 		isv6 = B_TRUE;
3927 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3928 		    IPV6_ADDR_LEN);
3929 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3930 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3931 		    IP_ADDR_LEN);
3932 	} else {
3933 		freemsg(mp);
3934 		return;
3935 	}
3936 
3937 	ill = q->q_ptr;
3938 
3939 	arcn = (arcn_t *)mp->b_rptr;
3940 	switch (arcn->arcn_code) {
3941 	case AR_CN_BOGON:
3942 		/*
3943 		 * Someone is sending ARP packets with a source protocol
3944 		 * address that we have published and for which we believe our
3945 		 * entry is authoritative and (when ill_arp_extend is set)
3946 		 * verified to be unique on the network.
3947 		 *
3948 		 * The ARP module internally handles the cases where the sender
3949 		 * is just probing (for DAD) and where the hardware address of
3950 		 * a non-authoritative entry has changed.  Thus, these are the
3951 		 * real conflicts, and we have to do resolution.
3952 		 *
3953 		 * We back away quickly from the address if it's from DHCP or
3954 		 * otherwise temporary and hasn't been used recently (or at
3955 		 * all).  We'd like to include "deprecated" addresses here as
3956 		 * well (as there's no real reason to defend something we're
3957 		 * discarding), but IPMP "reuses" this flag to mean something
3958 		 * other than the standard meaning.
3959 		 *
3960 		 * If the ARP module above is not extended (meaning that it
3961 		 * doesn't know how to defend the address), then we just log
3962 		 * the problem as we always did and continue on.  It's not
3963 		 * right, but there's little else we can do, and those old ATM
3964 		 * users are going away anyway.
3965 		 */
3966 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3967 		    hbuf, sizeof (hbuf));
3968 		(void) ip_dot_addr(src, sbuf);
3969 		if (isv6) {
3970 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3971 			    ipst);
3972 		} else {
3973 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3974 		}
3975 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3976 			uint32_t now;
3977 			uint32_t maxage;
3978 			clock_t lused;
3979 			uint_t maxdefense;
3980 			uint_t defs;
3981 
3982 			/*
3983 			 * First, figure out if this address hasn't been used
3984 			 * in a while.  If it hasn't, then it's a better
3985 			 * candidate for abandoning.
3986 			 */
3987 			ipif = ire->ire_ipif;
3988 			ASSERT(ipif != NULL);
3989 			now = gethrestime_sec();
3990 			maxage = now - ire->ire_create_time;
3991 			if (maxage > ipst->ips_ip_max_temp_idle)
3992 				maxage = ipst->ips_ip_max_temp_idle;
3993 			lused = drv_hztousec(ddi_get_lbolt() -
3994 			    ire->ire_last_used_time) / MICROSEC + 1;
3995 			if (lused >= maxage && (ipif->ipif_flags &
3996 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3997 				maxdefense = ipst->ips_ip_max_temp_defend;
3998 			else
3999 				maxdefense = ipst->ips_ip_max_defend;
4000 
4001 			/*
4002 			 * Now figure out how many times we've defended
4003 			 * ourselves.  Ignore defenses that happened long in
4004 			 * the past.
4005 			 */
4006 			mutex_enter(&ire->ire_lock);
4007 			if ((defs = ire->ire_defense_count) > 0 &&
4008 			    now - ire->ire_defense_time >
4009 			    ipst->ips_ip_defend_interval) {
4010 				ire->ire_defense_count = defs = 0;
4011 			}
4012 			ire->ire_defense_count++;
4013 			ire->ire_defense_time = now;
4014 			mutex_exit(&ire->ire_lock);
4015 			ill_refhold(ill);
4016 			ire_refrele(ire);
4017 
4018 			/*
4019 			 * If we've defended ourselves too many times already,
4020 			 * then give up and tear down the interface(s) using
4021 			 * this address.  Otherwise, defend by sending out a
4022 			 * gratuitous ARP.
4023 			 */
4024 			if (defs >= maxdefense && ill->ill_arp_extend) {
4025 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4026 				    B_FALSE);
4027 			} else {
4028 				cmn_err(CE_WARN,
4029 				    "node %s is using our IP address %s on %s",
4030 				    hbuf, sbuf, ill->ill_name);
4031 				/*
4032 				 * If this is an old (ATM) ARP module, then
4033 				 * don't try to defend the address.  Remain
4034 				 * compatible with the old behavior.  Defend
4035 				 * only with new ARP.
4036 				 */
4037 				if (ill->ill_arp_extend) {
4038 					qwriter_ip(ill, q, mp, ip_arp_defend,
4039 					    NEW_OP, B_FALSE);
4040 				} else {
4041 					ill_refrele(ill);
4042 				}
4043 			}
4044 			return;
4045 		}
4046 		cmn_err(CE_WARN,
4047 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4048 		    hbuf, sbuf, ill->ill_name);
4049 		if (ire != NULL)
4050 			ire_refrele(ire);
4051 		break;
4052 	case AR_CN_ANNOUNCE:
4053 		if (isv6) {
4054 			/*
4055 			 * For XRESOLV interfaces.
4056 			 * Delete the IRE cache entry and NCE for this
4057 			 * v6 address
4058 			 */
4059 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4060 			/*
4061 			 * If v6src is a non-zero, it's a router address
4062 			 * as below. Do the same sort of thing to clean
4063 			 * out off-net IRE_CACHE entries that go through
4064 			 * the router.
4065 			 */
4066 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4067 				ire_walk_v6(ire_delete_cache_gw_v6,
4068 				    (char *)&v6src, ALL_ZONES, ipst);
4069 			}
4070 		} else {
4071 			nce_hw_map_t hwm;
4072 
4073 			/*
4074 			 * ARP gives us a copy of any packet where it thinks
4075 			 * the address has changed, so that we can update our
4076 			 * caches.  We're responsible for caching known answers
4077 			 * in the current design.  We check whether the
4078 			 * hardware address really has changed in all of our
4079 			 * entries that have cached this mapping, and if so, we
4080 			 * blow them away.  This way we will immediately pick
4081 			 * up the rare case of a host changing hardware
4082 			 * address.
4083 			 */
4084 			if (src == 0)
4085 				break;
4086 			hwm.hwm_addr = src;
4087 			hwm.hwm_hwlen = arh->arh_hlen;
4088 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4089 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4090 			ndp_walk_common(ipst->ips_ndp4, NULL,
4091 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4092 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4093 		}
4094 		break;
4095 	case AR_CN_READY:
4096 		/* No external v6 resolver has a contract to use this */
4097 		if (isv6)
4098 			break;
4099 		/* If the link is down, we'll retry this later */
4100 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4101 			break;
4102 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4103 		    NULL, NULL, ipst);
4104 		if (ipif != NULL) {
4105 			/*
4106 			 * If this is a duplicate recovery, then we now need to
4107 			 * go exclusive to bring this thing back up.
4108 			 */
4109 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4110 			    IPIF_DUPLICATE) {
4111 				ipif_refrele(ipif);
4112 				ill_refhold(ill);
4113 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4114 				    B_FALSE);
4115 				return;
4116 			}
4117 			/*
4118 			 * If this is the first notice that this address is
4119 			 * ready, then let the user know now.
4120 			 */
4121 			if ((ipif->ipif_flags & IPIF_UP) &&
4122 			    !ipif->ipif_addr_ready) {
4123 				ipif_mask_reply(ipif);
4124 				ipif_up_notify(ipif);
4125 			}
4126 			ipif->ipif_addr_ready = 1;
4127 			ipif_refrele(ipif);
4128 		}
4129 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4130 		if (ire != NULL) {
4131 			ire->ire_defense_count = 0;
4132 			ire_refrele(ire);
4133 		}
4134 		break;
4135 	case AR_CN_FAILED:
4136 		/* No external v6 resolver has a contract to use this */
4137 		if (isv6)
4138 			break;
4139 		if (!ill->ill_arp_extend) {
4140 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4141 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4142 			(void) ip_dot_addr(src, sbuf);
4143 
4144 			cmn_err(CE_WARN,
4145 			    "node %s is using our IP address %s on %s",
4146 			    hbuf, sbuf, ill->ill_name);
4147 			break;
4148 		}
4149 		ill_refhold(ill);
4150 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4151 		return;
4152 	}
4153 	freemsg(mp);
4154 }
4155 
4156 /*
4157  * Create a mblk suitable for carrying the interface index and/or source link
4158  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4159  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4160  * application.
4161  */
4162 mblk_t *
4163 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4164     ip_stack_t *ipst)
4165 {
4166 	mblk_t		*mp;
4167 	ip_pktinfo_t	*pinfo;
4168 	ipha_t 		*ipha;
4169 	struct ether_header *pether;
4170 	boolean_t	ipmp_ill_held = B_FALSE;
4171 
4172 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4173 	if (mp == NULL) {
4174 		ip1dbg(("ip_add_info: allocation failure.\n"));
4175 		return (data_mp);
4176 	}
4177 
4178 	ipha = (ipha_t *)data_mp->b_rptr;
4179 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4180 	bzero(pinfo, sizeof (ip_pktinfo_t));
4181 	pinfo->ip_pkt_flags = (uchar_t)flags;
4182 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4183 
4184 	pether = (struct ether_header *)((char *)ipha
4185 	    - sizeof (struct ether_header));
4186 
4187 	/*
4188 	 * Make sure the interface is an ethernet type, since this option
4189 	 * is currently supported only on this type of interface. Also make
4190 	 * sure we are pointing correctly above db_base.
4191 	 */
4192 	if ((flags & IPF_RECVSLLA) &&
4193 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4194 	    (ill->ill_type == IFT_ETHER) &&
4195 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4196 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4197 		bcopy(pether->ether_shost.ether_addr_octet,
4198 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4199 	} else {
4200 		/*
4201 		 * Clear the bit. Indicate to upper layer that IP is not
4202 		 * sending this ancillary info.
4203 		 */
4204 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4205 	}
4206 
4207 	/*
4208 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4209 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4210 	 * IPF_RECVADDR support on test addresses is not needed.)
4211 	 *
4212 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4213 	 * processing a packet looped back to an IPMP data address
4214 	 * (since those IRE_LOCALs are tied to IPMP ills).
4215 	 */
4216 	if (IS_UNDER_IPMP(ill)) {
4217 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4218 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4219 			freemsg(mp);
4220 			return (data_mp);
4221 		}
4222 		ipmp_ill_held = B_TRUE;
4223 	}
4224 
4225 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4226 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4227 	if (flags & IPF_RECVADDR) {
4228 		ipif_t	*ipif;
4229 		ire_t	*ire;
4230 
4231 		/*
4232 		 * Only valid for V4
4233 		 */
4234 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4235 		    (IPV4_VERSION << 4));
4236 
4237 		ipif = ipif_get_next_ipif(NULL, ill);
4238 		if (ipif != NULL) {
4239 			/*
4240 			 * Since a decision has already been made to deliver the
4241 			 * packet, there is no need to test for SECATTR and
4242 			 * ZONEONLY.
4243 			 * When a multicast packet is transmitted
4244 			 * a cache entry is created for the multicast address.
4245 			 * When delivering a copy of the packet or when new
4246 			 * packets are received we do not want to match on the
4247 			 * cached entry so explicitly match on
4248 			 * IRE_LOCAL and IRE_LOOPBACK
4249 			 */
4250 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4251 			    IRE_LOCAL | IRE_LOOPBACK,
4252 			    ipif, zoneid, NULL,
4253 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4254 			if (ire == NULL) {
4255 				/*
4256 				 * packet must have come on a different
4257 				 * interface.
4258 				 * Since a decision has already been made to
4259 				 * deliver the packet, there is no need to test
4260 				 * for SECATTR and ZONEONLY.
4261 				 * Only match on local and broadcast ire's.
4262 				 * See detailed comment above.
4263 				 */
4264 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4265 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4266 				    NULL, MATCH_IRE_TYPE, ipst);
4267 			}
4268 
4269 			if (ire == NULL) {
4270 				/*
4271 				 * This is either a multicast packet or
4272 				 * the address has been removed since
4273 				 * the packet was received.
4274 				 * Return INADDR_ANY so that normal source
4275 				 * selection occurs for the response.
4276 				 */
4277 
4278 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4279 			} else {
4280 				pinfo->ip_pkt_match_addr.s_addr =
4281 				    ire->ire_src_addr;
4282 				ire_refrele(ire);
4283 			}
4284 			ipif_refrele(ipif);
4285 		} else {
4286 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4287 		}
4288 	}
4289 
4290 	if (ipmp_ill_held)
4291 		ill_refrele(ill);
4292 
4293 	mp->b_datap->db_type = M_CTL;
4294 	mp->b_wptr += sizeof (ip_pktinfo_t);
4295 	mp->b_cont = data_mp;
4296 
4297 	return (mp);
4298 }
4299 
4300 /*
4301  * Used to determine the most accurate cred_t to use for TX.
4302  * First priority is SCM_UCRED having set the label in the message,
4303  * which is used for MLP on UDP. Second priority is the peers label (aka
4304  * conn_peercred), which is needed for MLP on TCP/SCTP. Last priority is the
4305  * open credentials.
4306  */
4307 cred_t *
4308 ip_best_cred(mblk_t *mp, conn_t *connp)
4309 {
4310 	cred_t *cr;
4311 
4312 	cr = msg_getcred(mp, NULL);
4313 	if (cr != NULL && crgetlabel(cr) != NULL)
4314 		return (cr);
4315 	return (CONN_CRED(connp));
4316 }
4317 
4318 /*
4319  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4320  * part of the bind request.
4321  */
4322 
4323 boolean_t
4324 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4325 {
4326 	ipsec_in_t *ii;
4327 
4328 	ASSERT(policy_mp != NULL);
4329 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4330 
4331 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4332 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4333 
4334 	connp->conn_policy = ii->ipsec_in_policy;
4335 	ii->ipsec_in_policy = NULL;
4336 
4337 	if (ii->ipsec_in_action != NULL) {
4338 		if (connp->conn_latch == NULL) {
4339 			connp->conn_latch = iplatch_create();
4340 			if (connp->conn_latch == NULL)
4341 				return (B_FALSE);
4342 		}
4343 		ipsec_latch_inbound(connp->conn_latch, ii);
4344 	}
4345 	return (B_TRUE);
4346 }
4347 
4348 static void
4349 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4350 {
4351 	/*
4352 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4353 	 * We can't do this in ip_bind_get_ire because the policy
4354 	 * may not have been inherited at that point in time and hence
4355 	 * conn_out_enforce_policy may not be set.
4356 	 */
4357 	if (ire_requested && connp->conn_out_enforce_policy &&
4358 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4359 		ire_t *ire = (ire_t *)mp->b_rptr;
4360 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4361 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4362 	}
4363 }
4364 
4365 /*
4366  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4367  * and to arrange for power-fanout assist.  The ULP is identified by
4368  * adding a single byte at the end of the original bind message.
4369  * A ULP other than UDP or TCP that wishes to be recognized passes
4370  * down a bind with a zero length address.
4371  *
4372  * The binding works as follows:
4373  * - A zero byte address means just bind to the protocol.
4374  * - A four byte address is treated as a request to validate
4375  *   that the address is a valid local address, appropriate for
4376  *   an application to bind to. This does not affect any fanout
4377  *   information in IP.
4378  * - A sizeof sin_t byte address is used to bind to only the local address
4379  *   and port.
4380  * - A sizeof ipa_conn_t byte address contains complete fanout information
4381  *   consisting of local and remote addresses and ports.  In
4382  *   this case, the addresses are both validated as appropriate
4383  *   for this operation, and, if so, the information is retained
4384  *   for use in the inbound fanout.
4385  *
4386  * The ULP (except in the zero-length bind) can append an
4387  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4388  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4389  * a copy of the source or destination IRE (source for local bind;
4390  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4391  * policy information contained should be copied on to the conn.
4392  *
4393  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4394  */
4395 mblk_t *
4396 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4397 {
4398 	ssize_t		len;
4399 	struct T_bind_req	*tbr;
4400 	sin_t		*sin;
4401 	ipa_conn_t	*ac;
4402 	uchar_t		*ucp;
4403 	mblk_t		*mp1;
4404 	boolean_t	ire_requested;
4405 	int		error = 0;
4406 	int		protocol;
4407 	ipa_conn_x_t	*acx;
4408 	cred_t		*cr;
4409 
4410 	/*
4411 	 * All Solaris components should pass a db_credp
4412 	 * for this TPI message, hence we ASSERT.
4413 	 * But in case there is some other M_PROTO that looks
4414 	 * like a TPI message sent by some other kernel
4415 	 * component, we check and return an error.
4416 	 */
4417 	cr = msg_getcred(mp, NULL);
4418 	ASSERT(cr != NULL);
4419 	if (cr == NULL) {
4420 		error = EINVAL;
4421 		goto bad_addr;
4422 	}
4423 
4424 	ASSERT(!connp->conn_af_isv6);
4425 	connp->conn_pkt_isv6 = B_FALSE;
4426 
4427 	len = MBLKL(mp);
4428 	if (len < (sizeof (*tbr) + 1)) {
4429 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4430 		    "ip_bind: bogus msg, len %ld", len);
4431 		/* XXX: Need to return something better */
4432 		goto bad_addr;
4433 	}
4434 	/* Back up and extract the protocol identifier. */
4435 	mp->b_wptr--;
4436 	protocol = *mp->b_wptr & 0xFF;
4437 	tbr = (struct T_bind_req *)mp->b_rptr;
4438 	/* Reset the message type in preparation for shipping it back. */
4439 	DB_TYPE(mp) = M_PCPROTO;
4440 
4441 	connp->conn_ulp = (uint8_t)protocol;
4442 
4443 	/*
4444 	 * Check for a zero length address.  This is from a protocol that
4445 	 * wants to register to receive all packets of its type.
4446 	 */
4447 	if (tbr->ADDR_length == 0) {
4448 		/*
4449 		 * These protocols are now intercepted in ip_bind_v6().
4450 		 * Reject protocol-level binds here for now.
4451 		 *
4452 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4453 		 * so that the protocol type cannot be SCTP.
4454 		 */
4455 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4456 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4457 			goto bad_addr;
4458 		}
4459 
4460 		/*
4461 		 *
4462 		 * The udp module never sends down a zero-length address,
4463 		 * and allowing this on a labeled system will break MLP
4464 		 * functionality.
4465 		 */
4466 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4467 			goto bad_addr;
4468 
4469 		if (connp->conn_mac_exempt)
4470 			goto bad_addr;
4471 
4472 		/* No hash here really.  The table is big enough. */
4473 		connp->conn_srcv6 = ipv6_all_zeros;
4474 
4475 		ipcl_proto_insert(connp, protocol);
4476 
4477 		tbr->PRIM_type = T_BIND_ACK;
4478 		return (mp);
4479 	}
4480 
4481 	/* Extract the address pointer from the message. */
4482 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4483 	    tbr->ADDR_length);
4484 	if (ucp == NULL) {
4485 		ip1dbg(("ip_bind: no address\n"));
4486 		goto bad_addr;
4487 	}
4488 	if (!OK_32PTR(ucp)) {
4489 		ip1dbg(("ip_bind: unaligned address\n"));
4490 		goto bad_addr;
4491 	}
4492 	/*
4493 	 * Check for trailing mps.
4494 	 */
4495 
4496 	mp1 = mp->b_cont;
4497 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4498 
4499 	switch (tbr->ADDR_length) {
4500 	default:
4501 		ip1dbg(("ip_bind: bad address length %d\n",
4502 		    (int)tbr->ADDR_length));
4503 		goto bad_addr;
4504 
4505 	case IP_ADDR_LEN:
4506 		/* Verification of local address only */
4507 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4508 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4509 		break;
4510 
4511 	case sizeof (sin_t):
4512 		sin = (sin_t *)ucp;
4513 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4514 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4515 		break;
4516 
4517 	case sizeof (ipa_conn_t):
4518 		ac = (ipa_conn_t *)ucp;
4519 		/* For raw socket, the local port is not set. */
4520 		if (ac->ac_lport == 0)
4521 			ac->ac_lport = connp->conn_lport;
4522 		/* Always verify destination reachability. */
4523 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4524 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4525 		    B_TRUE, B_TRUE, cr);
4526 		break;
4527 
4528 	case sizeof (ipa_conn_x_t):
4529 		acx = (ipa_conn_x_t *)ucp;
4530 		/*
4531 		 * Whether or not to verify destination reachability depends
4532 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4533 		 */
4534 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4535 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4536 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4537 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4538 		break;
4539 	}
4540 	ASSERT(error != EINPROGRESS);
4541 	if (error != 0)
4542 		goto bad_addr;
4543 
4544 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4545 
4546 	/* Send it home. */
4547 	mp->b_datap->db_type = M_PCPROTO;
4548 	tbr->PRIM_type = T_BIND_ACK;
4549 	return (mp);
4550 
4551 bad_addr:
4552 	/*
4553 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4554 	 * a unix errno.
4555 	 */
4556 	if (error > 0)
4557 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4558 	else
4559 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4560 	return (mp);
4561 }
4562 
4563 /*
4564  * Here address is verified to be a valid local address.
4565  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4566  * address is also considered a valid local address.
4567  * In the case of a broadcast/multicast address, however, the
4568  * upper protocol is expected to reset the src address
4569  * to 0 if it sees a IRE_BROADCAST type returned so that
4570  * no packets are emitted with broadcast/multicast address as
4571  * source address (that violates hosts requirements RFC 1122)
4572  * The addresses valid for bind are:
4573  *	(1) - INADDR_ANY (0)
4574  *	(2) - IP address of an UP interface
4575  *	(3) - IP address of a DOWN interface
4576  *	(4) - valid local IP broadcast addresses. In this case
4577  *	the conn will only receive packets destined to
4578  *	the specified broadcast address.
4579  *	(5) - a multicast address. In this case
4580  *	the conn will only receive packets destined to
4581  *	the specified multicast address. Note: the
4582  *	application still has to issue an
4583  *	IP_ADD_MEMBERSHIP socket option.
4584  *
4585  * On error, return -1 for TBADADDR otherwise pass the
4586  * errno with TSYSERR reply.
4587  *
4588  * In all the above cases, the bound address must be valid in the current zone.
4589  * When the address is loopback, multicast or broadcast, there might be many
4590  * matching IREs so bind has to look up based on the zone.
4591  *
4592  * Note: lport is in network byte order.
4593  *
4594  */
4595 int
4596 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4597     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4598 {
4599 	int		error = 0;
4600 	ire_t		*src_ire;
4601 	zoneid_t	zoneid;
4602 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4603 	mblk_t		*mp = NULL;
4604 	boolean_t	ire_requested = B_FALSE;
4605 	boolean_t	ipsec_policy_set = B_FALSE;
4606 
4607 	if (mpp)
4608 		mp = *mpp;
4609 
4610 	if (mp != NULL) {
4611 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4612 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4613 	}
4614 
4615 	/*
4616 	 * If it was previously connected, conn_fully_bound would have
4617 	 * been set.
4618 	 */
4619 	connp->conn_fully_bound = B_FALSE;
4620 
4621 	src_ire = NULL;
4622 
4623 	zoneid = IPCL_ZONEID(connp);
4624 
4625 	if (src_addr) {
4626 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4627 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4628 		/*
4629 		 * If an address other than 0.0.0.0 is requested,
4630 		 * we verify that it is a valid address for bind
4631 		 * Note: Following code is in if-else-if form for
4632 		 * readability compared to a condition check.
4633 		 */
4634 		/* LINTED - statement has no consequence */
4635 		if (IRE_IS_LOCAL(src_ire)) {
4636 			/*
4637 			 * (2) Bind to address of local UP interface
4638 			 */
4639 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4640 			/*
4641 			 * (4) Bind to broadcast address
4642 			 * Note: permitted only from transports that
4643 			 * request IRE
4644 			 */
4645 			if (!ire_requested)
4646 				error = EADDRNOTAVAIL;
4647 		} else {
4648 			/*
4649 			 * (3) Bind to address of local DOWN interface
4650 			 * (ipif_lookup_addr() looks up all interfaces
4651 			 * but we do not get here for UP interfaces
4652 			 * - case (2) above)
4653 			 */
4654 			/* LINTED - statement has no consequent */
4655 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4656 				/* The address exists */
4657 			} else if (CLASSD(src_addr)) {
4658 				error = 0;
4659 				if (src_ire != NULL)
4660 					ire_refrele(src_ire);
4661 				/*
4662 				 * (5) bind to multicast address.
4663 				 * Fake out the IRE returned to upper
4664 				 * layer to be a broadcast IRE.
4665 				 */
4666 				src_ire = ire_ctable_lookup(
4667 				    INADDR_BROADCAST, INADDR_ANY,
4668 				    IRE_BROADCAST, NULL, zoneid, NULL,
4669 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4670 				    ipst);
4671 				if (src_ire == NULL || !ire_requested)
4672 					error = EADDRNOTAVAIL;
4673 			} else {
4674 				/*
4675 				 * Not a valid address for bind
4676 				 */
4677 				error = EADDRNOTAVAIL;
4678 			}
4679 		}
4680 		if (error) {
4681 			/* Red Alert!  Attempting to be a bogon! */
4682 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4683 			    ntohl(src_addr)));
4684 			goto bad_addr;
4685 		}
4686 	}
4687 
4688 	/*
4689 	 * Allow setting new policies. For example, disconnects come
4690 	 * down as ipa_t bind. As we would have set conn_policy_cached
4691 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4692 	 * can change after the disconnect.
4693 	 */
4694 	connp->conn_policy_cached = B_FALSE;
4695 
4696 	/*
4697 	 * If not fanout_insert this was just an address verification
4698 	 */
4699 	if (fanout_insert) {
4700 		/*
4701 		 * The addresses have been verified. Time to insert in
4702 		 * the correct fanout list.
4703 		 */
4704 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4705 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4706 		connp->conn_lport = lport;
4707 		connp->conn_fport = 0;
4708 		/*
4709 		 * Do we need to add a check to reject Multicast packets
4710 		 */
4711 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4712 	}
4713 
4714 	if (error == 0) {
4715 		if (ire_requested) {
4716 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4717 				error = -1;
4718 				/* Falls through to bad_addr */
4719 			}
4720 		} else if (ipsec_policy_set) {
4721 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4722 				error = -1;
4723 				/* Falls through to bad_addr */
4724 			}
4725 		}
4726 	}
4727 bad_addr:
4728 	if (error != 0) {
4729 		if (connp->conn_anon_port) {
4730 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4731 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4732 			    B_FALSE);
4733 		}
4734 		connp->conn_mlp_type = mlptSingle;
4735 	}
4736 	if (src_ire != NULL)
4737 		IRE_REFRELE(src_ire);
4738 	return (error);
4739 }
4740 
4741 int
4742 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4743     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4744 {
4745 	int error;
4746 	mblk_t	*mp = NULL;
4747 	boolean_t ire_requested;
4748 
4749 	if (ire_mpp)
4750 		mp = *ire_mpp;
4751 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4752 
4753 	ASSERT(!connp->conn_af_isv6);
4754 	connp->conn_pkt_isv6 = B_FALSE;
4755 	connp->conn_ulp = protocol;
4756 
4757 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4758 	    fanout_insert);
4759 	if (error == 0) {
4760 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4761 		    ire_requested);
4762 	} else if (error < 0) {
4763 		error = -TBADADDR;
4764 	}
4765 	return (error);
4766 }
4767 
4768 /*
4769  * Verify that both the source and destination addresses
4770  * are valid.  If verify_dst is false, then the destination address may be
4771  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4772  * destination reachability, while tunnels do not.
4773  * Note that we allow connect to broadcast and multicast
4774  * addresses when ire_requested is set. Thus the ULP
4775  * has to check for IRE_BROADCAST and multicast.
4776  *
4777  * Returns zero if ok.
4778  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4779  * (for use with TSYSERR reply).
4780  *
4781  * Note: lport and fport are in network byte order.
4782  */
4783 int
4784 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4785     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4786     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4787 {
4788 
4789 	ire_t		*src_ire;
4790 	ire_t		*dst_ire;
4791 	int		error = 0;
4792 	ire_t		*sire = NULL;
4793 	ire_t		*md_dst_ire = NULL;
4794 	ire_t		*lso_dst_ire = NULL;
4795 	ill_t		*ill = NULL;
4796 	zoneid_t	zoneid;
4797 	ipaddr_t	src_addr = *src_addrp;
4798 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4799 	mblk_t		*mp = NULL;
4800 	boolean_t	ire_requested = B_FALSE;
4801 	boolean_t	ipsec_policy_set = B_FALSE;
4802 	ts_label_t	*tsl = NULL;
4803 
4804 	if (mpp)
4805 		mp = *mpp;
4806 
4807 	if (mp != NULL) {
4808 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4809 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4810 	}
4811 	if (cr != NULL)
4812 		tsl = crgetlabel(cr);
4813 
4814 	src_ire = dst_ire = NULL;
4815 
4816 	/*
4817 	 * If we never got a disconnect before, clear it now.
4818 	 */
4819 	connp->conn_fully_bound = B_FALSE;
4820 
4821 	zoneid = IPCL_ZONEID(connp);
4822 
4823 	if (CLASSD(dst_addr)) {
4824 		/* Pick up an IRE_BROADCAST */
4825 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4826 		    NULL, zoneid, tsl,
4827 		    (MATCH_IRE_RECURSIVE |
4828 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4829 		    MATCH_IRE_SECATTR), ipst);
4830 	} else {
4831 		/*
4832 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4833 		 * and onlink ipif is not found set ENETUNREACH error.
4834 		 */
4835 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4836 			ipif_t *ipif;
4837 
4838 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4839 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4840 			if (ipif == NULL) {
4841 				error = ENETUNREACH;
4842 				goto bad_addr;
4843 			}
4844 			ipif_refrele(ipif);
4845 		}
4846 
4847 		if (connp->conn_nexthop_set) {
4848 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4849 			    0, 0, NULL, NULL, zoneid, tsl,
4850 			    MATCH_IRE_SECATTR, ipst);
4851 		} else {
4852 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4853 			    &sire, zoneid, tsl,
4854 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4855 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4856 			    MATCH_IRE_SECATTR), ipst);
4857 		}
4858 	}
4859 	/*
4860 	 * dst_ire can't be a broadcast when not ire_requested.
4861 	 * We also prevent ire's with src address INADDR_ANY to
4862 	 * be used, which are created temporarily for
4863 	 * sending out packets from endpoints that have
4864 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4865 	 * reachable.  If verify_dst is false, the destination needn't be
4866 	 * reachable.
4867 	 *
4868 	 * If we match on a reject or black hole, then we've got a
4869 	 * local failure.  May as well fail out the connect() attempt,
4870 	 * since it's never going to succeed.
4871 	 */
4872 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4873 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4874 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4875 		/*
4876 		 * If we're verifying destination reachability, we always want
4877 		 * to complain here.
4878 		 *
4879 		 * If we're not verifying destination reachability but the
4880 		 * destination has a route, we still want to fail on the
4881 		 * temporary address and broadcast address tests.
4882 		 */
4883 		if (verify_dst || (dst_ire != NULL)) {
4884 			if (ip_debug > 2) {
4885 				pr_addr_dbg("ip_bind_connected_v4:"
4886 				    "bad connected dst %s\n",
4887 				    AF_INET, &dst_addr);
4888 			}
4889 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4890 				error = ENETUNREACH;
4891 			else
4892 				error = EHOSTUNREACH;
4893 			goto bad_addr;
4894 		}
4895 	}
4896 
4897 	/*
4898 	 * We now know that routing will allow us to reach the destination.
4899 	 * Check whether Trusted Solaris policy allows communication with this
4900 	 * host, and pretend that the destination is unreachable if not.
4901 	 *
4902 	 * This is never a problem for TCP, since that transport is known to
4903 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4904 	 * handling.  If the remote is unreachable, it will be detected at that
4905 	 * point, so there's no reason to check it here.
4906 	 *
4907 	 * Note that for sendto (and other datagram-oriented friends), this
4908 	 * check is done as part of the data path label computation instead.
4909 	 * The check here is just to make non-TCP connect() report the right
4910 	 * error.
4911 	 */
4912 	if (dst_ire != NULL && is_system_labeled() &&
4913 	    !IPCL_IS_TCP(connp) &&
4914 	    tsol_compute_label(cr, dst_addr, NULL,
4915 	    connp->conn_mac_exempt, ipst) != 0) {
4916 		error = EHOSTUNREACH;
4917 		if (ip_debug > 2) {
4918 			pr_addr_dbg("ip_bind_connected_v4:"
4919 			    " no label for dst %s\n",
4920 			    AF_INET, &dst_addr);
4921 		}
4922 		goto bad_addr;
4923 	}
4924 
4925 	/*
4926 	 * If the app does a connect(), it means that it will most likely
4927 	 * send more than 1 packet to the destination.  It makes sense
4928 	 * to clear the temporary flag.
4929 	 */
4930 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4931 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4932 		irb_t *irb = dst_ire->ire_bucket;
4933 
4934 		rw_enter(&irb->irb_lock, RW_WRITER);
4935 		/*
4936 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4937 		 * the lock to guarantee irb_tmp_ire_cnt.
4938 		 */
4939 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4940 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4941 			irb->irb_tmp_ire_cnt--;
4942 		}
4943 		rw_exit(&irb->irb_lock);
4944 	}
4945 
4946 	/*
4947 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4948 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4949 	 * eligibility tests for passive connects are handled separately
4950 	 * through tcp_adapt_ire().  We do this before the source address
4951 	 * selection, because dst_ire may change after a call to
4952 	 * ipif_select_source().  This is a best-effort check, as the
4953 	 * packet for this connection may not actually go through
4954 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4955 	 * calling ip_newroute().  This is why we further check on the
4956 	 * IRE during LSO/Multidata packet transmission in
4957 	 * tcp_lsosend()/tcp_multisend().
4958 	 */
4959 	if (!ipsec_policy_set && dst_ire != NULL &&
4960 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4961 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4962 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4963 			lso_dst_ire = dst_ire;
4964 			IRE_REFHOLD(lso_dst_ire);
4965 		} else if (ipst->ips_ip_multidata_outbound &&
4966 		    ILL_MDT_CAPABLE(ill)) {
4967 			md_dst_ire = dst_ire;
4968 			IRE_REFHOLD(md_dst_ire);
4969 		}
4970 	}
4971 
4972 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4973 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4974 		/*
4975 		 * If the IRE belongs to a different zone, look for a matching
4976 		 * route in the forwarding table and use the source address from
4977 		 * that route.
4978 		 */
4979 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4980 		    zoneid, 0, NULL,
4981 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4982 		    MATCH_IRE_RJ_BHOLE, ipst);
4983 		if (src_ire == NULL) {
4984 			error = EHOSTUNREACH;
4985 			goto bad_addr;
4986 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4987 			if (!(src_ire->ire_type & IRE_HOST))
4988 				error = ENETUNREACH;
4989 			else
4990 				error = EHOSTUNREACH;
4991 			goto bad_addr;
4992 		}
4993 		if (src_addr == INADDR_ANY)
4994 			src_addr = src_ire->ire_src_addr;
4995 		ire_refrele(src_ire);
4996 		src_ire = NULL;
4997 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4998 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4999 			src_addr = sire->ire_src_addr;
5000 			ire_refrele(dst_ire);
5001 			dst_ire = sire;
5002 			sire = NULL;
5003 		} else {
5004 			/*
5005 			 * Pick a source address so that a proper inbound
5006 			 * load spreading would happen.
5007 			 */
5008 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5009 			ipif_t *src_ipif = NULL;
5010 			ire_t *ipif_ire;
5011 
5012 			/*
5013 			 * Supply a local source address such that inbound
5014 			 * load spreading happens.
5015 			 *
5016 			 * Determine the best source address on this ill for
5017 			 * the destination.
5018 			 *
5019 			 * 1) For broadcast, we should return a broadcast ire
5020 			 *    found above so that upper layers know that the
5021 			 *    destination address is a broadcast address.
5022 			 *
5023 			 * 2) If the ipif is DEPRECATED, select a better
5024 			 *    source address.  Similarly, if the ipif is on
5025 			 *    the IPMP meta-interface, pick a source address
5026 			 *    at random to improve inbound load spreading.
5027 			 *
5028 			 * 3) If the outgoing interface is part of a usesrc
5029 			 *    group, then try selecting a source address from
5030 			 *    the usesrc ILL.
5031 			 */
5032 			if ((dst_ire->ire_zoneid != zoneid &&
5033 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5034 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5035 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5036 			    (IS_IPMP(ire_ill) ||
5037 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5038 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5039 				/*
5040 				 * If the destination is reachable via a
5041 				 * given gateway, the selected source address
5042 				 * should be in the same subnet as the gateway.
5043 				 * Otherwise, the destination is not reachable.
5044 				 *
5045 				 * If there are no interfaces on the same subnet
5046 				 * as the destination, ipif_select_source gives
5047 				 * first non-deprecated interface which might be
5048 				 * on a different subnet than the gateway.
5049 				 * This is not desirable. Hence pass the dst_ire
5050 				 * source address to ipif_select_source.
5051 				 * It is sure that the destination is reachable
5052 				 * with the dst_ire source address subnet.
5053 				 * So passing dst_ire source address to
5054 				 * ipif_select_source will make sure that the
5055 				 * selected source will be on the same subnet
5056 				 * as dst_ire source address.
5057 				 */
5058 				ipaddr_t saddr =
5059 				    dst_ire->ire_ipif->ipif_src_addr;
5060 				src_ipif = ipif_select_source(ire_ill,
5061 				    saddr, zoneid);
5062 				if (src_ipif != NULL) {
5063 					if (IS_VNI(src_ipif->ipif_ill)) {
5064 						/*
5065 						 * For VNI there is no
5066 						 * interface route
5067 						 */
5068 						src_addr =
5069 						    src_ipif->ipif_src_addr;
5070 					} else {
5071 						ipif_ire =
5072 						    ipif_to_ire(src_ipif);
5073 						if (ipif_ire != NULL) {
5074 							IRE_REFRELE(dst_ire);
5075 							dst_ire = ipif_ire;
5076 						}
5077 						src_addr =
5078 						    dst_ire->ire_src_addr;
5079 					}
5080 					ipif_refrele(src_ipif);
5081 				} else {
5082 					src_addr = dst_ire->ire_src_addr;
5083 				}
5084 			} else {
5085 				src_addr = dst_ire->ire_src_addr;
5086 			}
5087 		}
5088 	}
5089 
5090 	/*
5091 	 * We do ire_route_lookup() here (and not
5092 	 * interface lookup as we assert that
5093 	 * src_addr should only come from an
5094 	 * UP interface for hard binding.
5095 	 */
5096 	ASSERT(src_ire == NULL);
5097 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5098 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5099 	/* src_ire must be a local|loopback */
5100 	if (!IRE_IS_LOCAL(src_ire)) {
5101 		if (ip_debug > 2) {
5102 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5103 			    "src %s\n", AF_INET, &src_addr);
5104 		}
5105 		error = EADDRNOTAVAIL;
5106 		goto bad_addr;
5107 	}
5108 
5109 	/*
5110 	 * If the source address is a loopback address, the
5111 	 * destination had best be local or multicast.
5112 	 * The transports that can't handle multicast will reject
5113 	 * those addresses.
5114 	 */
5115 	if (src_ire->ire_type == IRE_LOOPBACK &&
5116 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5117 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5118 		error = -1;
5119 		goto bad_addr;
5120 	}
5121 
5122 	/*
5123 	 * Allow setting new policies. For example, disconnects come
5124 	 * down as ipa_t bind. As we would have set conn_policy_cached
5125 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5126 	 * can change after the disconnect.
5127 	 */
5128 	connp->conn_policy_cached = B_FALSE;
5129 
5130 	/*
5131 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5132 	 * can handle their passed-in conn's.
5133 	 */
5134 
5135 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5136 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5137 	connp->conn_lport = lport;
5138 	connp->conn_fport = fport;
5139 	*src_addrp = src_addr;
5140 
5141 	ASSERT(!(ipsec_policy_set && ire_requested));
5142 	if (ire_requested) {
5143 		iulp_t *ulp_info = NULL;
5144 
5145 		/*
5146 		 * Note that sire will not be NULL if this is an off-link
5147 		 * connection and there is not cache for that dest yet.
5148 		 *
5149 		 * XXX Because of an existing bug, if there are multiple
5150 		 * default routes, the IRE returned now may not be the actual
5151 		 * default route used (default routes are chosen in a
5152 		 * round robin fashion).  So if the metrics for different
5153 		 * default routes are different, we may return the wrong
5154 		 * metrics.  This will not be a problem if the existing
5155 		 * bug is fixed.
5156 		 */
5157 		if (sire != NULL) {
5158 			ulp_info = &(sire->ire_uinfo);
5159 		}
5160 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5161 			error = -1;
5162 			goto bad_addr;
5163 		}
5164 		mp = *mpp;
5165 	} else if (ipsec_policy_set) {
5166 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5167 			error = -1;
5168 			goto bad_addr;
5169 		}
5170 	}
5171 
5172 	/*
5173 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5174 	 * we'll cache that.  If we don't, we'll inherit global policy.
5175 	 *
5176 	 * We can't insert until the conn reflects the policy. Note that
5177 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5178 	 * connections where we don't have a policy. This is to prevent
5179 	 * global policy lookups in the inbound path.
5180 	 *
5181 	 * If we insert before we set conn_policy_cached,
5182 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5183 	 * because global policy cound be non-empty. We normally call
5184 	 * ipsec_check_policy() for conn_policy_cached connections only if
5185 	 * ipc_in_enforce_policy is set. But in this case,
5186 	 * conn_policy_cached can get set anytime since we made the
5187 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5188 	 * called, which will make the above assumption false.  Thus, we
5189 	 * need to insert after we set conn_policy_cached.
5190 	 */
5191 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5192 		goto bad_addr;
5193 
5194 	if (fanout_insert) {
5195 		/*
5196 		 * The addresses have been verified. Time to insert in
5197 		 * the correct fanout list.
5198 		 */
5199 		error = ipcl_conn_insert(connp, protocol, src_addr,
5200 		    dst_addr, connp->conn_ports);
5201 	}
5202 
5203 	if (error == 0) {
5204 		connp->conn_fully_bound = B_TRUE;
5205 		/*
5206 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5207 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5208 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5209 		 * ip_xxinfo_return(), which performs further checks
5210 		 * against them and upon success, returns the LSO/MDT info
5211 		 * mblk which we will attach to the bind acknowledgment.
5212 		 */
5213 		if (lso_dst_ire != NULL) {
5214 			mblk_t *lsoinfo_mp;
5215 
5216 			ASSERT(ill->ill_lso_capab != NULL);
5217 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5218 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5219 				if (mp == NULL) {
5220 					*mpp = lsoinfo_mp;
5221 				} else {
5222 					linkb(mp, lsoinfo_mp);
5223 				}
5224 			}
5225 		} else if (md_dst_ire != NULL) {
5226 			mblk_t *mdinfo_mp;
5227 
5228 			ASSERT(ill->ill_mdt_capab != NULL);
5229 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5230 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5231 				if (mp == NULL) {
5232 					*mpp = mdinfo_mp;
5233 				} else {
5234 					linkb(mp, mdinfo_mp);
5235 				}
5236 			}
5237 		}
5238 	}
5239 bad_addr:
5240 	if (ipsec_policy_set) {
5241 		ASSERT(mp != NULL);
5242 		freeb(mp);
5243 		/*
5244 		 * As of now assume that nothing else accompanies
5245 		 * IPSEC_POLICY_SET.
5246 		 */
5247 		*mpp = NULL;
5248 	}
5249 	if (src_ire != NULL)
5250 		IRE_REFRELE(src_ire);
5251 	if (dst_ire != NULL)
5252 		IRE_REFRELE(dst_ire);
5253 	if (sire != NULL)
5254 		IRE_REFRELE(sire);
5255 	if (md_dst_ire != NULL)
5256 		IRE_REFRELE(md_dst_ire);
5257 	if (lso_dst_ire != NULL)
5258 		IRE_REFRELE(lso_dst_ire);
5259 	return (error);
5260 }
5261 
5262 int
5263 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5264     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5265     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5266 {
5267 	int error;
5268 	mblk_t	*mp = NULL;
5269 	boolean_t ire_requested;
5270 
5271 	if (ire_mpp)
5272 		mp = *ire_mpp;
5273 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5274 
5275 	ASSERT(!connp->conn_af_isv6);
5276 	connp->conn_pkt_isv6 = B_FALSE;
5277 	connp->conn_ulp = protocol;
5278 
5279 	/* For raw socket, the local port is not set. */
5280 	if (lport == 0)
5281 		lport = connp->conn_lport;
5282 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5283 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5284 	if (error == 0) {
5285 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5286 		    ire_requested);
5287 	} else if (error < 0) {
5288 		error = -TBADADDR;
5289 	}
5290 	return (error);
5291 }
5292 
5293 /*
5294  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5295  * Prefers dst_ire over src_ire.
5296  */
5297 static boolean_t
5298 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5299 {
5300 	mblk_t	*mp = *mpp;
5301 	ire_t	*ret_ire;
5302 
5303 	ASSERT(mp != NULL);
5304 
5305 	if (ire != NULL) {
5306 		/*
5307 		 * mp initialized above to IRE_DB_REQ_TYPE
5308 		 * appended mblk. Its <upper protocol>'s
5309 		 * job to make sure there is room.
5310 		 */
5311 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5312 			return (B_FALSE);
5313 
5314 		mp->b_datap->db_type = IRE_DB_TYPE;
5315 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5316 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5317 		ret_ire = (ire_t *)mp->b_rptr;
5318 		/*
5319 		 * Pass the latest setting of the ip_path_mtu_discovery and
5320 		 * copy the ulp info if any.
5321 		 */
5322 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5323 		    IPH_DF : 0;
5324 		if (ulp_info != NULL) {
5325 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5326 			    sizeof (iulp_t));
5327 		}
5328 		ret_ire->ire_mp = mp;
5329 	} else {
5330 		/*
5331 		 * No IRE was found. Remove IRE mblk.
5332 		 */
5333 		*mpp = mp->b_cont;
5334 		freeb(mp);
5335 	}
5336 	return (B_TRUE);
5337 }
5338 
5339 /*
5340  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5341  * the final piece where we don't.  Return a pointer to the first mblk in the
5342  * result, and update the pointer to the next mblk to chew on.  If anything
5343  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5344  * NULL pointer.
5345  */
5346 mblk_t *
5347 ip_carve_mp(mblk_t **mpp, ssize_t len)
5348 {
5349 	mblk_t	*mp0;
5350 	mblk_t	*mp1;
5351 	mblk_t	*mp2;
5352 
5353 	if (!len || !mpp || !(mp0 = *mpp))
5354 		return (NULL);
5355 	/* If we aren't going to consume the first mblk, we need a dup. */
5356 	if (mp0->b_wptr - mp0->b_rptr > len) {
5357 		mp1 = dupb(mp0);
5358 		if (mp1) {
5359 			/* Partition the data between the two mblks. */
5360 			mp1->b_wptr = mp1->b_rptr + len;
5361 			mp0->b_rptr = mp1->b_wptr;
5362 			/*
5363 			 * after adjustments if mblk not consumed is now
5364 			 * unaligned, try to align it. If this fails free
5365 			 * all messages and let upper layer recover.
5366 			 */
5367 			if (!OK_32PTR(mp0->b_rptr)) {
5368 				if (!pullupmsg(mp0, -1)) {
5369 					freemsg(mp0);
5370 					freemsg(mp1);
5371 					*mpp = NULL;
5372 					return (NULL);
5373 				}
5374 			}
5375 		}
5376 		return (mp1);
5377 	}
5378 	/* Eat through as many mblks as we need to get len bytes. */
5379 	len -= mp0->b_wptr - mp0->b_rptr;
5380 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5381 		if (mp2->b_wptr - mp2->b_rptr > len) {
5382 			/*
5383 			 * We won't consume the entire last mblk.  Like
5384 			 * above, dup and partition it.
5385 			 */
5386 			mp1->b_cont = dupb(mp2);
5387 			mp1 = mp1->b_cont;
5388 			if (!mp1) {
5389 				/*
5390 				 * Trouble.  Rather than go to a lot of
5391 				 * trouble to clean up, we free the messages.
5392 				 * This won't be any worse than losing it on
5393 				 * the wire.
5394 				 */
5395 				freemsg(mp0);
5396 				freemsg(mp2);
5397 				*mpp = NULL;
5398 				return (NULL);
5399 			}
5400 			mp1->b_wptr = mp1->b_rptr + len;
5401 			mp2->b_rptr = mp1->b_wptr;
5402 			/*
5403 			 * after adjustments if mblk not consumed is now
5404 			 * unaligned, try to align it. If this fails free
5405 			 * all messages and let upper layer recover.
5406 			 */
5407 			if (!OK_32PTR(mp2->b_rptr)) {
5408 				if (!pullupmsg(mp2, -1)) {
5409 					freemsg(mp0);
5410 					freemsg(mp2);
5411 					*mpp = NULL;
5412 					return (NULL);
5413 				}
5414 			}
5415 			*mpp = mp2;
5416 			return (mp0);
5417 		}
5418 		/* Decrement len by the amount we just got. */
5419 		len -= mp2->b_wptr - mp2->b_rptr;
5420 	}
5421 	/*
5422 	 * len should be reduced to zero now.  If not our caller has
5423 	 * screwed up.
5424 	 */
5425 	if (len) {
5426 		/* Shouldn't happen! */
5427 		freemsg(mp0);
5428 		*mpp = NULL;
5429 		return (NULL);
5430 	}
5431 	/*
5432 	 * We consumed up to exactly the end of an mblk.  Detach the part
5433 	 * we are returning from the rest of the chain.
5434 	 */
5435 	mp1->b_cont = NULL;
5436 	*mpp = mp2;
5437 	return (mp0);
5438 }
5439 
5440 /* The ill stream is being unplumbed. Called from ip_close */
5441 int
5442 ip_modclose(ill_t *ill)
5443 {
5444 	boolean_t success;
5445 	ipsq_t	*ipsq;
5446 	ipif_t	*ipif;
5447 	queue_t	*q = ill->ill_rq;
5448 	ip_stack_t	*ipst = ill->ill_ipst;
5449 	int	i;
5450 
5451 	/*
5452 	 * The punlink prior to this may have initiated a capability
5453 	 * negotiation. But ipsq_enter will block until that finishes or
5454 	 * times out.
5455 	 */
5456 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5457 
5458 	/*
5459 	 * Open/close/push/pop is guaranteed to be single threaded
5460 	 * per stream by STREAMS. FS guarantees that all references
5461 	 * from top are gone before close is called. So there can't
5462 	 * be another close thread that has set CONDEMNED on this ill.
5463 	 * and cause ipsq_enter to return failure.
5464 	 */
5465 	ASSERT(success);
5466 	ipsq = ill->ill_phyint->phyint_ipsq;
5467 
5468 	/*
5469 	 * Mark it condemned. No new reference will be made to this ill.
5470 	 * Lookup functions will return an error. Threads that try to
5471 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5472 	 * that the refcnt will drop down to zero.
5473 	 */
5474 	mutex_enter(&ill->ill_lock);
5475 	ill->ill_state_flags |= ILL_CONDEMNED;
5476 	for (ipif = ill->ill_ipif; ipif != NULL;
5477 	    ipif = ipif->ipif_next) {
5478 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5479 	}
5480 	/*
5481 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5482 	 * returns  error if ILL_CONDEMNED is set
5483 	 */
5484 	cv_broadcast(&ill->ill_cv);
5485 	mutex_exit(&ill->ill_lock);
5486 
5487 	/*
5488 	 * Send all the deferred DLPI messages downstream which came in
5489 	 * during the small window right before ipsq_enter(). We do this
5490 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5491 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5492 	 */
5493 	ill_dlpi_send_deferred(ill);
5494 
5495 	/*
5496 	 * Shut down fragmentation reassembly.
5497 	 * ill_frag_timer won't start a timer again.
5498 	 * Now cancel any existing timer
5499 	 */
5500 	(void) untimeout(ill->ill_frag_timer_id);
5501 	(void) ill_frag_timeout(ill, 0);
5502 
5503 	/*
5504 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5505 	 * this ill. Then wait for the refcnts to drop to zero.
5506 	 * ill_is_freeable checks whether the ill is really quiescent.
5507 	 * Then make sure that threads that are waiting to enter the
5508 	 * ipsq have seen the error returned by ipsq_enter and have
5509 	 * gone away. Then we call ill_delete_tail which does the
5510 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5511 	 */
5512 	ill_delete(ill);
5513 	mutex_enter(&ill->ill_lock);
5514 	while (!ill_is_freeable(ill))
5515 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5516 	while (ill->ill_waiters)
5517 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5518 
5519 	mutex_exit(&ill->ill_lock);
5520 
5521 	/*
5522 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5523 	 * it held until the end of the function since the cleanup
5524 	 * below needs to be able to use the ip_stack_t.
5525 	 */
5526 	netstack_hold(ipst->ips_netstack);
5527 
5528 	/* qprocsoff is done via ill_delete_tail */
5529 	ill_delete_tail(ill);
5530 	ASSERT(ill->ill_ipst == NULL);
5531 
5532 	/*
5533 	 * Walk through all upper (conn) streams and qenable
5534 	 * those that have queued data.
5535 	 * close synchronization needs this to
5536 	 * be done to ensure that all upper layers blocked
5537 	 * due to flow control to the closing device
5538 	 * get unblocked.
5539 	 */
5540 	ip1dbg(("ip_wsrv: walking\n"));
5541 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5542 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5543 	}
5544 
5545 	mutex_enter(&ipst->ips_ip_mi_lock);
5546 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5547 	mutex_exit(&ipst->ips_ip_mi_lock);
5548 
5549 	/*
5550 	 * credp could be null if the open didn't succeed and ip_modopen
5551 	 * itself calls ip_close.
5552 	 */
5553 	if (ill->ill_credp != NULL)
5554 		crfree(ill->ill_credp);
5555 
5556 	/*
5557 	 * Now we are done with the module close pieces that
5558 	 * need the netstack_t.
5559 	 */
5560 	netstack_rele(ipst->ips_netstack);
5561 
5562 	mi_close_free((IDP)ill);
5563 	q->q_ptr = WR(q)->q_ptr = NULL;
5564 
5565 	ipsq_exit(ipsq);
5566 
5567 	return (0);
5568 }
5569 
5570 /*
5571  * This is called as part of close() for IP, UDP, ICMP, and RTS
5572  * in order to quiesce the conn.
5573  */
5574 void
5575 ip_quiesce_conn(conn_t *connp)
5576 {
5577 	boolean_t	drain_cleanup_reqd = B_FALSE;
5578 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5579 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5580 	ip_stack_t	*ipst;
5581 
5582 	ASSERT(!IPCL_IS_TCP(connp));
5583 	ipst = connp->conn_netstack->netstack_ip;
5584 
5585 	/*
5586 	 * Mark the conn as closing, and this conn must not be
5587 	 * inserted in future into any list. Eg. conn_drain_insert(),
5588 	 * won't insert this conn into the conn_drain_list.
5589 	 * Similarly ill_pending_mp_add() will not add any mp to
5590 	 * the pending mp list, after this conn has started closing.
5591 	 *
5592 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5593 	 * cannot get set henceforth.
5594 	 */
5595 	mutex_enter(&connp->conn_lock);
5596 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5597 	connp->conn_state_flags |= CONN_CLOSING;
5598 	if (connp->conn_idl != NULL)
5599 		drain_cleanup_reqd = B_TRUE;
5600 	if (connp->conn_oper_pending_ill != NULL)
5601 		conn_ioctl_cleanup_reqd = B_TRUE;
5602 	if (connp->conn_dhcpinit_ill != NULL) {
5603 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5604 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5605 		connp->conn_dhcpinit_ill = NULL;
5606 	}
5607 	if (connp->conn_ilg_inuse != 0)
5608 		ilg_cleanup_reqd = B_TRUE;
5609 	mutex_exit(&connp->conn_lock);
5610 
5611 	if (conn_ioctl_cleanup_reqd)
5612 		conn_ioctl_cleanup(connp);
5613 
5614 	if (is_system_labeled() && connp->conn_anon_port) {
5615 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5616 		    connp->conn_mlp_type, connp->conn_ulp,
5617 		    ntohs(connp->conn_lport), B_FALSE);
5618 		connp->conn_anon_port = 0;
5619 	}
5620 	connp->conn_mlp_type = mlptSingle;
5621 
5622 	/*
5623 	 * Remove this conn from any fanout list it is on.
5624 	 * and then wait for any threads currently operating
5625 	 * on this endpoint to finish
5626 	 */
5627 	ipcl_hash_remove(connp);
5628 
5629 	/*
5630 	 * Remove this conn from the drain list, and do
5631 	 * any other cleanup that may be required.
5632 	 * (Only non-tcp streams may have a non-null conn_idl.
5633 	 * TCP streams are never flow controlled, and
5634 	 * conn_idl will be null)
5635 	 */
5636 	if (drain_cleanup_reqd)
5637 		conn_drain_tail(connp, B_TRUE);
5638 
5639 	if (connp == ipst->ips_ip_g_mrouter)
5640 		(void) ip_mrouter_done(NULL, ipst);
5641 
5642 	if (ilg_cleanup_reqd)
5643 		ilg_delete_all(connp);
5644 
5645 	conn_delete_ire(connp, NULL);
5646 
5647 	/*
5648 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5649 	 * callers from write side can't be there now because close
5650 	 * is in progress. The only other caller is ipcl_walk
5651 	 * which checks for the condemned flag.
5652 	 */
5653 	mutex_enter(&connp->conn_lock);
5654 	connp->conn_state_flags |= CONN_CONDEMNED;
5655 	while (connp->conn_ref != 1)
5656 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5657 	connp->conn_state_flags |= CONN_QUIESCED;
5658 	mutex_exit(&connp->conn_lock);
5659 }
5660 
5661 /* ARGSUSED */
5662 int
5663 ip_close(queue_t *q, int flags)
5664 {
5665 	conn_t		*connp;
5666 
5667 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5668 
5669 	/*
5670 	 * Call the appropriate delete routine depending on whether this is
5671 	 * a module or device.
5672 	 */
5673 	if (WR(q)->q_next != NULL) {
5674 		/* This is a module close */
5675 		return (ip_modclose((ill_t *)q->q_ptr));
5676 	}
5677 
5678 	connp = q->q_ptr;
5679 	ip_quiesce_conn(connp);
5680 
5681 	qprocsoff(q);
5682 
5683 	/*
5684 	 * Now we are truly single threaded on this stream, and can
5685 	 * delete the things hanging off the connp, and finally the connp.
5686 	 * We removed this connp from the fanout list, it cannot be
5687 	 * accessed thru the fanouts, and we already waited for the
5688 	 * conn_ref to drop to 0. We are already in close, so
5689 	 * there cannot be any other thread from the top. qprocsoff
5690 	 * has completed, and service has completed or won't run in
5691 	 * future.
5692 	 */
5693 	ASSERT(connp->conn_ref == 1);
5694 
5695 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5696 
5697 	connp->conn_ref--;
5698 	ipcl_conn_destroy(connp);
5699 
5700 	q->q_ptr = WR(q)->q_ptr = NULL;
5701 	return (0);
5702 }
5703 
5704 /*
5705  * Wapper around putnext() so that ip_rts_request can merely use
5706  * conn_recv.
5707  */
5708 /*ARGSUSED2*/
5709 static void
5710 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5711 {
5712 	conn_t *connp = (conn_t *)arg1;
5713 
5714 	putnext(connp->conn_rq, mp);
5715 }
5716 
5717 /*
5718  * Called when the module is about to be unloaded
5719  */
5720 void
5721 ip_ddi_destroy(void)
5722 {
5723 	tnet_fini();
5724 
5725 	icmp_ddi_g_destroy();
5726 	rts_ddi_g_destroy();
5727 	udp_ddi_g_destroy();
5728 	sctp_ddi_g_destroy();
5729 	tcp_ddi_g_destroy();
5730 	ipsec_policy_g_destroy();
5731 	ipcl_g_destroy();
5732 	ip_net_g_destroy();
5733 	ip_ire_g_fini();
5734 	inet_minor_destroy(ip_minor_arena_sa);
5735 #if defined(_LP64)
5736 	inet_minor_destroy(ip_minor_arena_la);
5737 #endif
5738 
5739 #ifdef DEBUG
5740 	list_destroy(&ip_thread_list);
5741 	rw_destroy(&ip_thread_rwlock);
5742 	tsd_destroy(&ip_thread_data);
5743 #endif
5744 
5745 	netstack_unregister(NS_IP);
5746 }
5747 
5748 /*
5749  * First step in cleanup.
5750  */
5751 /* ARGSUSED */
5752 static void
5753 ip_stack_shutdown(netstackid_t stackid, void *arg)
5754 {
5755 	ip_stack_t *ipst = (ip_stack_t *)arg;
5756 
5757 #ifdef NS_DEBUG
5758 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5759 #endif
5760 
5761 	/* Get rid of loopback interfaces and their IREs */
5762 	ip_loopback_cleanup(ipst);
5763 
5764 	/*
5765 	 * The *_hook_shutdown()s start the process of notifying any
5766 	 * consumers that things are going away.... nothing is destroyed.
5767 	 */
5768 	ipv4_hook_shutdown(ipst);
5769 	ipv6_hook_shutdown(ipst);
5770 
5771 	mutex_enter(&ipst->ips_capab_taskq_lock);
5772 	ipst->ips_capab_taskq_quit = B_TRUE;
5773 	cv_signal(&ipst->ips_capab_taskq_cv);
5774 	mutex_exit(&ipst->ips_capab_taskq_lock);
5775 
5776 	mutex_enter(&ipst->ips_mrt_lock);
5777 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5778 	cv_signal(&ipst->ips_mrt_cv);
5779 	mutex_exit(&ipst->ips_mrt_lock);
5780 }
5781 
5782 /*
5783  * Free the IP stack instance.
5784  */
5785 static void
5786 ip_stack_fini(netstackid_t stackid, void *arg)
5787 {
5788 	ip_stack_t *ipst = (ip_stack_t *)arg;
5789 	int ret;
5790 
5791 #ifdef NS_DEBUG
5792 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5793 #endif
5794 	/*
5795 	 * At this point, all of the notifications that the events and
5796 	 * protocols are going away have been run, meaning that we can
5797 	 * now set about starting to clean things up.
5798 	 */
5799 	ipv4_hook_destroy(ipst);
5800 	ipv6_hook_destroy(ipst);
5801 	ip_net_destroy(ipst);
5802 
5803 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5804 	cv_destroy(&ipst->ips_capab_taskq_cv);
5805 	list_destroy(&ipst->ips_capab_taskq_list);
5806 
5807 	mutex_enter(&ipst->ips_mrt_lock);
5808 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5809 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5810 	mutex_destroy(&ipst->ips_mrt_lock);
5811 	cv_destroy(&ipst->ips_mrt_cv);
5812 	cv_destroy(&ipst->ips_mrt_done_cv);
5813 
5814 	ipmp_destroy(ipst);
5815 	rw_destroy(&ipst->ips_srcid_lock);
5816 
5817 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5818 	ipst->ips_ip_mibkp = NULL;
5819 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5820 	ipst->ips_icmp_mibkp = NULL;
5821 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5822 	ipst->ips_ip_kstat = NULL;
5823 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5824 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5825 	ipst->ips_ip6_kstat = NULL;
5826 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5827 
5828 	nd_free(&ipst->ips_ip_g_nd);
5829 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5830 	ipst->ips_param_arr = NULL;
5831 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5832 	ipst->ips_ndp_arr = NULL;
5833 
5834 	ip_mrouter_stack_destroy(ipst);
5835 
5836 	mutex_destroy(&ipst->ips_ip_mi_lock);
5837 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5838 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5839 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5840 
5841 	ret = untimeout(ipst->ips_igmp_timeout_id);
5842 	if (ret == -1) {
5843 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5844 	} else {
5845 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5846 		ipst->ips_igmp_timeout_id = 0;
5847 	}
5848 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5849 	if (ret == -1) {
5850 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5851 	} else {
5852 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5853 		ipst->ips_igmp_slowtimeout_id = 0;
5854 	}
5855 	ret = untimeout(ipst->ips_mld_timeout_id);
5856 	if (ret == -1) {
5857 		ASSERT(ipst->ips_mld_timeout_id == 0);
5858 	} else {
5859 		ASSERT(ipst->ips_mld_timeout_id != 0);
5860 		ipst->ips_mld_timeout_id = 0;
5861 	}
5862 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5863 	if (ret == -1) {
5864 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5865 	} else {
5866 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5867 		ipst->ips_mld_slowtimeout_id = 0;
5868 	}
5869 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5874 		ipst->ips_ip_ire_expire_id = 0;
5875 	}
5876 
5877 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5878 	mutex_destroy(&ipst->ips_mld_timer_lock);
5879 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5880 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5881 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5882 	rw_destroy(&ipst->ips_ill_g_lock);
5883 
5884 	ipobs_fini(ipst);
5885 	ip_ire_fini(ipst);
5886 	ip6_asp_free(ipst);
5887 	conn_drain_fini(ipst);
5888 	ipcl_destroy(ipst);
5889 
5890 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5891 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5892 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5893 	ipst->ips_ndp4 = NULL;
5894 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5895 	ipst->ips_ndp6 = NULL;
5896 
5897 	if (ipst->ips_loopback_ksp != NULL) {
5898 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5899 		ipst->ips_loopback_ksp = NULL;
5900 	}
5901 
5902 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5903 	ipst->ips_phyint_g_list = NULL;
5904 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5905 	ipst->ips_ill_g_heads = NULL;
5906 
5907 	ldi_ident_release(ipst->ips_ldi_ident);
5908 	kmem_free(ipst, sizeof (*ipst));
5909 }
5910 
5911 /*
5912  * This function is called from the TSD destructor, and is used to debug
5913  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5914  * details.
5915  */
5916 static void
5917 ip_thread_exit(void *phash)
5918 {
5919 	th_hash_t *thh = phash;
5920 
5921 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5922 	list_remove(&ip_thread_list, thh);
5923 	rw_exit(&ip_thread_rwlock);
5924 	mod_hash_destroy_hash(thh->thh_hash);
5925 	kmem_free(thh, sizeof (*thh));
5926 }
5927 
5928 /*
5929  * Called when the IP kernel module is loaded into the kernel
5930  */
5931 void
5932 ip_ddi_init(void)
5933 {
5934 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5935 
5936 	/*
5937 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5938 	 * initial devices: ip, ip6, tcp, tcp6.
5939 	 */
5940 	/*
5941 	 * If this is a 64-bit kernel, then create two separate arenas -
5942 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5943 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5944 	 */
5945 	ip_minor_arena_la = NULL;
5946 	ip_minor_arena_sa = NULL;
5947 #if defined(_LP64)
5948 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5949 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5950 		cmn_err(CE_PANIC,
5951 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5952 	}
5953 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5954 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5955 		cmn_err(CE_PANIC,
5956 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5957 	}
5958 #else
5959 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5960 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5961 		cmn_err(CE_PANIC,
5962 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5963 	}
5964 #endif
5965 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5966 
5967 	ipcl_g_init();
5968 	ip_ire_g_init();
5969 	ip_net_g_init();
5970 
5971 #ifdef DEBUG
5972 	tsd_create(&ip_thread_data, ip_thread_exit);
5973 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5974 	list_create(&ip_thread_list, sizeof (th_hash_t),
5975 	    offsetof(th_hash_t, thh_link));
5976 #endif
5977 
5978 	/*
5979 	 * We want to be informed each time a stack is created or
5980 	 * destroyed in the kernel, so we can maintain the
5981 	 * set of udp_stack_t's.
5982 	 */
5983 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5984 	    ip_stack_fini);
5985 
5986 	ipsec_policy_g_init();
5987 	tcp_ddi_g_init();
5988 	sctp_ddi_g_init();
5989 
5990 	tnet_init();
5991 
5992 	udp_ddi_g_init();
5993 	rts_ddi_g_init();
5994 	icmp_ddi_g_init();
5995 }
5996 
5997 /*
5998  * Initialize the IP stack instance.
5999  */
6000 static void *
6001 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6002 {
6003 	ip_stack_t	*ipst;
6004 	ipparam_t	*pa;
6005 	ipndp_t		*na;
6006 	major_t		major;
6007 
6008 #ifdef NS_DEBUG
6009 	printf("ip_stack_init(stack %d)\n", stackid);
6010 #endif
6011 
6012 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6013 	ipst->ips_netstack = ns;
6014 
6015 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6016 	    KM_SLEEP);
6017 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6018 	    KM_SLEEP);
6019 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6020 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6021 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6022 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6023 
6024 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6025 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6026 	ipst->ips_igmp_deferred_next = INFINITY;
6027 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6028 	ipst->ips_mld_deferred_next = INFINITY;
6029 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6030 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6031 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6032 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6033 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6034 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6035 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6036 
6037 	ipcl_init(ipst);
6038 	ip_ire_init(ipst);
6039 	ip6_asp_init(ipst);
6040 	ipif_init(ipst);
6041 	conn_drain_init(ipst);
6042 	ip_mrouter_stack_init(ipst);
6043 
6044 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6045 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6046 
6047 	ipst->ips_ip_multirt_log_interval = 1000;
6048 
6049 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6050 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6051 	ipst->ips_ill_index = 1;
6052 
6053 	ipst->ips_saved_ip_g_forward = -1;
6054 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6055 
6056 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6057 	ipst->ips_param_arr = pa;
6058 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6059 
6060 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6061 	ipst->ips_ndp_arr = na;
6062 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6063 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6064 	    (caddr_t)&ipst->ips_ip_g_forward;
6065 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6066 	    (caddr_t)&ipst->ips_ipv6_forward;
6067 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6068 	    "ip_cgtp_filter") == 0);
6069 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6070 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6071 
6072 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6073 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6074 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6075 
6076 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6077 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6078 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6079 	ipst->ips_ip6_kstat =
6080 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6081 
6082 	ipst->ips_ip_src_id = 1;
6083 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6084 
6085 	ipobs_init(ipst);
6086 	ip_net_init(ipst, ns);
6087 	ipv4_hook_init(ipst);
6088 	ipv6_hook_init(ipst);
6089 	ipmp_init(ipst);
6090 
6091 	/*
6092 	 * Create the taskq dispatcher thread and initialize related stuff.
6093 	 */
6094 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6095 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6096 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6097 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6098 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6099 	    offsetof(mblk_t, b_next));
6100 
6101 	/*
6102 	 * Create the mcast_restart_timers_thread() worker thread.
6103 	 */
6104 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6105 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6106 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6107 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6108 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6109 
6110 	major = mod_name_to_major(INET_NAME);
6111 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6112 	return (ipst);
6113 }
6114 
6115 /*
6116  * Allocate and initialize a DLPI template of the specified length.  (May be
6117  * called as writer.)
6118  */
6119 mblk_t *
6120 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6121 {
6122 	mblk_t	*mp;
6123 
6124 	mp = allocb(len, BPRI_MED);
6125 	if (!mp)
6126 		return (NULL);
6127 
6128 	/*
6129 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6130 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6131 	 * that other DLPI are M_PROTO.
6132 	 */
6133 	if (prim == DL_INFO_REQ) {
6134 		mp->b_datap->db_type = M_PCPROTO;
6135 	} else {
6136 		mp->b_datap->db_type = M_PROTO;
6137 	}
6138 
6139 	mp->b_wptr = mp->b_rptr + len;
6140 	bzero(mp->b_rptr, len);
6141 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6142 	return (mp);
6143 }
6144 
6145 /*
6146  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6147  */
6148 mblk_t *
6149 ip_dlnotify_alloc(uint_t notification, uint_t data)
6150 {
6151 	dl_notify_ind_t	*notifyp;
6152 	mblk_t		*mp;
6153 
6154 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6155 		return (NULL);
6156 
6157 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6158 	notifyp->dl_notification = notification;
6159 	notifyp->dl_data = data;
6160 	return (mp);
6161 }
6162 
6163 /*
6164  * Debug formatting routine.  Returns a character string representation of the
6165  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6166  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6167  *
6168  * Once the ndd table-printing interfaces are removed, this can be changed to
6169  * standard dotted-decimal form.
6170  */
6171 char *
6172 ip_dot_addr(ipaddr_t addr, char *buf)
6173 {
6174 	uint8_t *ap = (uint8_t *)&addr;
6175 
6176 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6177 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6178 	return (buf);
6179 }
6180 
6181 /*
6182  * Write the given MAC address as a printable string in the usual colon-
6183  * separated format.
6184  */
6185 const char *
6186 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6187 {
6188 	char *bp;
6189 
6190 	if (alen == 0 || buflen < 4)
6191 		return ("?");
6192 	bp = buf;
6193 	for (;;) {
6194 		/*
6195 		 * If there are more MAC address bytes available, but we won't
6196 		 * have any room to print them, then add "..." to the string
6197 		 * instead.  See below for the 'magic number' explanation.
6198 		 */
6199 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6200 			(void) strcpy(bp, "...");
6201 			break;
6202 		}
6203 		(void) sprintf(bp, "%02x", *addr++);
6204 		bp += 2;
6205 		if (--alen == 0)
6206 			break;
6207 		*bp++ = ':';
6208 		buflen -= 3;
6209 		/*
6210 		 * At this point, based on the first 'if' statement above,
6211 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6212 		 * buflen >= 4.  The first case leaves room for the final "xx"
6213 		 * number and trailing NUL byte.  The second leaves room for at
6214 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6215 		 * that statement.
6216 		 */
6217 	}
6218 	return (buf);
6219 }
6220 
6221 /*
6222  * Send an ICMP error after patching up the packet appropriately.  Returns
6223  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6224  */
6225 static boolean_t
6226 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6227     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6228     zoneid_t zoneid, ip_stack_t *ipst)
6229 {
6230 	ipha_t *ipha;
6231 	mblk_t *first_mp;
6232 	boolean_t secure;
6233 	unsigned char db_type;
6234 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6235 
6236 	first_mp = mp;
6237 	if (mctl_present) {
6238 		mp = mp->b_cont;
6239 		secure = ipsec_in_is_secure(first_mp);
6240 		ASSERT(mp != NULL);
6241 	} else {
6242 		/*
6243 		 * If this is an ICMP error being reported - which goes
6244 		 * up as M_CTLs, we need to convert them to M_DATA till
6245 		 * we finish checking with global policy because
6246 		 * ipsec_check_global_policy() assumes M_DATA as clear
6247 		 * and M_CTL as secure.
6248 		 */
6249 		db_type = DB_TYPE(mp);
6250 		DB_TYPE(mp) = M_DATA;
6251 		secure = B_FALSE;
6252 	}
6253 	/*
6254 	 * We are generating an icmp error for some inbound packet.
6255 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6256 	 * Before we generate an error, check with global policy
6257 	 * to see whether this is allowed to enter the system. As
6258 	 * there is no "conn", we are checking with global policy.
6259 	 */
6260 	ipha = (ipha_t *)mp->b_rptr;
6261 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6262 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6263 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6264 		if (first_mp == NULL)
6265 			return (B_FALSE);
6266 	}
6267 
6268 	if (!mctl_present)
6269 		DB_TYPE(mp) = db_type;
6270 
6271 	if (flags & IP_FF_SEND_ICMP) {
6272 		if (flags & IP_FF_HDR_COMPLETE) {
6273 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6274 				freemsg(first_mp);
6275 				return (B_TRUE);
6276 			}
6277 		}
6278 		if (flags & IP_FF_CKSUM) {
6279 			/*
6280 			 * Have to correct checksum since
6281 			 * the packet might have been
6282 			 * fragmented and the reassembly code in ip_rput
6283 			 * does not restore the IP checksum.
6284 			 */
6285 			ipha->ipha_hdr_checksum = 0;
6286 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6287 		}
6288 		switch (icmp_type) {
6289 		case ICMP_DEST_UNREACHABLE:
6290 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6291 			    ipst);
6292 			break;
6293 		default:
6294 			freemsg(first_mp);
6295 			break;
6296 		}
6297 	} else {
6298 		freemsg(first_mp);
6299 		return (B_FALSE);
6300 	}
6301 
6302 	return (B_TRUE);
6303 }
6304 
6305 /*
6306  * Used to send an ICMP error message when a packet is received for
6307  * a protocol that is not supported. The mblk passed as argument
6308  * is consumed by this function.
6309  */
6310 void
6311 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6312     ip_stack_t *ipst)
6313 {
6314 	mblk_t *mp;
6315 	ipha_t *ipha;
6316 	ill_t *ill;
6317 	ipsec_in_t *ii;
6318 
6319 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6320 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6321 
6322 	mp = ipsec_mp->b_cont;
6323 	ipsec_mp->b_cont = NULL;
6324 	ipha = (ipha_t *)mp->b_rptr;
6325 	/* Get ill from index in ipsec_in_t. */
6326 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6327 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6328 	    ipst);
6329 	if (ill != NULL) {
6330 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6331 			if (ip_fanout_send_icmp(q, mp, flags,
6332 			    ICMP_DEST_UNREACHABLE,
6333 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6334 				BUMP_MIB(ill->ill_ip_mib,
6335 				    ipIfStatsInUnknownProtos);
6336 			}
6337 		} else {
6338 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6339 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6340 			    0, B_FALSE, zoneid, ipst)) {
6341 				BUMP_MIB(ill->ill_ip_mib,
6342 				    ipIfStatsInUnknownProtos);
6343 			}
6344 		}
6345 		ill_refrele(ill);
6346 	} else { /* re-link for the freemsg() below. */
6347 		ipsec_mp->b_cont = mp;
6348 	}
6349 
6350 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6351 	freemsg(ipsec_mp);
6352 }
6353 
6354 /*
6355  * See if the inbound datagram has had IPsec processing applied to it.
6356  */
6357 boolean_t
6358 ipsec_in_is_secure(mblk_t *ipsec_mp)
6359 {
6360 	ipsec_in_t *ii;
6361 
6362 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6363 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6364 
6365 	if (ii->ipsec_in_loopback) {
6366 		return (ii->ipsec_in_secure);
6367 	} else {
6368 		return (ii->ipsec_in_ah_sa != NULL ||
6369 		    ii->ipsec_in_esp_sa != NULL ||
6370 		    ii->ipsec_in_decaps);
6371 	}
6372 }
6373 
6374 /*
6375  * Handle protocols with which IP is less intimate.  There
6376  * can be more than one stream bound to a particular
6377  * protocol.  When this is the case, normally each one gets a copy
6378  * of any incoming packets.
6379  *
6380  * IPsec NOTE :
6381  *
6382  * Don't allow a secure packet going up a non-secure connection.
6383  * We don't allow this because
6384  *
6385  * 1) Reply might go out in clear which will be dropped at
6386  *    the sending side.
6387  * 2) If the reply goes out in clear it will give the
6388  *    adversary enough information for getting the key in
6389  *    most of the cases.
6390  *
6391  * Moreover getting a secure packet when we expect clear
6392  * implies that SA's were added without checking for
6393  * policy on both ends. This should not happen once ISAKMP
6394  * is used to negotiate SAs as SAs will be added only after
6395  * verifying the policy.
6396  *
6397  * NOTE : If the packet was tunneled and not multicast we only send
6398  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6399  * back to delivering packets to AF_INET6 raw sockets.
6400  *
6401  * IPQoS Notes:
6402  * Once we have determined the client, invoke IPPF processing.
6403  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6404  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6405  * ip_policy will be false.
6406  *
6407  * Zones notes:
6408  * Currently only applications in the global zone can create raw sockets for
6409  * protocols other than ICMP. So unlike the broadcast / multicast case of
6410  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6411  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6412  */
6413 static void
6414 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6415     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6416     zoneid_t zoneid)
6417 {
6418 	queue_t	*rq;
6419 	mblk_t	*mp1, *first_mp1;
6420 	uint_t	protocol = ipha->ipha_protocol;
6421 	ipaddr_t dst;
6422 	boolean_t one_only;
6423 	mblk_t *first_mp = mp;
6424 	boolean_t secure;
6425 	uint32_t ill_index;
6426 	conn_t	*connp, *first_connp, *next_connp;
6427 	connf_t	*connfp;
6428 	boolean_t shared_addr;
6429 	mib2_ipIfStatsEntry_t *mibptr;
6430 	ip_stack_t *ipst = recv_ill->ill_ipst;
6431 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6432 
6433 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6434 	if (mctl_present) {
6435 		mp = first_mp->b_cont;
6436 		secure = ipsec_in_is_secure(first_mp);
6437 		ASSERT(mp != NULL);
6438 	} else {
6439 		secure = B_FALSE;
6440 	}
6441 	dst = ipha->ipha_dst;
6442 	/*
6443 	 * If the packet was tunneled and not multicast we only send to it
6444 	 * the first match.
6445 	 */
6446 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6447 	    !CLASSD(dst));
6448 
6449 	shared_addr = (zoneid == ALL_ZONES);
6450 	if (shared_addr) {
6451 		/*
6452 		 * We don't allow multilevel ports for raw IP, so no need to
6453 		 * check for that here.
6454 		 */
6455 		zoneid = tsol_packet_to_zoneid(mp);
6456 	}
6457 
6458 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6459 	mutex_enter(&connfp->connf_lock);
6460 	connp = connfp->connf_head;
6461 	for (connp = connfp->connf_head; connp != NULL;
6462 	    connp = connp->conn_next) {
6463 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6464 		    zoneid) &&
6465 		    (!is_system_labeled() ||
6466 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6467 		    connp))) {
6468 			break;
6469 		}
6470 	}
6471 
6472 	if (connp == NULL) {
6473 		/*
6474 		 * No one bound to these addresses.  Is
6475 		 * there a client that wants all
6476 		 * unclaimed datagrams?
6477 		 */
6478 		mutex_exit(&connfp->connf_lock);
6479 		/*
6480 		 * Check for IPPROTO_ENCAP...
6481 		 */
6482 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6483 			/*
6484 			 * If an IPsec mblk is here on a multicast
6485 			 * tunnel (using ip_mroute stuff), check policy here,
6486 			 * THEN ship off to ip_mroute_decap().
6487 			 *
6488 			 * BTW,  If I match a configured IP-in-IP
6489 			 * tunnel, this path will not be reached, and
6490 			 * ip_mroute_decap will never be called.
6491 			 */
6492 			first_mp = ipsec_check_global_policy(first_mp, connp,
6493 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6494 			if (first_mp != NULL) {
6495 				if (mctl_present)
6496 					freeb(first_mp);
6497 				ip_mroute_decap(q, mp, ill);
6498 			} /* Else we already freed everything! */
6499 		} else {
6500 			/*
6501 			 * Otherwise send an ICMP protocol unreachable.
6502 			 */
6503 			if (ip_fanout_send_icmp(q, first_mp, flags,
6504 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6505 			    mctl_present, zoneid, ipst)) {
6506 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6507 			}
6508 		}
6509 		return;
6510 	}
6511 
6512 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6513 
6514 	CONN_INC_REF(connp);
6515 	first_connp = connp;
6516 
6517 	/*
6518 	 * Only send message to one tunnel driver by immediately
6519 	 * terminating the loop.
6520 	 */
6521 	connp = one_only ? NULL : connp->conn_next;
6522 
6523 	for (;;) {
6524 		while (connp != NULL) {
6525 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6526 			    flags, zoneid) &&
6527 			    (!is_system_labeled() ||
6528 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6529 			    shared_addr, connp)))
6530 				break;
6531 			connp = connp->conn_next;
6532 		}
6533 
6534 		/*
6535 		 * Copy the packet.
6536 		 */
6537 		if (connp == NULL ||
6538 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6539 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6540 			/*
6541 			 * No more interested clients or memory
6542 			 * allocation failed
6543 			 */
6544 			connp = first_connp;
6545 			break;
6546 		}
6547 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6548 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6549 		CONN_INC_REF(connp);
6550 		mutex_exit(&connfp->connf_lock);
6551 		rq = connp->conn_rq;
6552 
6553 		/*
6554 		 * Check flow control
6555 		 */
6556 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6557 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6558 			if (flags & IP_FF_RAWIP) {
6559 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6560 			} else {
6561 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6562 			}
6563 
6564 			freemsg(first_mp1);
6565 		} else {
6566 			/*
6567 			 * Don't enforce here if we're an actual tunnel -
6568 			 * let "tun" do it instead.
6569 			 */
6570 			if (!IPCL_IS_IPTUN(connp) &&
6571 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6572 			    secure)) {
6573 				first_mp1 = ipsec_check_inbound_policy
6574 				    (first_mp1, connp, ipha, NULL,
6575 				    mctl_present);
6576 			}
6577 			if (first_mp1 != NULL) {
6578 				int in_flags = 0;
6579 				/*
6580 				 * ip_fanout_proto also gets called from
6581 				 * icmp_inbound_error_fanout, in which case
6582 				 * the msg type is M_CTL.  Don't add info
6583 				 * in this case for the time being. In future
6584 				 * when there is a need for knowing the
6585 				 * inbound iface index for ICMP error msgs,
6586 				 * then this can be changed.
6587 				 */
6588 				if (connp->conn_recvif)
6589 					in_flags = IPF_RECVIF;
6590 				/*
6591 				 * The ULP may support IP_RECVPKTINFO for both
6592 				 * IP v4 and v6 so pass the appropriate argument
6593 				 * based on conn IP version.
6594 				 */
6595 				if (connp->conn_ip_recvpktinfo) {
6596 					if (connp->conn_af_isv6) {
6597 						/*
6598 						 * V6 only needs index
6599 						 */
6600 						in_flags |= IPF_RECVIF;
6601 					} else {
6602 						/*
6603 						 * V4 needs index +
6604 						 * matching address.
6605 						 */
6606 						in_flags |= IPF_RECVADDR;
6607 					}
6608 				}
6609 				if ((in_flags != 0) &&
6610 				    (mp->b_datap->db_type != M_CTL)) {
6611 					/*
6612 					 * the actual data will be
6613 					 * contained in b_cont upon
6614 					 * successful return of the
6615 					 * following call else
6616 					 * original mblk is returned
6617 					 */
6618 					ASSERT(recv_ill != NULL);
6619 					mp1 = ip_add_info(mp1, recv_ill,
6620 					    in_flags, IPCL_ZONEID(connp), ipst);
6621 				}
6622 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6623 				if (mctl_present)
6624 					freeb(first_mp1);
6625 				(connp->conn_recv)(connp, mp1, NULL);
6626 			}
6627 		}
6628 		mutex_enter(&connfp->connf_lock);
6629 		/* Follow the next pointer before releasing the conn. */
6630 		next_connp = connp->conn_next;
6631 		CONN_DEC_REF(connp);
6632 		connp = next_connp;
6633 	}
6634 
6635 	/* Last one.  Send it upstream. */
6636 	mutex_exit(&connfp->connf_lock);
6637 
6638 	/*
6639 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6640 	 * will be set to false.
6641 	 */
6642 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6643 		ill_index = ill->ill_phyint->phyint_ifindex;
6644 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6645 		if (mp == NULL) {
6646 			CONN_DEC_REF(connp);
6647 			if (mctl_present) {
6648 				freeb(first_mp);
6649 			}
6650 			return;
6651 		}
6652 	}
6653 
6654 	rq = connp->conn_rq;
6655 	/*
6656 	 * Check flow control
6657 	 */
6658 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6659 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6660 		if (flags & IP_FF_RAWIP) {
6661 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6662 		} else {
6663 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6664 		}
6665 
6666 		freemsg(first_mp);
6667 	} else {
6668 		if (IPCL_IS_IPTUN(connp)) {
6669 			/*
6670 			 * Tunneled packet.  We enforce policy in the tunnel
6671 			 * module itself.
6672 			 *
6673 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6674 			 * a policy check.
6675 			 * FIXME to use conn_recv for tun later.
6676 			 */
6677 			putnext(rq, first_mp);
6678 			CONN_DEC_REF(connp);
6679 			return;
6680 		}
6681 
6682 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6683 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6684 			    ipha, NULL, mctl_present);
6685 		}
6686 
6687 		if (first_mp != NULL) {
6688 			int in_flags = 0;
6689 
6690 			/*
6691 			 * ip_fanout_proto also gets called
6692 			 * from icmp_inbound_error_fanout, in
6693 			 * which case the msg type is M_CTL.
6694 			 * Don't add info in this case for time
6695 			 * being. In future when there is a
6696 			 * need for knowing the inbound iface
6697 			 * index for ICMP error msgs, then this
6698 			 * can be changed
6699 			 */
6700 			if (connp->conn_recvif)
6701 				in_flags = IPF_RECVIF;
6702 			if (connp->conn_ip_recvpktinfo) {
6703 				if (connp->conn_af_isv6) {
6704 					/*
6705 					 * V6 only needs index
6706 					 */
6707 					in_flags |= IPF_RECVIF;
6708 				} else {
6709 					/*
6710 					 * V4 needs index +
6711 					 * matching address.
6712 					 */
6713 					in_flags |= IPF_RECVADDR;
6714 				}
6715 			}
6716 			if ((in_flags != 0) &&
6717 			    (mp->b_datap->db_type != M_CTL)) {
6718 
6719 				/*
6720 				 * the actual data will be contained in
6721 				 * b_cont upon successful return
6722 				 * of the following call else original
6723 				 * mblk is returned
6724 				 */
6725 				ASSERT(recv_ill != NULL);
6726 				mp = ip_add_info(mp, recv_ill,
6727 				    in_flags, IPCL_ZONEID(connp), ipst);
6728 			}
6729 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6730 			(connp->conn_recv)(connp, mp, NULL);
6731 			if (mctl_present)
6732 				freeb(first_mp);
6733 		}
6734 	}
6735 	CONN_DEC_REF(connp);
6736 }
6737 
6738 /*
6739  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6740  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6741  * the correct squeue, in this case the same squeue as a valid listener with
6742  * no current connection state for the packet we are processing. The function
6743  * is called for synchronizing both IPv4 and IPv6.
6744  */
6745 void
6746 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6747     tcp_stack_t *tcps, conn_t *connp)
6748 {
6749 	mblk_t *rst_mp;
6750 	tcp_xmit_reset_event_t *eventp;
6751 
6752 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6753 
6754 	if (rst_mp == NULL) {
6755 		freemsg(mp);
6756 		return;
6757 	}
6758 
6759 	rst_mp->b_datap->db_type = M_PROTO;
6760 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6761 
6762 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6763 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6764 	eventp->tcp_xre_iphdrlen = hdrlen;
6765 	eventp->tcp_xre_zoneid = zoneid;
6766 	eventp->tcp_xre_tcps = tcps;
6767 
6768 	rst_mp->b_cont = mp;
6769 	mp = rst_mp;
6770 
6771 	/*
6772 	 * Increment the connref, this ref will be released by the squeue
6773 	 * framework.
6774 	 */
6775 	CONN_INC_REF(connp);
6776 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6777 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6778 }
6779 
6780 /*
6781  * Fanout for TCP packets
6782  * The caller puts <fport, lport> in the ports parameter.
6783  *
6784  * IPQoS Notes
6785  * Before sending it to the client, invoke IPPF processing.
6786  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6787  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6788  * ip_policy is false.
6789  */
6790 static void
6791 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6792     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6793 {
6794 	mblk_t  *first_mp;
6795 	boolean_t secure;
6796 	uint32_t ill_index;
6797 	int	ip_hdr_len;
6798 	tcph_t	*tcph;
6799 	boolean_t syn_present = B_FALSE;
6800 	conn_t	*connp;
6801 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6802 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6803 
6804 	ASSERT(recv_ill != NULL);
6805 
6806 	first_mp = mp;
6807 	if (mctl_present) {
6808 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6809 		mp = first_mp->b_cont;
6810 		secure = ipsec_in_is_secure(first_mp);
6811 		ASSERT(mp != NULL);
6812 	} else {
6813 		secure = B_FALSE;
6814 	}
6815 
6816 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6817 
6818 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6819 	    zoneid, ipst)) == NULL) {
6820 		/*
6821 		 * No connected connection or listener. Send a
6822 		 * TH_RST via tcp_xmit_listeners_reset.
6823 		 */
6824 
6825 		/* Initiate IPPf processing, if needed. */
6826 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6827 			uint32_t ill_index;
6828 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6829 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6830 			if (first_mp == NULL)
6831 				return;
6832 		}
6833 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6834 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6835 		    zoneid));
6836 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6837 		    ipst->ips_netstack->netstack_tcp, NULL);
6838 		return;
6839 	}
6840 
6841 	/*
6842 	 * Allocate the SYN for the TCP connection here itself
6843 	 */
6844 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6845 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6846 		if (IPCL_IS_TCP(connp)) {
6847 			squeue_t *sqp;
6848 
6849 			/*
6850 			 * For fused tcp loopback, assign the eager's
6851 			 * squeue to be that of the active connect's.
6852 			 * Note that we don't check for IP_FF_LOOPBACK
6853 			 * here since this routine gets called only
6854 			 * for loopback (unlike the IPv6 counterpart).
6855 			 */
6856 			ASSERT(Q_TO_CONN(q) != NULL);
6857 			if (do_tcp_fusion &&
6858 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6859 			    !secure &&
6860 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6861 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6862 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6863 				sqp = Q_TO_CONN(q)->conn_sqp;
6864 			} else {
6865 				sqp = IP_SQUEUE_GET(lbolt);
6866 			}
6867 
6868 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6869 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6870 			syn_present = B_TRUE;
6871 		}
6872 	}
6873 
6874 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6875 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6876 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6877 		if ((flags & TH_RST) || (flags & TH_URG)) {
6878 			CONN_DEC_REF(connp);
6879 			freemsg(first_mp);
6880 			return;
6881 		}
6882 		if (flags & TH_ACK) {
6883 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6884 			    ipst->ips_netstack->netstack_tcp, connp);
6885 			CONN_DEC_REF(connp);
6886 			return;
6887 		}
6888 
6889 		CONN_DEC_REF(connp);
6890 		freemsg(first_mp);
6891 		return;
6892 	}
6893 
6894 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6895 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6896 		    NULL, mctl_present);
6897 		if (first_mp == NULL) {
6898 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6899 			CONN_DEC_REF(connp);
6900 			return;
6901 		}
6902 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6903 			ASSERT(syn_present);
6904 			if (mctl_present) {
6905 				ASSERT(first_mp != mp);
6906 				first_mp->b_datap->db_struioflag |=
6907 				    STRUIO_POLICY;
6908 			} else {
6909 				ASSERT(first_mp == mp);
6910 				mp->b_datap->db_struioflag &=
6911 				    ~STRUIO_EAGER;
6912 				mp->b_datap->db_struioflag |=
6913 				    STRUIO_POLICY;
6914 			}
6915 		} else {
6916 			/*
6917 			 * Discard first_mp early since we're dealing with a
6918 			 * fully-connected conn_t and tcp doesn't do policy in
6919 			 * this case.
6920 			 */
6921 			if (mctl_present) {
6922 				freeb(first_mp);
6923 				mctl_present = B_FALSE;
6924 			}
6925 			first_mp = mp;
6926 		}
6927 	}
6928 
6929 	/*
6930 	 * Initiate policy processing here if needed. If we get here from
6931 	 * icmp_inbound_error_fanout, ip_policy is false.
6932 	 */
6933 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6934 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6935 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6936 		if (mp == NULL) {
6937 			CONN_DEC_REF(connp);
6938 			if (mctl_present)
6939 				freeb(first_mp);
6940 			return;
6941 		} else if (mctl_present) {
6942 			ASSERT(first_mp != mp);
6943 			first_mp->b_cont = mp;
6944 		} else {
6945 			first_mp = mp;
6946 		}
6947 	}
6948 
6949 	/* Handle socket options. */
6950 	if (!syn_present &&
6951 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6952 		/* Add header */
6953 		ASSERT(recv_ill != NULL);
6954 		/*
6955 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6956 		 * IPF_RECVIF.
6957 		 */
6958 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6959 		    ipst);
6960 		if (mp == NULL) {
6961 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6962 			CONN_DEC_REF(connp);
6963 			if (mctl_present)
6964 				freeb(first_mp);
6965 			return;
6966 		} else if (mctl_present) {
6967 			/*
6968 			 * ip_add_info might return a new mp.
6969 			 */
6970 			ASSERT(first_mp != mp);
6971 			first_mp->b_cont = mp;
6972 		} else {
6973 			first_mp = mp;
6974 		}
6975 	}
6976 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6977 	if (IPCL_IS_TCP(connp)) {
6978 		/* do not drain, certain use cases can blow the stack */
6979 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6980 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6981 	} else {
6982 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6983 		(connp->conn_recv)(connp, first_mp, NULL);
6984 		CONN_DEC_REF(connp);
6985 	}
6986 }
6987 
6988 /*
6989  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6990  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6991  * is not consumed.
6992  *
6993  * One of four things can happen, all of which affect the passed-in mblk:
6994  *
6995  * 1.) ICMP messages that go through here just get returned TRUE.
6996  *
6997  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6998  *
6999  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7000  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7001  *
7002  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7003  */
7004 static boolean_t
7005 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7006     ipsec_stack_t *ipss)
7007 {
7008 	int shift, plen, iph_len;
7009 	ipha_t *ipha;
7010 	udpha_t *udpha;
7011 	uint32_t *spi;
7012 	uint32_t esp_ports;
7013 	uint8_t *orptr;
7014 	boolean_t free_ire;
7015 
7016 	if (DB_TYPE(mp) == M_CTL) {
7017 		/*
7018 		 * ICMP message with UDP inside.  Don't bother stripping, just
7019 		 * send it up.
7020 		 *
7021 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7022 		 * to ignore errors set by ICMP anyway ('cause they might be
7023 		 * forged), but that's the app's decision, not ours.
7024 		 */
7025 
7026 		/* Bunch of reality checks for DEBUG kernels... */
7027 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7028 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7029 
7030 		return (B_TRUE);
7031 	}
7032 
7033 	ipha = (ipha_t *)mp->b_rptr;
7034 	iph_len = IPH_HDR_LENGTH(ipha);
7035 	plen = ntohs(ipha->ipha_length);
7036 
7037 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7038 		/*
7039 		 * Most likely a keepalive for the benefit of an intervening
7040 		 * NAT.  These aren't for us, per se, so drop it.
7041 		 *
7042 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7043 		 * byte packets (keepalives are 1-byte), but we'll drop them
7044 		 * also.
7045 		 */
7046 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7047 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7048 		return (B_FALSE);
7049 	}
7050 
7051 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7052 		/* might as well pull it all up - it might be ESP. */
7053 		if (!pullupmsg(mp, -1)) {
7054 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7055 			    DROPPER(ipss, ipds_esp_nomem),
7056 			    &ipss->ipsec_dropper);
7057 			return (B_FALSE);
7058 		}
7059 
7060 		ipha = (ipha_t *)mp->b_rptr;
7061 	}
7062 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7063 	if (*spi == 0) {
7064 		/* UDP packet - remove 0-spi. */
7065 		shift = sizeof (uint32_t);
7066 	} else {
7067 		/* ESP-in-UDP packet - reduce to ESP. */
7068 		ipha->ipha_protocol = IPPROTO_ESP;
7069 		shift = sizeof (udpha_t);
7070 	}
7071 
7072 	/* Fix IP header */
7073 	ipha->ipha_length = htons(plen - shift);
7074 	ipha->ipha_hdr_checksum = 0;
7075 
7076 	orptr = mp->b_rptr;
7077 	mp->b_rptr += shift;
7078 
7079 	udpha = (udpha_t *)(orptr + iph_len);
7080 	if (*spi == 0) {
7081 		ASSERT((uint8_t *)ipha == orptr);
7082 		udpha->uha_length = htons(plen - shift - iph_len);
7083 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7084 		esp_ports = 0;
7085 	} else {
7086 		esp_ports = *((uint32_t *)udpha);
7087 		ASSERT(esp_ports != 0);
7088 	}
7089 	ovbcopy(orptr, orptr + shift, iph_len);
7090 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7091 		ipha = (ipha_t *)(orptr + shift);
7092 
7093 		free_ire = (ire == NULL);
7094 		if (free_ire) {
7095 			/* Re-acquire ire. */
7096 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7097 			    ipss->ipsec_netstack->netstack_ip);
7098 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7099 				if (ire != NULL)
7100 					ire_refrele(ire);
7101 				/*
7102 				 * Do a regular freemsg(), as this is an IP
7103 				 * error (no local route) not an IPsec one.
7104 				 */
7105 				freemsg(mp);
7106 			}
7107 		}
7108 
7109 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7110 		if (free_ire)
7111 			ire_refrele(ire);
7112 	}
7113 
7114 	return (esp_ports == 0);
7115 }
7116 
7117 /*
7118  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7119  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7120  * Caller is responsible for dropping references to the conn, and freeing
7121  * first_mp.
7122  *
7123  * IPQoS Notes
7124  * Before sending it to the client, invoke IPPF processing. Policy processing
7125  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7126  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7127  * ip_wput_local, ip_policy is false.
7128  */
7129 static void
7130 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7131     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7132     boolean_t ip_policy)
7133 {
7134 	boolean_t	mctl_present = (first_mp != NULL);
7135 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7136 	uint32_t	ill_index;
7137 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7138 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7139 
7140 	ASSERT(ill != NULL);
7141 
7142 	if (mctl_present)
7143 		first_mp->b_cont = mp;
7144 	else
7145 		first_mp = mp;
7146 
7147 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7148 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7149 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7150 		freemsg(first_mp);
7151 		return;
7152 	}
7153 
7154 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7155 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7156 		    NULL, mctl_present);
7157 		/* Freed by ipsec_check_inbound_policy(). */
7158 		if (first_mp == NULL) {
7159 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7160 			return;
7161 		}
7162 	}
7163 	if (mctl_present)
7164 		freeb(first_mp);
7165 
7166 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7167 	if (connp->conn_udp->udp_nat_t_endpoint) {
7168 		if (mctl_present) {
7169 			/* mctl_present *shouldn't* happen. */
7170 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7171 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7172 			    &ipss->ipsec_dropper);
7173 			return;
7174 		}
7175 
7176 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7177 			return;
7178 	}
7179 
7180 	/* Handle options. */
7181 	if (connp->conn_recvif)
7182 		in_flags = IPF_RECVIF;
7183 	/*
7184 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7185 	 * passed to ip_add_info is based on IP version of connp.
7186 	 */
7187 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7188 		if (connp->conn_af_isv6) {
7189 			/*
7190 			 * V6 only needs index
7191 			 */
7192 			in_flags |= IPF_RECVIF;
7193 		} else {
7194 			/*
7195 			 * V4 needs index + matching address.
7196 			 */
7197 			in_flags |= IPF_RECVADDR;
7198 		}
7199 	}
7200 
7201 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7202 		in_flags |= IPF_RECVSLLA;
7203 
7204 	/*
7205 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7206 	 * freed if the packet is dropped. The caller will do so.
7207 	 */
7208 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7209 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7210 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7211 		if (mp == NULL) {
7212 			return;
7213 		}
7214 	}
7215 	if ((in_flags != 0) &&
7216 	    (mp->b_datap->db_type != M_CTL)) {
7217 		/*
7218 		 * The actual data will be contained in b_cont
7219 		 * upon successful return of the following call
7220 		 * else original mblk is returned
7221 		 */
7222 		ASSERT(recv_ill != NULL);
7223 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7224 		    ipst);
7225 	}
7226 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7227 	/* Send it upstream */
7228 	(connp->conn_recv)(connp, mp, NULL);
7229 }
7230 
7231 /*
7232  * Fanout for UDP packets.
7233  * The caller puts <fport, lport> in the ports parameter.
7234  *
7235  * If SO_REUSEADDR is set all multicast and broadcast packets
7236  * will be delivered to all streams bound to the same port.
7237  *
7238  * Zones notes:
7239  * Multicast and broadcast packets will be distributed to streams in all zones.
7240  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7241  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7242  * packets. To maintain this behavior with multiple zones, the conns are grouped
7243  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7244  * each zone. If unset, all the following conns in the same zone are skipped.
7245  */
7246 static void
7247 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7248     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7249     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7250 {
7251 	uint32_t	dstport, srcport;
7252 	ipaddr_t	dst;
7253 	mblk_t		*first_mp;
7254 	boolean_t	secure;
7255 	in6_addr_t	v6src;
7256 	conn_t		*connp;
7257 	connf_t		*connfp;
7258 	conn_t		*first_connp;
7259 	conn_t		*next_connp;
7260 	mblk_t		*mp1, *first_mp1;
7261 	ipaddr_t	src;
7262 	zoneid_t	last_zoneid;
7263 	boolean_t	reuseaddr;
7264 	boolean_t	shared_addr;
7265 	boolean_t	unlabeled;
7266 	ip_stack_t	*ipst;
7267 
7268 	ASSERT(recv_ill != NULL);
7269 	ipst = recv_ill->ill_ipst;
7270 
7271 	first_mp = mp;
7272 	if (mctl_present) {
7273 		mp = first_mp->b_cont;
7274 		first_mp->b_cont = NULL;
7275 		secure = ipsec_in_is_secure(first_mp);
7276 		ASSERT(mp != NULL);
7277 	} else {
7278 		first_mp = NULL;
7279 		secure = B_FALSE;
7280 	}
7281 
7282 	/* Extract ports in net byte order */
7283 	dstport = htons(ntohl(ports) & 0xFFFF);
7284 	srcport = htons(ntohl(ports) >> 16);
7285 	dst = ipha->ipha_dst;
7286 	src = ipha->ipha_src;
7287 
7288 	unlabeled = B_FALSE;
7289 	if (is_system_labeled())
7290 		/* Cred cannot be null on IPv4 */
7291 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7292 		    TSLF_UNLABELED) != 0;
7293 	shared_addr = (zoneid == ALL_ZONES);
7294 	if (shared_addr) {
7295 		/*
7296 		 * No need to handle exclusive-stack zones since ALL_ZONES
7297 		 * only applies to the shared stack.
7298 		 */
7299 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7300 		/*
7301 		 * If no shared MLP is found, tsol_mlp_findzone returns
7302 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7303 		 * search for the zone based on the packet label.
7304 		 *
7305 		 * If there is such a zone, we prefer to find a
7306 		 * connection in it.  Otherwise, we look for a
7307 		 * MAC-exempt connection in any zone whose label
7308 		 * dominates the default label on the packet.
7309 		 */
7310 		if (zoneid == ALL_ZONES)
7311 			zoneid = tsol_packet_to_zoneid(mp);
7312 		else
7313 			unlabeled = B_FALSE;
7314 	}
7315 
7316 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7317 	mutex_enter(&connfp->connf_lock);
7318 	connp = connfp->connf_head;
7319 	if (!broadcast && !CLASSD(dst)) {
7320 		/*
7321 		 * Not broadcast or multicast. Send to the one (first)
7322 		 * client we find. No need to check conn_wantpacket()
7323 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7324 		 * IPv4 unicast packets.
7325 		 */
7326 		while ((connp != NULL) &&
7327 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7328 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7329 		    !(unlabeled && connp->conn_mac_exempt)))) {
7330 			/*
7331 			 * We keep searching since the conn did not match,
7332 			 * or its zone did not match and it is not either
7333 			 * an allzones conn or a mac exempt conn (if the
7334 			 * sender is unlabeled.)
7335 			 */
7336 			connp = connp->conn_next;
7337 		}
7338 
7339 		if (connp == NULL ||
7340 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7341 			goto notfound;
7342 
7343 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7344 
7345 		if (is_system_labeled() &&
7346 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7347 		    connp))
7348 			goto notfound;
7349 
7350 		CONN_INC_REF(connp);
7351 		mutex_exit(&connfp->connf_lock);
7352 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7353 		    flags, recv_ill, ip_policy);
7354 		IP_STAT(ipst, ip_udp_fannorm);
7355 		CONN_DEC_REF(connp);
7356 		return;
7357 	}
7358 
7359 	/*
7360 	 * Broadcast and multicast case
7361 	 *
7362 	 * Need to check conn_wantpacket().
7363 	 * If SO_REUSEADDR has been set on the first we send the
7364 	 * packet to all clients that have joined the group and
7365 	 * match the port.
7366 	 */
7367 
7368 	while (connp != NULL) {
7369 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7370 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7371 		    (!is_system_labeled() ||
7372 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7373 		    connp)))
7374 			break;
7375 		connp = connp->conn_next;
7376 	}
7377 
7378 	if (connp == NULL ||
7379 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7380 		goto notfound;
7381 
7382 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7383 
7384 	first_connp = connp;
7385 	/*
7386 	 * When SO_REUSEADDR is not set, send the packet only to the first
7387 	 * matching connection in its zone by keeping track of the zoneid.
7388 	 */
7389 	reuseaddr = first_connp->conn_reuseaddr;
7390 	last_zoneid = first_connp->conn_zoneid;
7391 
7392 	CONN_INC_REF(connp);
7393 	connp = connp->conn_next;
7394 	for (;;) {
7395 		while (connp != NULL) {
7396 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7397 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7398 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7399 			    (!is_system_labeled() ||
7400 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7401 			    shared_addr, connp)))
7402 				break;
7403 			connp = connp->conn_next;
7404 		}
7405 		/*
7406 		 * Just copy the data part alone. The mctl part is
7407 		 * needed just for verifying policy and it is never
7408 		 * sent up.
7409 		 */
7410 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7411 		    ((mp1 = copymsg(mp)) == NULL))) {
7412 			/*
7413 			 * No more interested clients or memory
7414 			 * allocation failed
7415 			 */
7416 			connp = first_connp;
7417 			break;
7418 		}
7419 		if (connp->conn_zoneid != last_zoneid) {
7420 			/*
7421 			 * Update the zoneid so that the packet isn't sent to
7422 			 * any more conns in the same zone unless SO_REUSEADDR
7423 			 * is set.
7424 			 */
7425 			reuseaddr = connp->conn_reuseaddr;
7426 			last_zoneid = connp->conn_zoneid;
7427 		}
7428 		if (first_mp != NULL) {
7429 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7430 			    ipsec_info_type == IPSEC_IN);
7431 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7432 			    ipst->ips_netstack);
7433 			if (first_mp1 == NULL) {
7434 				freemsg(mp1);
7435 				connp = first_connp;
7436 				break;
7437 			}
7438 		} else {
7439 			first_mp1 = NULL;
7440 		}
7441 		CONN_INC_REF(connp);
7442 		mutex_exit(&connfp->connf_lock);
7443 		/*
7444 		 * IPQoS notes: We don't send the packet for policy
7445 		 * processing here, will do it for the last one (below).
7446 		 * i.e. we do it per-packet now, but if we do policy
7447 		 * processing per-conn, then we would need to do it
7448 		 * here too.
7449 		 */
7450 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7451 		    ipha, flags, recv_ill, B_FALSE);
7452 		mutex_enter(&connfp->connf_lock);
7453 		/* Follow the next pointer before releasing the conn. */
7454 		next_connp = connp->conn_next;
7455 		IP_STAT(ipst, ip_udp_fanmb);
7456 		CONN_DEC_REF(connp);
7457 		connp = next_connp;
7458 	}
7459 
7460 	/* Last one.  Send it upstream. */
7461 	mutex_exit(&connfp->connf_lock);
7462 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7463 	    recv_ill, ip_policy);
7464 	IP_STAT(ipst, ip_udp_fanmb);
7465 	CONN_DEC_REF(connp);
7466 	return;
7467 
7468 notfound:
7469 
7470 	mutex_exit(&connfp->connf_lock);
7471 	IP_STAT(ipst, ip_udp_fanothers);
7472 	/*
7473 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7474 	 * have already been matched above, since they live in the IPv4
7475 	 * fanout tables. This implies we only need to
7476 	 * check for IPv6 in6addr_any endpoints here.
7477 	 * Thus we compare using ipv6_all_zeros instead of the destination
7478 	 * address, except for the multicast group membership lookup which
7479 	 * uses the IPv4 destination.
7480 	 */
7481 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7482 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7483 	mutex_enter(&connfp->connf_lock);
7484 	connp = connfp->connf_head;
7485 	if (!broadcast && !CLASSD(dst)) {
7486 		while (connp != NULL) {
7487 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7488 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7489 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7490 			    !connp->conn_ipv6_v6only)
7491 				break;
7492 			connp = connp->conn_next;
7493 		}
7494 
7495 		if (connp != NULL && is_system_labeled() &&
7496 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7497 		    connp))
7498 			connp = NULL;
7499 
7500 		if (connp == NULL ||
7501 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7502 			/*
7503 			 * No one bound to this port.  Is
7504 			 * there a client that wants all
7505 			 * unclaimed datagrams?
7506 			 */
7507 			mutex_exit(&connfp->connf_lock);
7508 
7509 			if (mctl_present)
7510 				first_mp->b_cont = mp;
7511 			else
7512 				first_mp = mp;
7513 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7514 			    connf_head != NULL) {
7515 				ip_fanout_proto(q, first_mp, ill, ipha,
7516 				    flags | IP_FF_RAWIP, mctl_present,
7517 				    ip_policy, recv_ill, zoneid);
7518 			} else {
7519 				if (ip_fanout_send_icmp(q, first_mp, flags,
7520 				    ICMP_DEST_UNREACHABLE,
7521 				    ICMP_PORT_UNREACHABLE,
7522 				    mctl_present, zoneid, ipst)) {
7523 					BUMP_MIB(ill->ill_ip_mib,
7524 					    udpIfStatsNoPorts);
7525 				}
7526 			}
7527 			return;
7528 		}
7529 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7530 
7531 		CONN_INC_REF(connp);
7532 		mutex_exit(&connfp->connf_lock);
7533 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7534 		    flags, recv_ill, ip_policy);
7535 		CONN_DEC_REF(connp);
7536 		return;
7537 	}
7538 	/*
7539 	 * IPv4 multicast packet being delivered to an AF_INET6
7540 	 * in6addr_any endpoint.
7541 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7542 	 * and not conn_wantpacket_v6() since any multicast membership is
7543 	 * for an IPv4-mapped multicast address.
7544 	 * The packet is sent to all clients in all zones that have joined the
7545 	 * group and match the port.
7546 	 */
7547 	while (connp != NULL) {
7548 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7549 		    srcport, v6src) &&
7550 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7551 		    (!is_system_labeled() ||
7552 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7553 		    connp)))
7554 			break;
7555 		connp = connp->conn_next;
7556 	}
7557 
7558 	if (connp == NULL ||
7559 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7560 		/*
7561 		 * No one bound to this port.  Is
7562 		 * there a client that wants all
7563 		 * unclaimed datagrams?
7564 		 */
7565 		mutex_exit(&connfp->connf_lock);
7566 
7567 		if (mctl_present)
7568 			first_mp->b_cont = mp;
7569 		else
7570 			first_mp = mp;
7571 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7572 		    NULL) {
7573 			ip_fanout_proto(q, first_mp, ill, ipha,
7574 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7575 			    recv_ill, zoneid);
7576 		} else {
7577 			/*
7578 			 * We used to attempt to send an icmp error here, but
7579 			 * since this is known to be a multicast packet
7580 			 * and we don't send icmp errors in response to
7581 			 * multicast, just drop the packet and give up sooner.
7582 			 */
7583 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7584 			freemsg(first_mp);
7585 		}
7586 		return;
7587 	}
7588 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7589 
7590 	first_connp = connp;
7591 
7592 	CONN_INC_REF(connp);
7593 	connp = connp->conn_next;
7594 	for (;;) {
7595 		while (connp != NULL) {
7596 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7597 			    ipv6_all_zeros, srcport, v6src) &&
7598 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7599 			    (!is_system_labeled() ||
7600 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7601 			    shared_addr, connp)))
7602 				break;
7603 			connp = connp->conn_next;
7604 		}
7605 		/*
7606 		 * Just copy the data part alone. The mctl part is
7607 		 * needed just for verifying policy and it is never
7608 		 * sent up.
7609 		 */
7610 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7611 		    ((mp1 = copymsg(mp)) == NULL))) {
7612 			/*
7613 			 * No more intested clients or memory
7614 			 * allocation failed
7615 			 */
7616 			connp = first_connp;
7617 			break;
7618 		}
7619 		if (first_mp != NULL) {
7620 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7621 			    ipsec_info_type == IPSEC_IN);
7622 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7623 			    ipst->ips_netstack);
7624 			if (first_mp1 == NULL) {
7625 				freemsg(mp1);
7626 				connp = first_connp;
7627 				break;
7628 			}
7629 		} else {
7630 			first_mp1 = NULL;
7631 		}
7632 		CONN_INC_REF(connp);
7633 		mutex_exit(&connfp->connf_lock);
7634 		/*
7635 		 * IPQoS notes: We don't send the packet for policy
7636 		 * processing here, will do it for the last one (below).
7637 		 * i.e. we do it per-packet now, but if we do policy
7638 		 * processing per-conn, then we would need to do it
7639 		 * here too.
7640 		 */
7641 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7642 		    ipha, flags, recv_ill, B_FALSE);
7643 		mutex_enter(&connfp->connf_lock);
7644 		/* Follow the next pointer before releasing the conn. */
7645 		next_connp = connp->conn_next;
7646 		CONN_DEC_REF(connp);
7647 		connp = next_connp;
7648 	}
7649 
7650 	/* Last one.  Send it upstream. */
7651 	mutex_exit(&connfp->connf_lock);
7652 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7653 	    recv_ill, ip_policy);
7654 	CONN_DEC_REF(connp);
7655 }
7656 
7657 /*
7658  * Complete the ip_wput header so that it
7659  * is possible to generate ICMP
7660  * errors.
7661  */
7662 int
7663 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7664 {
7665 	ire_t *ire;
7666 
7667 	if (ipha->ipha_src == INADDR_ANY) {
7668 		ire = ire_lookup_local(zoneid, ipst);
7669 		if (ire == NULL) {
7670 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7671 			return (1);
7672 		}
7673 		ipha->ipha_src = ire->ire_addr;
7674 		ire_refrele(ire);
7675 	}
7676 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7677 	ipha->ipha_hdr_checksum = 0;
7678 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7679 	return (0);
7680 }
7681 
7682 /*
7683  * Nobody should be sending
7684  * packets up this stream
7685  */
7686 static void
7687 ip_lrput(queue_t *q, mblk_t *mp)
7688 {
7689 	mblk_t *mp1;
7690 
7691 	switch (mp->b_datap->db_type) {
7692 	case M_FLUSH:
7693 		/* Turn around */
7694 		if (*mp->b_rptr & FLUSHW) {
7695 			*mp->b_rptr &= ~FLUSHR;
7696 			qreply(q, mp);
7697 			return;
7698 		}
7699 		break;
7700 	}
7701 	/* Could receive messages that passed through ar_rput */
7702 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7703 		mp1->b_prev = mp1->b_next = NULL;
7704 	freemsg(mp);
7705 }
7706 
7707 /* Nobody should be sending packets down this stream */
7708 /* ARGSUSED */
7709 void
7710 ip_lwput(queue_t *q, mblk_t *mp)
7711 {
7712 	freemsg(mp);
7713 }
7714 
7715 /*
7716  * Move the first hop in any source route to ipha_dst and remove that part of
7717  * the source route.  Called by other protocols.  Errors in option formatting
7718  * are ignored - will be handled by ip_wput_options Return the final
7719  * destination (either ipha_dst or the last entry in a source route.)
7720  */
7721 ipaddr_t
7722 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7723 {
7724 	ipoptp_t	opts;
7725 	uchar_t		*opt;
7726 	uint8_t		optval;
7727 	uint8_t		optlen;
7728 	ipaddr_t	dst;
7729 	int		i;
7730 	ire_t		*ire;
7731 	ip_stack_t	*ipst = ns->netstack_ip;
7732 
7733 	ip2dbg(("ip_massage_options\n"));
7734 	dst = ipha->ipha_dst;
7735 	for (optval = ipoptp_first(&opts, ipha);
7736 	    optval != IPOPT_EOL;
7737 	    optval = ipoptp_next(&opts)) {
7738 		opt = opts.ipoptp_cur;
7739 		switch (optval) {
7740 			uint8_t off;
7741 		case IPOPT_SSRR:
7742 		case IPOPT_LSRR:
7743 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7744 				ip1dbg(("ip_massage_options: bad src route\n"));
7745 				break;
7746 			}
7747 			optlen = opts.ipoptp_len;
7748 			off = opt[IPOPT_OFFSET];
7749 			off--;
7750 		redo_srr:
7751 			if (optlen < IP_ADDR_LEN ||
7752 			    off > optlen - IP_ADDR_LEN) {
7753 				/* End of source route */
7754 				ip1dbg(("ip_massage_options: end of SR\n"));
7755 				break;
7756 			}
7757 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7758 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7759 			    ntohl(dst)));
7760 			/*
7761 			 * Check if our address is present more than
7762 			 * once as consecutive hops in source route.
7763 			 * XXX verify per-interface ip_forwarding
7764 			 * for source route?
7765 			 */
7766 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7767 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7768 			if (ire != NULL) {
7769 				ire_refrele(ire);
7770 				off += IP_ADDR_LEN;
7771 				goto redo_srr;
7772 			}
7773 			if (dst == htonl(INADDR_LOOPBACK)) {
7774 				ip1dbg(("ip_massage_options: loopback addr in "
7775 				    "source route!\n"));
7776 				break;
7777 			}
7778 			/*
7779 			 * Update ipha_dst to be the first hop and remove the
7780 			 * first hop from the source route (by overwriting
7781 			 * part of the option with NOP options).
7782 			 */
7783 			ipha->ipha_dst = dst;
7784 			/* Put the last entry in dst */
7785 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7786 			    3;
7787 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7788 
7789 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7790 			    ntohl(dst)));
7791 			/* Move down and overwrite */
7792 			opt[IP_ADDR_LEN] = opt[0];
7793 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7794 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7795 			for (i = 0; i < IP_ADDR_LEN; i++)
7796 				opt[i] = IPOPT_NOP;
7797 			break;
7798 		}
7799 	}
7800 	return (dst);
7801 }
7802 
7803 /*
7804  * Return the network mask
7805  * associated with the specified address.
7806  */
7807 ipaddr_t
7808 ip_net_mask(ipaddr_t addr)
7809 {
7810 	uchar_t	*up = (uchar_t *)&addr;
7811 	ipaddr_t mask = 0;
7812 	uchar_t	*maskp = (uchar_t *)&mask;
7813 
7814 #if defined(__i386) || defined(__amd64)
7815 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7816 #endif
7817 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7818 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7819 #endif
7820 	if (CLASSD(addr)) {
7821 		maskp[0] = 0xF0;
7822 		return (mask);
7823 	}
7824 
7825 	/* We assume Class E default netmask to be 32 */
7826 	if (CLASSE(addr))
7827 		return (0xffffffffU);
7828 
7829 	if (addr == 0)
7830 		return (0);
7831 	maskp[0] = 0xFF;
7832 	if ((up[0] & 0x80) == 0)
7833 		return (mask);
7834 
7835 	maskp[1] = 0xFF;
7836 	if ((up[0] & 0xC0) == 0x80)
7837 		return (mask);
7838 
7839 	maskp[2] = 0xFF;
7840 	if ((up[0] & 0xE0) == 0xC0)
7841 		return (mask);
7842 
7843 	/* Otherwise return no mask */
7844 	return ((ipaddr_t)0);
7845 }
7846 
7847 /*
7848  * Helper ill lookup function used by IPsec.
7849  */
7850 ill_t *
7851 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7852 {
7853 	ill_t *ret_ill;
7854 
7855 	ASSERT(ifindex != 0);
7856 
7857 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7858 	    ipst);
7859 	if (ret_ill == NULL) {
7860 		if (isv6) {
7861 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7862 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7863 			    ifindex));
7864 		} else {
7865 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7866 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7867 			    ifindex));
7868 		}
7869 		freemsg(first_mp);
7870 		return (NULL);
7871 	}
7872 	return (ret_ill);
7873 }
7874 
7875 /*
7876  * IPv4 -
7877  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7878  * out a packet to a destination address for which we do not have specific
7879  * (or sufficient) routing information.
7880  *
7881  * NOTE : These are the scopes of some of the variables that point at IRE,
7882  *	  which needs to be followed while making any future modifications
7883  *	  to avoid memory leaks.
7884  *
7885  *	- ire and sire are the entries looked up initially by
7886  *	  ire_ftable_lookup.
7887  *	- ipif_ire is used to hold the interface ire associated with
7888  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7889  *	  it before branching out to error paths.
7890  *	- save_ire is initialized before ire_create, so that ire returned
7891  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7892  *	  before breaking out of the switch.
7893  *
7894  *	Thus on failures, we have to REFRELE only ire and sire, if they
7895  *	are not NULL.
7896  */
7897 void
7898 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7899     zoneid_t zoneid, ip_stack_t *ipst)
7900 {
7901 	areq_t	*areq;
7902 	ipaddr_t gw = 0;
7903 	ire_t	*ire = NULL;
7904 	mblk_t	*res_mp;
7905 	ipaddr_t *addrp;
7906 	ipaddr_t nexthop_addr;
7907 	ipif_t  *src_ipif = NULL;
7908 	ill_t	*dst_ill = NULL;
7909 	ipha_t  *ipha;
7910 	ire_t	*sire = NULL;
7911 	mblk_t	*first_mp;
7912 	ire_t	*save_ire;
7913 	ushort_t ire_marks = 0;
7914 	boolean_t mctl_present;
7915 	ipsec_out_t *io;
7916 	mblk_t	*saved_mp;
7917 	ire_t	*first_sire = NULL;
7918 	mblk_t	*copy_mp = NULL;
7919 	mblk_t	*xmit_mp = NULL;
7920 	ipaddr_t save_dst;
7921 	uint32_t multirt_flags =
7922 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7923 	boolean_t multirt_is_resolvable;
7924 	boolean_t multirt_resolve_next;
7925 	boolean_t unspec_src;
7926 	boolean_t ip_nexthop = B_FALSE;
7927 	tsol_ire_gw_secattr_t *attrp = NULL;
7928 	tsol_gcgrp_t *gcgrp = NULL;
7929 	tsol_gcgrp_addr_t ga;
7930 
7931 	if (ip_debug > 2) {
7932 		/* ip1dbg */
7933 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7934 	}
7935 
7936 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7937 	if (mctl_present) {
7938 		io = (ipsec_out_t *)first_mp->b_rptr;
7939 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7940 		ASSERT(zoneid == io->ipsec_out_zoneid);
7941 		ASSERT(zoneid != ALL_ZONES);
7942 	}
7943 
7944 	ipha = (ipha_t *)mp->b_rptr;
7945 
7946 	/* All multicast lookups come through ip_newroute_ipif() */
7947 	if (CLASSD(dst)) {
7948 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7949 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7950 		freemsg(first_mp);
7951 		return;
7952 	}
7953 
7954 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7955 		ip_nexthop = B_TRUE;
7956 		nexthop_addr = io->ipsec_out_nexthop_addr;
7957 	}
7958 	/*
7959 	 * If this IRE is created for forwarding or it is not for
7960 	 * traffic for congestion controlled protocols, mark it as temporary.
7961 	 */
7962 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7963 		ire_marks |= IRE_MARK_TEMPORARY;
7964 
7965 	/*
7966 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7967 	 * chain until it gets the most specific information available.
7968 	 * For example, we know that there is no IRE_CACHE for this dest,
7969 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7970 	 * ire_ftable_lookup will look up the gateway, etc.
7971 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7972 	 * to the destination, of equal netmask length in the forward table,
7973 	 * will be recursively explored. If no information is available
7974 	 * for the final gateway of that route, we force the returned ire
7975 	 * to be equal to sire using MATCH_IRE_PARENT.
7976 	 * At least, in this case we have a starting point (in the buckets)
7977 	 * to look for other routes to the destination in the forward table.
7978 	 * This is actually used only for multirouting, where a list
7979 	 * of routes has to be processed in sequence.
7980 	 *
7981 	 * In the process of coming up with the most specific information,
7982 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7983 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7984 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7985 	 * Two caveats when handling incomplete ire's in ip_newroute:
7986 	 * - we should be careful when accessing its ire_nce (specifically
7987 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7988 	 * - not all legacy code path callers are prepared to handle
7989 	 *   incomplete ire's, so we should not create/add incomplete
7990 	 *   ire_cache entries here. (See discussion about temporary solution
7991 	 *   further below).
7992 	 *
7993 	 * In order to minimize packet dropping, and to preserve existing
7994 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7995 	 * gateway, and instead use the IF_RESOLVER ire to send out
7996 	 * another request to ARP (this is achieved by passing the
7997 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7998 	 * arp response comes back in ip_wput_nondata, we will create
7999 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8000 	 *
8001 	 * Note that this is a temporary solution; the correct solution is
8002 	 * to create an incomplete  per-dst ire_cache entry, and send the
8003 	 * packet out when the gw's nce is resolved. In order to achieve this,
8004 	 * all packet processing must have been completed prior to calling
8005 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8006 	 * to be modified to accomodate this solution.
8007 	 */
8008 	if (ip_nexthop) {
8009 		/*
8010 		 * The first time we come here, we look for an IRE_INTERFACE
8011 		 * entry for the specified nexthop, set the dst to be the
8012 		 * nexthop address and create an IRE_CACHE entry for the
8013 		 * nexthop. The next time around, we are able to find an
8014 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8015 		 * nexthop address and create an IRE_CACHE entry for the
8016 		 * destination address via the specified nexthop.
8017 		 */
8018 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8019 		    msg_getlabel(mp), ipst);
8020 		if (ire != NULL) {
8021 			gw = nexthop_addr;
8022 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8023 		} else {
8024 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8025 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8026 			    msg_getlabel(mp),
8027 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8028 			    ipst);
8029 			if (ire != NULL) {
8030 				dst = nexthop_addr;
8031 			}
8032 		}
8033 	} else {
8034 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8035 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8036 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8037 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8038 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8039 		    ipst);
8040 	}
8041 
8042 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8043 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8044 
8045 	/*
8046 	 * This loop is run only once in most cases.
8047 	 * We loop to resolve further routes only when the destination
8048 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8049 	 */
8050 	do {
8051 		/* Clear the previous iteration's values */
8052 		if (src_ipif != NULL) {
8053 			ipif_refrele(src_ipif);
8054 			src_ipif = NULL;
8055 		}
8056 		if (dst_ill != NULL) {
8057 			ill_refrele(dst_ill);
8058 			dst_ill = NULL;
8059 		}
8060 
8061 		multirt_resolve_next = B_FALSE;
8062 		/*
8063 		 * We check if packets have to be multirouted.
8064 		 * In this case, given the current <ire, sire> couple,
8065 		 * we look for the next suitable <ire, sire>.
8066 		 * This check is done in ire_multirt_lookup(),
8067 		 * which applies various criteria to find the next route
8068 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8069 		 * unchanged if it detects it has not been tried yet.
8070 		 */
8071 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8072 			ip3dbg(("ip_newroute: starting next_resolution "
8073 			    "with first_mp %p, tag %d\n",
8074 			    (void *)first_mp,
8075 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8076 
8077 			ASSERT(sire != NULL);
8078 			multirt_is_resolvable =
8079 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8080 			    msg_getlabel(mp), ipst);
8081 
8082 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8083 			    "ire %p, sire %p\n",
8084 			    multirt_is_resolvable,
8085 			    (void *)ire, (void *)sire));
8086 
8087 			if (!multirt_is_resolvable) {
8088 				/*
8089 				 * No more multirt route to resolve; give up
8090 				 * (all routes resolved or no more
8091 				 * resolvable routes).
8092 				 */
8093 				if (ire != NULL) {
8094 					ire_refrele(ire);
8095 					ire = NULL;
8096 				}
8097 			} else {
8098 				ASSERT(sire != NULL);
8099 				ASSERT(ire != NULL);
8100 				/*
8101 				 * We simply use first_sire as a flag that
8102 				 * indicates if a resolvable multirt route
8103 				 * has already been found.
8104 				 * If it is not the case, we may have to send
8105 				 * an ICMP error to report that the
8106 				 * destination is unreachable.
8107 				 * We do not IRE_REFHOLD first_sire.
8108 				 */
8109 				if (first_sire == NULL) {
8110 					first_sire = sire;
8111 				}
8112 			}
8113 		}
8114 		if (ire == NULL) {
8115 			if (ip_debug > 3) {
8116 				/* ip2dbg */
8117 				pr_addr_dbg("ip_newroute: "
8118 				    "can't resolve %s\n", AF_INET, &dst);
8119 			}
8120 			ip3dbg(("ip_newroute: "
8121 			    "ire %p, sire %p, first_sire %p\n",
8122 			    (void *)ire, (void *)sire, (void *)first_sire));
8123 
8124 			if (sire != NULL) {
8125 				ire_refrele(sire);
8126 				sire = NULL;
8127 			}
8128 
8129 			if (first_sire != NULL) {
8130 				/*
8131 				 * At least one multirt route has been found
8132 				 * in the same call to ip_newroute();
8133 				 * there is no need to report an ICMP error.
8134 				 * first_sire was not IRE_REFHOLDed.
8135 				 */
8136 				MULTIRT_DEBUG_UNTAG(first_mp);
8137 				freemsg(first_mp);
8138 				return;
8139 			}
8140 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8141 			    RTA_DST, ipst);
8142 			goto icmp_err_ret;
8143 		}
8144 
8145 		/*
8146 		 * Verify that the returned IRE does not have either
8147 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8148 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8149 		 */
8150 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8151 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8152 			goto icmp_err_ret;
8153 		}
8154 		/*
8155 		 * Increment the ire_ob_pkt_count field for ire if it is an
8156 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8157 		 * increment the same for the parent IRE, sire, if it is some
8158 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8159 		 */
8160 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8161 			UPDATE_OB_PKT_COUNT(ire);
8162 			ire->ire_last_used_time = lbolt;
8163 		}
8164 
8165 		if (sire != NULL) {
8166 			gw = sire->ire_gateway_addr;
8167 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8168 			    IRE_INTERFACE)) == 0);
8169 			UPDATE_OB_PKT_COUNT(sire);
8170 			sire->ire_last_used_time = lbolt;
8171 		}
8172 		/*
8173 		 * We have a route to reach the destination.  Find the
8174 		 * appropriate ill, then get a source address using
8175 		 * ipif_select_source().
8176 		 *
8177 		 * If we are here trying to create an IRE_CACHE for an offlink
8178 		 * destination and have an IRE_CACHE entry for VNI, then use
8179 		 * ire_stq instead since VNI's queue is a black hole.
8180 		 */
8181 		if ((ire->ire_type == IRE_CACHE) &&
8182 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8183 			dst_ill = ire->ire_stq->q_ptr;
8184 			ill_refhold(dst_ill);
8185 		} else {
8186 			ill_t *ill = ire->ire_ipif->ipif_ill;
8187 
8188 			if (IS_IPMP(ill)) {
8189 				dst_ill =
8190 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8191 			} else {
8192 				dst_ill = ill;
8193 				ill_refhold(dst_ill);
8194 			}
8195 		}
8196 
8197 		if (dst_ill == NULL) {
8198 			if (ip_debug > 2) {
8199 				pr_addr_dbg("ip_newroute: no dst "
8200 				    "ill for dst %s\n", AF_INET, &dst);
8201 			}
8202 			goto icmp_err_ret;
8203 		}
8204 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8205 
8206 		/*
8207 		 * Pick the best source address from dst_ill.
8208 		 *
8209 		 * 1) Try to pick the source address from the destination
8210 		 *    route. Clustering assumes that when we have multiple
8211 		 *    prefixes hosted on an interface, the prefix of the
8212 		 *    source address matches the prefix of the destination
8213 		 *    route. We do this only if the address is not
8214 		 *    DEPRECATED.
8215 		 *
8216 		 * 2) If the conn is in a different zone than the ire, we
8217 		 *    need to pick a source address from the right zone.
8218 		 */
8219 		ASSERT(src_ipif == NULL);
8220 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8221 			/*
8222 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8223 			 * Check that the ipif matching the requested source
8224 			 * address still exists.
8225 			 */
8226 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8227 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8228 		}
8229 
8230 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8231 
8232 		if (src_ipif == NULL &&
8233 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8234 			ire_marks |= IRE_MARK_USESRC_CHECK;
8235 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8236 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8237 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8238 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8239 			    ire->ire_zoneid != ALL_ZONES) ||
8240 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8241 				/*
8242 				 * If the destination is reachable via a
8243 				 * given gateway, the selected source address
8244 				 * should be in the same subnet as the gateway.
8245 				 * Otherwise, the destination is not reachable.
8246 				 *
8247 				 * If there are no interfaces on the same subnet
8248 				 * as the destination, ipif_select_source gives
8249 				 * first non-deprecated interface which might be
8250 				 * on a different subnet than the gateway.
8251 				 * This is not desirable. Hence pass the dst_ire
8252 				 * source address to ipif_select_source.
8253 				 * It is sure that the destination is reachable
8254 				 * with the dst_ire source address subnet.
8255 				 * So passing dst_ire source address to
8256 				 * ipif_select_source will make sure that the
8257 				 * selected source will be on the same subnet
8258 				 * as dst_ire source address.
8259 				 */
8260 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8261 
8262 				src_ipif = ipif_select_source(dst_ill, saddr,
8263 				    zoneid);
8264 				if (src_ipif == NULL) {
8265 					if (ip_debug > 2) {
8266 						pr_addr_dbg("ip_newroute: "
8267 						    "no src for dst %s ",
8268 						    AF_INET, &dst);
8269 						printf("on interface %s\n",
8270 						    dst_ill->ill_name);
8271 					}
8272 					goto icmp_err_ret;
8273 				}
8274 			} else {
8275 				src_ipif = ire->ire_ipif;
8276 				ASSERT(src_ipif != NULL);
8277 				/* hold src_ipif for uniformity */
8278 				ipif_refhold(src_ipif);
8279 			}
8280 		}
8281 
8282 		/*
8283 		 * Assign a source address while we have the conn.
8284 		 * We can't have ip_wput_ire pick a source address when the
8285 		 * packet returns from arp since we need to look at
8286 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8287 		 * going through arp.
8288 		 *
8289 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8290 		 *	  it uses ip6i to store this information.
8291 		 */
8292 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8293 			ipha->ipha_src = src_ipif->ipif_src_addr;
8294 
8295 		if (ip_debug > 3) {
8296 			/* ip2dbg */
8297 			pr_addr_dbg("ip_newroute: first hop %s\n",
8298 			    AF_INET, &gw);
8299 		}
8300 		ip2dbg(("\tire type %s (%d)\n",
8301 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8302 
8303 		/*
8304 		 * The TTL of multirouted packets is bounded by the
8305 		 * ip_multirt_ttl ndd variable.
8306 		 */
8307 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8308 			/* Force TTL of multirouted packets */
8309 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8310 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8311 				ip2dbg(("ip_newroute: forcing multirt TTL "
8312 				    "to %d (was %d), dst 0x%08x\n",
8313 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8314 				    ntohl(sire->ire_addr)));
8315 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8316 			}
8317 		}
8318 		/*
8319 		 * At this point in ip_newroute(), ire is either the
8320 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8321 		 * destination or an IRE_INTERFACE type that should be used
8322 		 * to resolve an on-subnet destination or an on-subnet
8323 		 * next-hop gateway.
8324 		 *
8325 		 * In the IRE_CACHE case, we have the following :
8326 		 *
8327 		 * 1) src_ipif - used for getting a source address.
8328 		 *
8329 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8330 		 *    means packets using this IRE_CACHE will go out on
8331 		 *    dst_ill.
8332 		 *
8333 		 * 3) The IRE sire will point to the prefix that is the
8334 		 *    longest  matching route for the destination. These
8335 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8336 		 *
8337 		 *    The newly created IRE_CACHE entry for the off-subnet
8338 		 *    destination is tied to both the prefix route and the
8339 		 *    interface route used to resolve the next-hop gateway
8340 		 *    via the ire_phandle and ire_ihandle fields,
8341 		 *    respectively.
8342 		 *
8343 		 * In the IRE_INTERFACE case, we have the following :
8344 		 *
8345 		 * 1) src_ipif - used for getting a source address.
8346 		 *
8347 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8348 		 *    means packets using the IRE_CACHE that we will build
8349 		 *    here will go out on dst_ill.
8350 		 *
8351 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8352 		 *    to be created will only be tied to the IRE_INTERFACE
8353 		 *    that was derived from the ire_ihandle field.
8354 		 *
8355 		 *    If sire is non-NULL, it means the destination is
8356 		 *    off-link and we will first create the IRE_CACHE for the
8357 		 *    gateway. Next time through ip_newroute, we will create
8358 		 *    the IRE_CACHE for the final destination as described
8359 		 *    above.
8360 		 *
8361 		 * In both cases, after the current resolution has been
8362 		 * completed (or possibly initialised, in the IRE_INTERFACE
8363 		 * case), the loop may be re-entered to attempt the resolution
8364 		 * of another RTF_MULTIRT route.
8365 		 *
8366 		 * When an IRE_CACHE entry for the off-subnet destination is
8367 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8368 		 * for further processing in emission loops.
8369 		 */
8370 		save_ire = ire;
8371 		switch (ire->ire_type) {
8372 		case IRE_CACHE: {
8373 			ire_t	*ipif_ire;
8374 
8375 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8376 			if (gw == 0)
8377 				gw = ire->ire_gateway_addr;
8378 			/*
8379 			 * We need 3 ire's to create a new cache ire for an
8380 			 * off-link destination from the cache ire of the
8381 			 * gateway.
8382 			 *
8383 			 *	1. The prefix ire 'sire' (Note that this does
8384 			 *	   not apply to the conn_nexthop_set case)
8385 			 *	2. The cache ire of the gateway 'ire'
8386 			 *	3. The interface ire 'ipif_ire'
8387 			 *
8388 			 * We have (1) and (2). We lookup (3) below.
8389 			 *
8390 			 * If there is no interface route to the gateway,
8391 			 * it is a race condition, where we found the cache
8392 			 * but the interface route has been deleted.
8393 			 */
8394 			if (ip_nexthop) {
8395 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8396 			} else {
8397 				ipif_ire =
8398 				    ire_ihandle_lookup_offlink(ire, sire);
8399 			}
8400 			if (ipif_ire == NULL) {
8401 				ip1dbg(("ip_newroute: "
8402 				    "ire_ihandle_lookup_offlink failed\n"));
8403 				goto icmp_err_ret;
8404 			}
8405 
8406 			/*
8407 			 * Check cached gateway IRE for any security
8408 			 * attributes; if found, associate the gateway
8409 			 * credentials group to the destination IRE.
8410 			 */
8411 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8412 				mutex_enter(&attrp->igsa_lock);
8413 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8414 					GCGRP_REFHOLD(gcgrp);
8415 				mutex_exit(&attrp->igsa_lock);
8416 			}
8417 
8418 			/*
8419 			 * XXX For the source of the resolver mp,
8420 			 * we are using the same DL_UNITDATA_REQ
8421 			 * (from save_ire->ire_nce->nce_res_mp)
8422 			 * though the save_ire is not pointing at the same ill.
8423 			 * This is incorrect. We need to send it up to the
8424 			 * resolver to get the right res_mp. For ethernets
8425 			 * this may be okay (ill_type == DL_ETHER).
8426 			 */
8427 
8428 			ire = ire_create(
8429 			    (uchar_t *)&dst,		/* dest address */
8430 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8431 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8432 			    (uchar_t *)&gw,		/* gateway address */
8433 			    &save_ire->ire_max_frag,
8434 			    save_ire->ire_nce,		/* src nce */
8435 			    dst_ill->ill_rq,		/* recv-from queue */
8436 			    dst_ill->ill_wq,		/* send-to queue */
8437 			    IRE_CACHE,			/* IRE type */
8438 			    src_ipif,
8439 			    (sire != NULL) ?
8440 			    sire->ire_mask : 0, 	/* Parent mask */
8441 			    (sire != NULL) ?
8442 			    sire->ire_phandle : 0,	/* Parent handle */
8443 			    ipif_ire->ire_ihandle,	/* Interface handle */
8444 			    (sire != NULL) ? (sire->ire_flags &
8445 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8446 			    (sire != NULL) ?
8447 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8448 			    NULL,
8449 			    gcgrp,
8450 			    ipst);
8451 
8452 			if (ire == NULL) {
8453 				if (gcgrp != NULL) {
8454 					GCGRP_REFRELE(gcgrp);
8455 					gcgrp = NULL;
8456 				}
8457 				ire_refrele(ipif_ire);
8458 				ire_refrele(save_ire);
8459 				break;
8460 			}
8461 
8462 			/* reference now held by IRE */
8463 			gcgrp = NULL;
8464 
8465 			ire->ire_marks |= ire_marks;
8466 
8467 			/*
8468 			 * Prevent sire and ipif_ire from getting deleted.
8469 			 * The newly created ire is tied to both of them via
8470 			 * the phandle and ihandle respectively.
8471 			 */
8472 			if (sire != NULL) {
8473 				IRB_REFHOLD(sire->ire_bucket);
8474 				/* Has it been removed already ? */
8475 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8476 					IRB_REFRELE(sire->ire_bucket);
8477 					ire_refrele(ipif_ire);
8478 					ire_refrele(save_ire);
8479 					break;
8480 				}
8481 			}
8482 
8483 			IRB_REFHOLD(ipif_ire->ire_bucket);
8484 			/* Has it been removed already ? */
8485 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8486 				IRB_REFRELE(ipif_ire->ire_bucket);
8487 				if (sire != NULL)
8488 					IRB_REFRELE(sire->ire_bucket);
8489 				ire_refrele(ipif_ire);
8490 				ire_refrele(save_ire);
8491 				break;
8492 			}
8493 
8494 			xmit_mp = first_mp;
8495 			/*
8496 			 * In the case of multirouting, a copy
8497 			 * of the packet is done before its sending.
8498 			 * The copy is used to attempt another
8499 			 * route resolution, in a next loop.
8500 			 */
8501 			if (ire->ire_flags & RTF_MULTIRT) {
8502 				copy_mp = copymsg(first_mp);
8503 				if (copy_mp != NULL) {
8504 					xmit_mp = copy_mp;
8505 					MULTIRT_DEBUG_TAG(first_mp);
8506 				}
8507 			}
8508 
8509 			ire_add_then_send(q, ire, xmit_mp);
8510 			ire_refrele(save_ire);
8511 
8512 			/* Assert that sire is not deleted yet. */
8513 			if (sire != NULL) {
8514 				ASSERT(sire->ire_ptpn != NULL);
8515 				IRB_REFRELE(sire->ire_bucket);
8516 			}
8517 
8518 			/* Assert that ipif_ire is not deleted yet. */
8519 			ASSERT(ipif_ire->ire_ptpn != NULL);
8520 			IRB_REFRELE(ipif_ire->ire_bucket);
8521 			ire_refrele(ipif_ire);
8522 
8523 			/*
8524 			 * If copy_mp is not NULL, multirouting was
8525 			 * requested. We loop to initiate a next
8526 			 * route resolution attempt, starting from sire.
8527 			 */
8528 			if (copy_mp != NULL) {
8529 				/*
8530 				 * Search for the next unresolved
8531 				 * multirt route.
8532 				 */
8533 				copy_mp = NULL;
8534 				ipif_ire = NULL;
8535 				ire = NULL;
8536 				multirt_resolve_next = B_TRUE;
8537 				continue;
8538 			}
8539 			if (sire != NULL)
8540 				ire_refrele(sire);
8541 			ipif_refrele(src_ipif);
8542 			ill_refrele(dst_ill);
8543 			return;
8544 		}
8545 		case IRE_IF_NORESOLVER: {
8546 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8547 			    dst_ill->ill_resolver_mp == NULL) {
8548 				ip1dbg(("ip_newroute: dst_ill %p "
8549 				    "for IRE_IF_NORESOLVER ire %p has "
8550 				    "no ill_resolver_mp\n",
8551 				    (void *)dst_ill, (void *)ire));
8552 				break;
8553 			}
8554 
8555 			/*
8556 			 * TSol note: We are creating the ire cache for the
8557 			 * destination 'dst'. If 'dst' is offlink, going
8558 			 * through the first hop 'gw', the security attributes
8559 			 * of 'dst' must be set to point to the gateway
8560 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8561 			 * is possible that 'dst' is a potential gateway that is
8562 			 * referenced by some route that has some security
8563 			 * attributes. Thus in the former case, we need to do a
8564 			 * gcgrp_lookup of 'gw' while in the latter case we
8565 			 * need to do gcgrp_lookup of 'dst' itself.
8566 			 */
8567 			ga.ga_af = AF_INET;
8568 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8569 			    &ga.ga_addr);
8570 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8571 
8572 			ire = ire_create(
8573 			    (uchar_t *)&dst,		/* dest address */
8574 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8575 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8576 			    (uchar_t *)&gw,		/* gateway address */
8577 			    &save_ire->ire_max_frag,
8578 			    NULL,			/* no src nce */
8579 			    dst_ill->ill_rq,		/* recv-from queue */
8580 			    dst_ill->ill_wq,		/* send-to queue */
8581 			    IRE_CACHE,
8582 			    src_ipif,
8583 			    save_ire->ire_mask,		/* Parent mask */
8584 			    (sire != NULL) ?		/* Parent handle */
8585 			    sire->ire_phandle : 0,
8586 			    save_ire->ire_ihandle,	/* Interface handle */
8587 			    (sire != NULL) ? sire->ire_flags &
8588 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8589 			    &(save_ire->ire_uinfo),
8590 			    NULL,
8591 			    gcgrp,
8592 			    ipst);
8593 
8594 			if (ire == NULL) {
8595 				if (gcgrp != NULL) {
8596 					GCGRP_REFRELE(gcgrp);
8597 					gcgrp = NULL;
8598 				}
8599 				ire_refrele(save_ire);
8600 				break;
8601 			}
8602 
8603 			/* reference now held by IRE */
8604 			gcgrp = NULL;
8605 
8606 			ire->ire_marks |= ire_marks;
8607 
8608 			/* Prevent save_ire from getting deleted */
8609 			IRB_REFHOLD(save_ire->ire_bucket);
8610 			/* Has it been removed already ? */
8611 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8612 				IRB_REFRELE(save_ire->ire_bucket);
8613 				ire_refrele(save_ire);
8614 				break;
8615 			}
8616 
8617 			/*
8618 			 * In the case of multirouting, a copy
8619 			 * of the packet is made before it is sent.
8620 			 * The copy is used in the next
8621 			 * loop to attempt another resolution.
8622 			 */
8623 			xmit_mp = first_mp;
8624 			if ((sire != NULL) &&
8625 			    (sire->ire_flags & RTF_MULTIRT)) {
8626 				copy_mp = copymsg(first_mp);
8627 				if (copy_mp != NULL) {
8628 					xmit_mp = copy_mp;
8629 					MULTIRT_DEBUG_TAG(first_mp);
8630 				}
8631 			}
8632 			ire_add_then_send(q, ire, xmit_mp);
8633 
8634 			/* Assert that it is not deleted yet. */
8635 			ASSERT(save_ire->ire_ptpn != NULL);
8636 			IRB_REFRELE(save_ire->ire_bucket);
8637 			ire_refrele(save_ire);
8638 
8639 			if (copy_mp != NULL) {
8640 				/*
8641 				 * If we found a (no)resolver, we ignore any
8642 				 * trailing top priority IRE_CACHE in further
8643 				 * loops. This ensures that we do not omit any
8644 				 * (no)resolver.
8645 				 * This IRE_CACHE, if any, will be processed
8646 				 * by another thread entering ip_newroute().
8647 				 * IRE_CACHE entries, if any, will be processed
8648 				 * by another thread entering ip_newroute(),
8649 				 * (upon resolver response, for instance).
8650 				 * This aims to force parallel multirt
8651 				 * resolutions as soon as a packet must be sent.
8652 				 * In the best case, after the tx of only one
8653 				 * packet, all reachable routes are resolved.
8654 				 * Otherwise, the resolution of all RTF_MULTIRT
8655 				 * routes would require several emissions.
8656 				 */
8657 				multirt_flags &= ~MULTIRT_CACHEGW;
8658 
8659 				/*
8660 				 * Search for the next unresolved multirt
8661 				 * route.
8662 				 */
8663 				copy_mp = NULL;
8664 				save_ire = NULL;
8665 				ire = NULL;
8666 				multirt_resolve_next = B_TRUE;
8667 				continue;
8668 			}
8669 
8670 			/*
8671 			 * Don't need sire anymore
8672 			 */
8673 			if (sire != NULL)
8674 				ire_refrele(sire);
8675 
8676 			ipif_refrele(src_ipif);
8677 			ill_refrele(dst_ill);
8678 			return;
8679 		}
8680 		case IRE_IF_RESOLVER:
8681 			/*
8682 			 * We can't build an IRE_CACHE yet, but at least we
8683 			 * found a resolver that can help.
8684 			 */
8685 			res_mp = dst_ill->ill_resolver_mp;
8686 			if (!OK_RESOLVER_MP(res_mp))
8687 				break;
8688 
8689 			/*
8690 			 * To be at this point in the code with a non-zero gw
8691 			 * means that dst is reachable through a gateway that
8692 			 * we have never resolved.  By changing dst to the gw
8693 			 * addr we resolve the gateway first.
8694 			 * When ire_add_then_send() tries to put the IP dg
8695 			 * to dst, it will reenter ip_newroute() at which
8696 			 * time we will find the IRE_CACHE for the gw and
8697 			 * create another IRE_CACHE in case IRE_CACHE above.
8698 			 */
8699 			if (gw != INADDR_ANY) {
8700 				/*
8701 				 * The source ipif that was determined above was
8702 				 * relative to the destination address, not the
8703 				 * gateway's. If src_ipif was not taken out of
8704 				 * the IRE_IF_RESOLVER entry, we'll need to call
8705 				 * ipif_select_source() again.
8706 				 */
8707 				if (src_ipif != ire->ire_ipif) {
8708 					ipif_refrele(src_ipif);
8709 					src_ipif = ipif_select_source(dst_ill,
8710 					    gw, zoneid);
8711 					if (src_ipif == NULL) {
8712 						if (ip_debug > 2) {
8713 							pr_addr_dbg(
8714 							    "ip_newroute: no "
8715 							    "src for gw %s ",
8716 							    AF_INET, &gw);
8717 							printf("on "
8718 							    "interface %s\n",
8719 							    dst_ill->ill_name);
8720 						}
8721 						goto icmp_err_ret;
8722 					}
8723 				}
8724 				save_dst = dst;
8725 				dst = gw;
8726 				gw = INADDR_ANY;
8727 			}
8728 
8729 			/*
8730 			 * We obtain a partial IRE_CACHE which we will pass
8731 			 * along with the resolver query.  When the response
8732 			 * comes back it will be there ready for us to add.
8733 			 * The ire_max_frag is atomically set under the
8734 			 * irebucket lock in ire_add_v[46].
8735 			 */
8736 
8737 			ire = ire_create_mp(
8738 			    (uchar_t *)&dst,		/* dest address */
8739 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8740 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8741 			    (uchar_t *)&gw,		/* gateway address */
8742 			    NULL,			/* ire_max_frag */
8743 			    NULL,			/* no src nce */
8744 			    dst_ill->ill_rq,		/* recv-from queue */
8745 			    dst_ill->ill_wq,		/* send-to queue */
8746 			    IRE_CACHE,
8747 			    src_ipif,			/* Interface ipif */
8748 			    save_ire->ire_mask,		/* Parent mask */
8749 			    0,
8750 			    save_ire->ire_ihandle,	/* Interface handle */
8751 			    0,				/* flags if any */
8752 			    &(save_ire->ire_uinfo),
8753 			    NULL,
8754 			    NULL,
8755 			    ipst);
8756 
8757 			if (ire == NULL) {
8758 				ire_refrele(save_ire);
8759 				break;
8760 			}
8761 
8762 			if ((sire != NULL) &&
8763 			    (sire->ire_flags & RTF_MULTIRT)) {
8764 				copy_mp = copymsg(first_mp);
8765 				if (copy_mp != NULL)
8766 					MULTIRT_DEBUG_TAG(copy_mp);
8767 			}
8768 
8769 			ire->ire_marks |= ire_marks;
8770 
8771 			/*
8772 			 * Construct message chain for the resolver
8773 			 * of the form:
8774 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8775 			 * Packet could contain a IPSEC_OUT mp.
8776 			 *
8777 			 * NOTE : ire will be added later when the response
8778 			 * comes back from ARP. If the response does not
8779 			 * come back, ARP frees the packet. For this reason,
8780 			 * we can't REFHOLD the bucket of save_ire to prevent
8781 			 * deletions. We may not be able to REFRELE the bucket
8782 			 * if the response never comes back. Thus, before
8783 			 * adding the ire, ire_add_v4 will make sure that the
8784 			 * interface route does not get deleted. This is the
8785 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8786 			 * where we can always prevent deletions because of
8787 			 * the synchronous nature of adding IRES i.e
8788 			 * ire_add_then_send is called after creating the IRE.
8789 			 */
8790 			ASSERT(ire->ire_mp != NULL);
8791 			ire->ire_mp->b_cont = first_mp;
8792 			/* Have saved_mp handy, for cleanup if canput fails */
8793 			saved_mp = mp;
8794 			mp = copyb(res_mp);
8795 			if (mp == NULL) {
8796 				/* Prepare for cleanup */
8797 				mp = saved_mp; /* pkt */
8798 				ire_delete(ire); /* ire_mp */
8799 				ire = NULL;
8800 				ire_refrele(save_ire);
8801 				if (copy_mp != NULL) {
8802 					MULTIRT_DEBUG_UNTAG(copy_mp);
8803 					freemsg(copy_mp);
8804 					copy_mp = NULL;
8805 				}
8806 				break;
8807 			}
8808 			linkb(mp, ire->ire_mp);
8809 
8810 			/*
8811 			 * Fill in the source and dest addrs for the resolver.
8812 			 * NOTE: this depends on memory layouts imposed by
8813 			 * ill_init().
8814 			 */
8815 			areq = (areq_t *)mp->b_rptr;
8816 			addrp = (ipaddr_t *)((char *)areq +
8817 			    areq->areq_sender_addr_offset);
8818 			*addrp = save_ire->ire_src_addr;
8819 
8820 			ire_refrele(save_ire);
8821 			addrp = (ipaddr_t *)((char *)areq +
8822 			    areq->areq_target_addr_offset);
8823 			*addrp = dst;
8824 			/* Up to the resolver. */
8825 			if (canputnext(dst_ill->ill_rq) &&
8826 			    !(dst_ill->ill_arp_closing)) {
8827 				putnext(dst_ill->ill_rq, mp);
8828 				ire = NULL;
8829 				if (copy_mp != NULL) {
8830 					/*
8831 					 * If we found a resolver, we ignore
8832 					 * any trailing top priority IRE_CACHE
8833 					 * in the further loops. This ensures
8834 					 * that we do not omit any resolver.
8835 					 * IRE_CACHE entries, if any, will be
8836 					 * processed next time we enter
8837 					 * ip_newroute().
8838 					 */
8839 					multirt_flags &= ~MULTIRT_CACHEGW;
8840 					/*
8841 					 * Search for the next unresolved
8842 					 * multirt route.
8843 					 */
8844 					first_mp = copy_mp;
8845 					copy_mp = NULL;
8846 					/* Prepare the next resolution loop. */
8847 					mp = first_mp;
8848 					EXTRACT_PKT_MP(mp, first_mp,
8849 					    mctl_present);
8850 					if (mctl_present)
8851 						io = (ipsec_out_t *)
8852 						    first_mp->b_rptr;
8853 					ipha = (ipha_t *)mp->b_rptr;
8854 
8855 					ASSERT(sire != NULL);
8856 
8857 					dst = save_dst;
8858 					multirt_resolve_next = B_TRUE;
8859 					continue;
8860 				}
8861 
8862 				if (sire != NULL)
8863 					ire_refrele(sire);
8864 
8865 				/*
8866 				 * The response will come back in ip_wput
8867 				 * with db_type IRE_DB_TYPE.
8868 				 */
8869 				ipif_refrele(src_ipif);
8870 				ill_refrele(dst_ill);
8871 				return;
8872 			} else {
8873 				/* Prepare for cleanup */
8874 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8875 				    mp);
8876 				mp->b_cont = NULL;
8877 				freeb(mp); /* areq */
8878 				/*
8879 				 * this is an ire that is not added to the
8880 				 * cache. ire_freemblk will handle the release
8881 				 * of any resources associated with the ire.
8882 				 */
8883 				ire_delete(ire); /* ire_mp */
8884 				mp = saved_mp; /* pkt */
8885 				ire = NULL;
8886 				if (copy_mp != NULL) {
8887 					MULTIRT_DEBUG_UNTAG(copy_mp);
8888 					freemsg(copy_mp);
8889 					copy_mp = NULL;
8890 				}
8891 				break;
8892 			}
8893 		default:
8894 			break;
8895 		}
8896 	} while (multirt_resolve_next);
8897 
8898 	ip1dbg(("ip_newroute: dropped\n"));
8899 	/* Did this packet originate externally? */
8900 	if (mp->b_prev) {
8901 		mp->b_next = NULL;
8902 		mp->b_prev = NULL;
8903 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8904 	} else {
8905 		if (dst_ill != NULL) {
8906 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8907 		} else {
8908 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8909 		}
8910 	}
8911 	ASSERT(copy_mp == NULL);
8912 	MULTIRT_DEBUG_UNTAG(first_mp);
8913 	freemsg(first_mp);
8914 	if (ire != NULL)
8915 		ire_refrele(ire);
8916 	if (sire != NULL)
8917 		ire_refrele(sire);
8918 	if (src_ipif != NULL)
8919 		ipif_refrele(src_ipif);
8920 	if (dst_ill != NULL)
8921 		ill_refrele(dst_ill);
8922 	return;
8923 
8924 icmp_err_ret:
8925 	ip1dbg(("ip_newroute: no route\n"));
8926 	if (src_ipif != NULL)
8927 		ipif_refrele(src_ipif);
8928 	if (dst_ill != NULL)
8929 		ill_refrele(dst_ill);
8930 	if (sire != NULL)
8931 		ire_refrele(sire);
8932 	/* Did this packet originate externally? */
8933 	if (mp->b_prev) {
8934 		mp->b_next = NULL;
8935 		mp->b_prev = NULL;
8936 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8937 		q = WR(q);
8938 	} else {
8939 		/*
8940 		 * There is no outgoing ill, so just increment the
8941 		 * system MIB.
8942 		 */
8943 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8944 		/*
8945 		 * Since ip_wput() isn't close to finished, we fill
8946 		 * in enough of the header for credible error reporting.
8947 		 */
8948 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8949 			/* Failed */
8950 			MULTIRT_DEBUG_UNTAG(first_mp);
8951 			freemsg(first_mp);
8952 			if (ire != NULL)
8953 				ire_refrele(ire);
8954 			return;
8955 		}
8956 	}
8957 
8958 	/*
8959 	 * At this point we will have ire only if RTF_BLACKHOLE
8960 	 * or RTF_REJECT flags are set on the IRE. It will not
8961 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8962 	 */
8963 	if (ire != NULL) {
8964 		if (ire->ire_flags & RTF_BLACKHOLE) {
8965 			ire_refrele(ire);
8966 			MULTIRT_DEBUG_UNTAG(first_mp);
8967 			freemsg(first_mp);
8968 			return;
8969 		}
8970 		ire_refrele(ire);
8971 	}
8972 	if (ip_source_routed(ipha, ipst)) {
8973 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8974 		    zoneid, ipst);
8975 		return;
8976 	}
8977 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8978 }
8979 
8980 ip_opt_info_t zero_info;
8981 
8982 /*
8983  * IPv4 -
8984  * ip_newroute_ipif is called by ip_wput_multicast and
8985  * ip_rput_forward_multicast whenever we need to send
8986  * out a packet to a destination address for which we do not have specific
8987  * routing information. It is used when the packet will be sent out
8988  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8989  * socket option is set or icmp error message wants to go out on a particular
8990  * interface for a unicast packet.
8991  *
8992  * In most cases, the destination address is resolved thanks to the ipif
8993  * intrinsic resolver. However, there are some cases where the call to
8994  * ip_newroute_ipif must take into account the potential presence of
8995  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8996  * that uses the interface. This is specified through flags,
8997  * which can be a combination of:
8998  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8999  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9000  *   and flags. Additionally, the packet source address has to be set to
9001  *   the specified address. The caller is thus expected to set this flag
9002  *   if the packet has no specific source address yet.
9003  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9004  *   flag, the resulting ire will inherit the flag. All unresolved routes
9005  *   to the destination must be explored in the same call to
9006  *   ip_newroute_ipif().
9007  */
9008 static void
9009 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9010     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9011 {
9012 	areq_t	*areq;
9013 	ire_t	*ire = NULL;
9014 	mblk_t	*res_mp;
9015 	ipaddr_t *addrp;
9016 	mblk_t *first_mp;
9017 	ire_t	*save_ire = NULL;
9018 	ipif_t	*src_ipif = NULL;
9019 	ushort_t ire_marks = 0;
9020 	ill_t	*dst_ill = NULL;
9021 	ipha_t *ipha;
9022 	mblk_t	*saved_mp;
9023 	ire_t   *fire = NULL;
9024 	mblk_t  *copy_mp = NULL;
9025 	boolean_t multirt_resolve_next;
9026 	boolean_t unspec_src;
9027 	ipaddr_t ipha_dst;
9028 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9029 
9030 	/*
9031 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9032 	 * here for uniformity
9033 	 */
9034 	ipif_refhold(ipif);
9035 
9036 	/*
9037 	 * This loop is run only once in most cases.
9038 	 * We loop to resolve further routes only when the destination
9039 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9040 	 */
9041 	do {
9042 		if (dst_ill != NULL) {
9043 			ill_refrele(dst_ill);
9044 			dst_ill = NULL;
9045 		}
9046 		if (src_ipif != NULL) {
9047 			ipif_refrele(src_ipif);
9048 			src_ipif = NULL;
9049 		}
9050 		multirt_resolve_next = B_FALSE;
9051 
9052 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9053 		    ipif->ipif_ill->ill_name));
9054 
9055 		first_mp = mp;
9056 		if (DB_TYPE(mp) == M_CTL)
9057 			mp = mp->b_cont;
9058 		ipha = (ipha_t *)mp->b_rptr;
9059 
9060 		/*
9061 		 * Save the packet destination address, we may need it after
9062 		 * the packet has been consumed.
9063 		 */
9064 		ipha_dst = ipha->ipha_dst;
9065 
9066 		/*
9067 		 * If the interface is a pt-pt interface we look for an
9068 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9069 		 * local_address and the pt-pt destination address. Otherwise
9070 		 * we just match the local address.
9071 		 * NOTE: dst could be different than ipha->ipha_dst in case
9072 		 * of sending igmp multicast packets over a point-to-point
9073 		 * connection.
9074 		 * Thus we must be careful enough to check ipha_dst to be a
9075 		 * multicast address, otherwise it will take xmit_if path for
9076 		 * multicast packets resulting into kernel stack overflow by
9077 		 * repeated calls to ip_newroute_ipif from ire_send().
9078 		 */
9079 		if (CLASSD(ipha_dst) &&
9080 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9081 			goto err_ret;
9082 		}
9083 
9084 		/*
9085 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9086 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9087 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9088 		 * propagate its flags to the new ire.
9089 		 */
9090 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9091 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9092 			ip2dbg(("ip_newroute_ipif: "
9093 			    "ipif_lookup_multi_ire("
9094 			    "ipif %p, dst %08x) = fire %p\n",
9095 			    (void *)ipif, ntohl(dst), (void *)fire));
9096 		}
9097 
9098 		/*
9099 		 * Note: While we pick a dst_ill we are really only
9100 		 * interested in the ill for load spreading. The source
9101 		 * ipif is determined by source address selection below.
9102 		 */
9103 		if (IS_IPMP(ipif->ipif_ill)) {
9104 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9105 
9106 			if (CLASSD(ipha_dst))
9107 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9108 			else
9109 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9110 		} else {
9111 			dst_ill = ipif->ipif_ill;
9112 			ill_refhold(dst_ill);
9113 		}
9114 
9115 		if (dst_ill == NULL) {
9116 			if (ip_debug > 2) {
9117 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9118 				    "for dst %s\n", AF_INET, &dst);
9119 			}
9120 			goto err_ret;
9121 		}
9122 
9123 		/*
9124 		 * Pick a source address preferring non-deprecated ones.
9125 		 * Unlike ip_newroute, we don't do any source address
9126 		 * selection here since for multicast it really does not help
9127 		 * in inbound load spreading as in the unicast case.
9128 		 */
9129 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9130 		    (fire->ire_flags & RTF_SETSRC)) {
9131 			/*
9132 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9133 			 * on that interface. This ire has RTF_SETSRC flag, so
9134 			 * the source address of the packet must be changed.
9135 			 * Check that the ipif matching the requested source
9136 			 * address still exists.
9137 			 */
9138 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9139 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9140 		}
9141 
9142 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9143 
9144 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9145 		    (IS_IPMP(ipif->ipif_ill) ||
9146 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9147 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9148 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9149 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9150 		    (src_ipif == NULL) &&
9151 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9152 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9153 			if (src_ipif == NULL) {
9154 				if (ip_debug > 2) {
9155 					/* ip1dbg */
9156 					pr_addr_dbg("ip_newroute_ipif: "
9157 					    "no src for dst %s",
9158 					    AF_INET, &dst);
9159 				}
9160 				ip1dbg((" on interface %s\n",
9161 				    dst_ill->ill_name));
9162 				goto err_ret;
9163 			}
9164 			ipif_refrele(ipif);
9165 			ipif = src_ipif;
9166 			ipif_refhold(ipif);
9167 		}
9168 		if (src_ipif == NULL) {
9169 			src_ipif = ipif;
9170 			ipif_refhold(src_ipif);
9171 		}
9172 
9173 		/*
9174 		 * Assign a source address while we have the conn.
9175 		 * We can't have ip_wput_ire pick a source address when the
9176 		 * packet returns from arp since conn_unspec_src might be set
9177 		 * and we lose the conn when going through arp.
9178 		 */
9179 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9180 			ipha->ipha_src = src_ipif->ipif_src_addr;
9181 
9182 		/*
9183 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9184 		 * that the outgoing interface does not have an interface ire.
9185 		 */
9186 		if (CLASSD(ipha_dst) && (connp == NULL ||
9187 		    connp->conn_outgoing_ill == NULL) &&
9188 		    infop->ip_opt_ill_index == 0) {
9189 			/* ipif_to_ire returns an held ire */
9190 			ire = ipif_to_ire(ipif);
9191 			if (ire == NULL)
9192 				goto err_ret;
9193 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9194 				goto err_ret;
9195 			save_ire = ire;
9196 
9197 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9198 			    "flags %04x\n",
9199 			    (void *)ire, (void *)ipif, flags));
9200 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9201 			    (fire->ire_flags & RTF_MULTIRT)) {
9202 				/*
9203 				 * As requested by flags, an IRE_OFFSUBNET was
9204 				 * looked up on that interface. This ire has
9205 				 * RTF_MULTIRT flag, so the resolution loop will
9206 				 * be re-entered to resolve additional routes on
9207 				 * other interfaces. For that purpose, a copy of
9208 				 * the packet is performed at this point.
9209 				 */
9210 				fire->ire_last_used_time = lbolt;
9211 				copy_mp = copymsg(first_mp);
9212 				if (copy_mp) {
9213 					MULTIRT_DEBUG_TAG(copy_mp);
9214 				}
9215 			}
9216 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9217 			    (fire->ire_flags & RTF_SETSRC)) {
9218 				/*
9219 				 * As requested by flags, an IRE_OFFSUBET was
9220 				 * looked up on that interface. This ire has
9221 				 * RTF_SETSRC flag, so the source address of the
9222 				 * packet must be changed.
9223 				 */
9224 				ipha->ipha_src = fire->ire_src_addr;
9225 			}
9226 		} else {
9227 			/*
9228 			 * The only ways we can come here are:
9229 			 * 1) IP_BOUND_IF socket option is set
9230 			 * 2) SO_DONTROUTE socket option is set
9231 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9232 			 * In all cases, the new ire will not be added
9233 			 * into cache table.
9234 			 */
9235 			ASSERT(connp == NULL || connp->conn_dontroute ||
9236 			    connp->conn_outgoing_ill != NULL ||
9237 			    infop->ip_opt_ill_index != 0);
9238 			ire_marks |= IRE_MARK_NOADD;
9239 		}
9240 
9241 		switch (ipif->ipif_net_type) {
9242 		case IRE_IF_NORESOLVER: {
9243 			/* We have what we need to build an IRE_CACHE. */
9244 
9245 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9246 			    (dst_ill->ill_resolver_mp == NULL)) {
9247 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9248 				    "for IRE_IF_NORESOLVER ire %p has "
9249 				    "no ill_resolver_mp\n",
9250 				    (void *)dst_ill, (void *)ire));
9251 				break;
9252 			}
9253 
9254 			/*
9255 			 * The new ire inherits the IRE_OFFSUBNET flags
9256 			 * and source address, if this was requested.
9257 			 */
9258 			ire = ire_create(
9259 			    (uchar_t *)&dst,		/* dest address */
9260 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9261 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9262 			    NULL,			/* gateway address */
9263 			    &ipif->ipif_mtu,
9264 			    NULL,			/* no src nce */
9265 			    dst_ill->ill_rq,		/* recv-from queue */
9266 			    dst_ill->ill_wq,		/* send-to queue */
9267 			    IRE_CACHE,
9268 			    src_ipif,
9269 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9270 			    (fire != NULL) ?		/* Parent handle */
9271 			    fire->ire_phandle : 0,
9272 			    (save_ire != NULL) ?	/* Interface handle */
9273 			    save_ire->ire_ihandle : 0,
9274 			    (fire != NULL) ?
9275 			    (fire->ire_flags &
9276 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9277 			    (save_ire == NULL ? &ire_uinfo_null :
9278 			    &save_ire->ire_uinfo),
9279 			    NULL,
9280 			    NULL,
9281 			    ipst);
9282 
9283 			if (ire == NULL) {
9284 				if (save_ire != NULL)
9285 					ire_refrele(save_ire);
9286 				break;
9287 			}
9288 
9289 			ire->ire_marks |= ire_marks;
9290 
9291 			/*
9292 			 * If IRE_MARK_NOADD is set then we need to convert
9293 			 * the max_fragp to a useable value now. This is
9294 			 * normally done in ire_add_v[46]. We also need to
9295 			 * associate the ire with an nce (normally would be
9296 			 * done in ip_wput_nondata()).
9297 			 *
9298 			 * Note that IRE_MARK_NOADD packets created here
9299 			 * do not have a non-null ire_mp pointer. The null
9300 			 * value of ire_bucket indicates that they were
9301 			 * never added.
9302 			 */
9303 			if (ire->ire_marks & IRE_MARK_NOADD) {
9304 				uint_t  max_frag;
9305 
9306 				max_frag = *ire->ire_max_fragp;
9307 				ire->ire_max_fragp = NULL;
9308 				ire->ire_max_frag = max_frag;
9309 
9310 				if ((ire->ire_nce = ndp_lookup_v4(
9311 				    ire_to_ill(ire),
9312 				    (ire->ire_gateway_addr != INADDR_ANY ?
9313 				    &ire->ire_gateway_addr : &ire->ire_addr),
9314 				    B_FALSE)) == NULL) {
9315 					if (save_ire != NULL)
9316 						ire_refrele(save_ire);
9317 					break;
9318 				}
9319 				ASSERT(ire->ire_nce->nce_state ==
9320 				    ND_REACHABLE);
9321 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9322 			}
9323 
9324 			/* Prevent save_ire from getting deleted */
9325 			if (save_ire != NULL) {
9326 				IRB_REFHOLD(save_ire->ire_bucket);
9327 				/* Has it been removed already ? */
9328 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9329 					IRB_REFRELE(save_ire->ire_bucket);
9330 					ire_refrele(save_ire);
9331 					break;
9332 				}
9333 			}
9334 
9335 			ire_add_then_send(q, ire, first_mp);
9336 
9337 			/* Assert that save_ire is not deleted yet. */
9338 			if (save_ire != NULL) {
9339 				ASSERT(save_ire->ire_ptpn != NULL);
9340 				IRB_REFRELE(save_ire->ire_bucket);
9341 				ire_refrele(save_ire);
9342 				save_ire = NULL;
9343 			}
9344 			if (fire != NULL) {
9345 				ire_refrele(fire);
9346 				fire = NULL;
9347 			}
9348 
9349 			/*
9350 			 * the resolution loop is re-entered if this
9351 			 * was requested through flags and if we
9352 			 * actually are in a multirouting case.
9353 			 */
9354 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9355 				boolean_t need_resolve =
9356 				    ire_multirt_need_resolve(ipha_dst,
9357 				    msg_getlabel(copy_mp), ipst);
9358 				if (!need_resolve) {
9359 					MULTIRT_DEBUG_UNTAG(copy_mp);
9360 					freemsg(copy_mp);
9361 					copy_mp = NULL;
9362 				} else {
9363 					/*
9364 					 * ipif_lookup_group() calls
9365 					 * ire_lookup_multi() that uses
9366 					 * ire_ftable_lookup() to find
9367 					 * an IRE_INTERFACE for the group.
9368 					 * In the multirt case,
9369 					 * ire_lookup_multi() then invokes
9370 					 * ire_multirt_lookup() to find
9371 					 * the next resolvable ire.
9372 					 * As a result, we obtain an new
9373 					 * interface, derived from the
9374 					 * next ire.
9375 					 */
9376 					ipif_refrele(ipif);
9377 					ipif = ipif_lookup_group(ipha_dst,
9378 					    zoneid, ipst);
9379 					ip2dbg(("ip_newroute_ipif: "
9380 					    "multirt dst %08x, ipif %p\n",
9381 					    htonl(dst), (void *)ipif));
9382 					if (ipif != NULL) {
9383 						mp = copy_mp;
9384 						copy_mp = NULL;
9385 						multirt_resolve_next = B_TRUE;
9386 						continue;
9387 					} else {
9388 						freemsg(copy_mp);
9389 					}
9390 				}
9391 			}
9392 			if (ipif != NULL)
9393 				ipif_refrele(ipif);
9394 			ill_refrele(dst_ill);
9395 			ipif_refrele(src_ipif);
9396 			return;
9397 		}
9398 		case IRE_IF_RESOLVER:
9399 			/*
9400 			 * We can't build an IRE_CACHE yet, but at least
9401 			 * we found a resolver that can help.
9402 			 */
9403 			res_mp = dst_ill->ill_resolver_mp;
9404 			if (!OK_RESOLVER_MP(res_mp))
9405 				break;
9406 
9407 			/*
9408 			 * We obtain a partial IRE_CACHE which we will pass
9409 			 * along with the resolver query.  When the response
9410 			 * comes back it will be there ready for us to add.
9411 			 * The new ire inherits the IRE_OFFSUBNET flags
9412 			 * and source address, if this was requested.
9413 			 * The ire_max_frag is atomically set under the
9414 			 * irebucket lock in ire_add_v[46]. Only in the
9415 			 * case of IRE_MARK_NOADD, we set it here itself.
9416 			 */
9417 			ire = ire_create_mp(
9418 			    (uchar_t *)&dst,		/* dest address */
9419 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9420 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9421 			    NULL,			/* gateway address */
9422 			    (ire_marks & IRE_MARK_NOADD) ?
9423 			    ipif->ipif_mtu : 0,		/* max_frag */
9424 			    NULL,			/* no src nce */
9425 			    dst_ill->ill_rq,		/* recv-from queue */
9426 			    dst_ill->ill_wq,		/* send-to queue */
9427 			    IRE_CACHE,
9428 			    src_ipif,
9429 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9430 			    (fire != NULL) ?		/* Parent handle */
9431 			    fire->ire_phandle : 0,
9432 			    (save_ire != NULL) ?	/* Interface handle */
9433 			    save_ire->ire_ihandle : 0,
9434 			    (fire != NULL) ?		/* flags if any */
9435 			    (fire->ire_flags &
9436 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9437 			    (save_ire == NULL ? &ire_uinfo_null :
9438 			    &save_ire->ire_uinfo),
9439 			    NULL,
9440 			    NULL,
9441 			    ipst);
9442 
9443 			if (save_ire != NULL) {
9444 				ire_refrele(save_ire);
9445 				save_ire = NULL;
9446 			}
9447 			if (ire == NULL)
9448 				break;
9449 
9450 			ire->ire_marks |= ire_marks;
9451 			/*
9452 			 * Construct message chain for the resolver of the
9453 			 * form:
9454 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9455 			 *
9456 			 * NOTE : ire will be added later when the response
9457 			 * comes back from ARP. If the response does not
9458 			 * come back, ARP frees the packet. For this reason,
9459 			 * we can't REFHOLD the bucket of save_ire to prevent
9460 			 * deletions. We may not be able to REFRELE the
9461 			 * bucket if the response never comes back.
9462 			 * Thus, before adding the ire, ire_add_v4 will make
9463 			 * sure that the interface route does not get deleted.
9464 			 * This is the only case unlike ip_newroute_v6,
9465 			 * ip_newroute_ipif_v6 where we can always prevent
9466 			 * deletions because ire_add_then_send is called after
9467 			 * creating the IRE.
9468 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9469 			 * does not add this IRE into the IRE CACHE.
9470 			 */
9471 			ASSERT(ire->ire_mp != NULL);
9472 			ire->ire_mp->b_cont = first_mp;
9473 			/* Have saved_mp handy, for cleanup if canput fails */
9474 			saved_mp = mp;
9475 			mp = copyb(res_mp);
9476 			if (mp == NULL) {
9477 				/* Prepare for cleanup */
9478 				mp = saved_mp; /* pkt */
9479 				ire_delete(ire); /* ire_mp */
9480 				ire = NULL;
9481 				if (copy_mp != NULL) {
9482 					MULTIRT_DEBUG_UNTAG(copy_mp);
9483 					freemsg(copy_mp);
9484 					copy_mp = NULL;
9485 				}
9486 				break;
9487 			}
9488 			linkb(mp, ire->ire_mp);
9489 
9490 			/*
9491 			 * Fill in the source and dest addrs for the resolver.
9492 			 * NOTE: this depends on memory layouts imposed by
9493 			 * ill_init().  There are corner cases above where we
9494 			 * might've created the IRE with an INADDR_ANY source
9495 			 * address (e.g., if the zeroth ipif on an underlying
9496 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9497 			 * on the ill has a usable test address).  If so, tell
9498 			 * ARP to use ipha_src as its sender address.
9499 			 */
9500 			areq = (areq_t *)mp->b_rptr;
9501 			addrp = (ipaddr_t *)((char *)areq +
9502 			    areq->areq_sender_addr_offset);
9503 			if (ire->ire_src_addr != INADDR_ANY)
9504 				*addrp = ire->ire_src_addr;
9505 			else
9506 				*addrp = ipha->ipha_src;
9507 			addrp = (ipaddr_t *)((char *)areq +
9508 			    areq->areq_target_addr_offset);
9509 			*addrp = dst;
9510 			/* Up to the resolver. */
9511 			if (canputnext(dst_ill->ill_rq) &&
9512 			    !(dst_ill->ill_arp_closing)) {
9513 				putnext(dst_ill->ill_rq, mp);
9514 				/*
9515 				 * The response will come back in ip_wput
9516 				 * with db_type IRE_DB_TYPE.
9517 				 */
9518 			} else {
9519 				mp->b_cont = NULL;
9520 				freeb(mp); /* areq */
9521 				ire_delete(ire); /* ire_mp */
9522 				saved_mp->b_next = NULL;
9523 				saved_mp->b_prev = NULL;
9524 				freemsg(first_mp); /* pkt */
9525 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9526 			}
9527 
9528 			if (fire != NULL) {
9529 				ire_refrele(fire);
9530 				fire = NULL;
9531 			}
9532 
9533 			/*
9534 			 * The resolution loop is re-entered if this was
9535 			 * requested through flags and we actually are
9536 			 * in a multirouting case.
9537 			 */
9538 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9539 				boolean_t need_resolve =
9540 				    ire_multirt_need_resolve(ipha_dst,
9541 				    msg_getlabel(copy_mp), ipst);
9542 				if (!need_resolve) {
9543 					MULTIRT_DEBUG_UNTAG(copy_mp);
9544 					freemsg(copy_mp);
9545 					copy_mp = NULL;
9546 				} else {
9547 					/*
9548 					 * ipif_lookup_group() calls
9549 					 * ire_lookup_multi() that uses
9550 					 * ire_ftable_lookup() to find
9551 					 * an IRE_INTERFACE for the group.
9552 					 * In the multirt case,
9553 					 * ire_lookup_multi() then invokes
9554 					 * ire_multirt_lookup() to find
9555 					 * the next resolvable ire.
9556 					 * As a result, we obtain an new
9557 					 * interface, derived from the
9558 					 * next ire.
9559 					 */
9560 					ipif_refrele(ipif);
9561 					ipif = ipif_lookup_group(ipha_dst,
9562 					    zoneid, ipst);
9563 					if (ipif != NULL) {
9564 						mp = copy_mp;
9565 						copy_mp = NULL;
9566 						multirt_resolve_next = B_TRUE;
9567 						continue;
9568 					} else {
9569 						freemsg(copy_mp);
9570 					}
9571 				}
9572 			}
9573 			if (ipif != NULL)
9574 				ipif_refrele(ipif);
9575 			ill_refrele(dst_ill);
9576 			ipif_refrele(src_ipif);
9577 			return;
9578 		default:
9579 			break;
9580 		}
9581 	} while (multirt_resolve_next);
9582 
9583 err_ret:
9584 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9585 	if (fire != NULL)
9586 		ire_refrele(fire);
9587 	ipif_refrele(ipif);
9588 	/* Did this packet originate externally? */
9589 	if (dst_ill != NULL)
9590 		ill_refrele(dst_ill);
9591 	if (src_ipif != NULL)
9592 		ipif_refrele(src_ipif);
9593 	if (mp->b_prev || mp->b_next) {
9594 		mp->b_next = NULL;
9595 		mp->b_prev = NULL;
9596 	} else {
9597 		/*
9598 		 * Since ip_wput() isn't close to finished, we fill
9599 		 * in enough of the header for credible error reporting.
9600 		 */
9601 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9602 			/* Failed */
9603 			freemsg(first_mp);
9604 			if (ire != NULL)
9605 				ire_refrele(ire);
9606 			return;
9607 		}
9608 	}
9609 	/*
9610 	 * At this point we will have ire only if RTF_BLACKHOLE
9611 	 * or RTF_REJECT flags are set on the IRE. It will not
9612 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9613 	 */
9614 	if (ire != NULL) {
9615 		if (ire->ire_flags & RTF_BLACKHOLE) {
9616 			ire_refrele(ire);
9617 			freemsg(first_mp);
9618 			return;
9619 		}
9620 		ire_refrele(ire);
9621 	}
9622 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9623 }
9624 
9625 /* Name/Value Table Lookup Routine */
9626 char *
9627 ip_nv_lookup(nv_t *nv, int value)
9628 {
9629 	if (!nv)
9630 		return (NULL);
9631 	for (; nv->nv_name; nv++) {
9632 		if (nv->nv_value == value)
9633 			return (nv->nv_name);
9634 	}
9635 	return ("unknown");
9636 }
9637 
9638 /*
9639  * This is a module open, i.e. this is a control stream for access
9640  * to a DLPI device.  We allocate an ill_t as the instance data in
9641  * this case.
9642  */
9643 int
9644 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9645 {
9646 	ill_t	*ill;
9647 	int	err;
9648 	zoneid_t zoneid;
9649 	netstack_t *ns;
9650 	ip_stack_t *ipst;
9651 
9652 	/*
9653 	 * Prevent unprivileged processes from pushing IP so that
9654 	 * they can't send raw IP.
9655 	 */
9656 	if (secpolicy_net_rawaccess(credp) != 0)
9657 		return (EPERM);
9658 
9659 	ns = netstack_find_by_cred(credp);
9660 	ASSERT(ns != NULL);
9661 	ipst = ns->netstack_ip;
9662 	ASSERT(ipst != NULL);
9663 
9664 	/*
9665 	 * For exclusive stacks we set the zoneid to zero
9666 	 * to make IP operate as if in the global zone.
9667 	 */
9668 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9669 		zoneid = GLOBAL_ZONEID;
9670 	else
9671 		zoneid = crgetzoneid(credp);
9672 
9673 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9674 	q->q_ptr = WR(q)->q_ptr = ill;
9675 	ill->ill_ipst = ipst;
9676 	ill->ill_zoneid = zoneid;
9677 
9678 	/*
9679 	 * ill_init initializes the ill fields and then sends down
9680 	 * down a DL_INFO_REQ after calling qprocson.
9681 	 */
9682 	err = ill_init(q, ill);
9683 	if (err != 0) {
9684 		mi_free(ill);
9685 		netstack_rele(ipst->ips_netstack);
9686 		q->q_ptr = NULL;
9687 		WR(q)->q_ptr = NULL;
9688 		return (err);
9689 	}
9690 
9691 	/* ill_init initializes the ipsq marking this thread as writer */
9692 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9693 	/* Wait for the DL_INFO_ACK */
9694 	mutex_enter(&ill->ill_lock);
9695 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9696 		/*
9697 		 * Return value of 0 indicates a pending signal.
9698 		 */
9699 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9700 		if (err == 0) {
9701 			mutex_exit(&ill->ill_lock);
9702 			(void) ip_close(q, 0);
9703 			return (EINTR);
9704 		}
9705 	}
9706 	mutex_exit(&ill->ill_lock);
9707 
9708 	/*
9709 	 * ip_rput_other could have set an error  in ill_error on
9710 	 * receipt of M_ERROR.
9711 	 */
9712 
9713 	err = ill->ill_error;
9714 	if (err != 0) {
9715 		(void) ip_close(q, 0);
9716 		return (err);
9717 	}
9718 
9719 	ill->ill_credp = credp;
9720 	crhold(credp);
9721 
9722 	mutex_enter(&ipst->ips_ip_mi_lock);
9723 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9724 	    credp);
9725 	mutex_exit(&ipst->ips_ip_mi_lock);
9726 	if (err) {
9727 		(void) ip_close(q, 0);
9728 		return (err);
9729 	}
9730 	return (0);
9731 }
9732 
9733 /* For /dev/ip aka AF_INET open */
9734 int
9735 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9736 {
9737 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9738 }
9739 
9740 /* For /dev/ip6 aka AF_INET6 open */
9741 int
9742 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9743 {
9744 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9745 }
9746 
9747 /* IP open routine. */
9748 int
9749 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9750     boolean_t isv6)
9751 {
9752 	conn_t 		*connp;
9753 	major_t		maj;
9754 	zoneid_t	zoneid;
9755 	netstack_t	*ns;
9756 	ip_stack_t	*ipst;
9757 
9758 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9759 
9760 	/* Allow reopen. */
9761 	if (q->q_ptr != NULL)
9762 		return (0);
9763 
9764 	if (sflag & MODOPEN) {
9765 		/* This is a module open */
9766 		return (ip_modopen(q, devp, flag, sflag, credp));
9767 	}
9768 
9769 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9770 		/*
9771 		 * Non streams based socket looking for a stream
9772 		 * to access IP
9773 		 */
9774 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9775 		    credp, isv6));
9776 	}
9777 
9778 	ns = netstack_find_by_cred(credp);
9779 	ASSERT(ns != NULL);
9780 	ipst = ns->netstack_ip;
9781 	ASSERT(ipst != NULL);
9782 
9783 	/*
9784 	 * For exclusive stacks we set the zoneid to zero
9785 	 * to make IP operate as if in the global zone.
9786 	 */
9787 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9788 		zoneid = GLOBAL_ZONEID;
9789 	else
9790 		zoneid = crgetzoneid(credp);
9791 
9792 	/*
9793 	 * We are opening as a device. This is an IP client stream, and we
9794 	 * allocate an conn_t as the instance data.
9795 	 */
9796 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9797 
9798 	/*
9799 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9800 	 * done by netstack_find_by_cred()
9801 	 */
9802 	netstack_rele(ipst->ips_netstack);
9803 
9804 	connp->conn_zoneid = zoneid;
9805 	connp->conn_sqp = NULL;
9806 	connp->conn_initial_sqp = NULL;
9807 	connp->conn_final_sqp = NULL;
9808 
9809 	connp->conn_upq = q;
9810 	q->q_ptr = WR(q)->q_ptr = connp;
9811 
9812 	if (flag & SO_SOCKSTR)
9813 		connp->conn_flags |= IPCL_SOCKET;
9814 
9815 	/* Minor tells us which /dev entry was opened */
9816 	if (isv6) {
9817 		connp->conn_flags |= IPCL_ISV6;
9818 		connp->conn_af_isv6 = B_TRUE;
9819 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9820 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9821 	} else {
9822 		connp->conn_af_isv6 = B_FALSE;
9823 		connp->conn_pkt_isv6 = B_FALSE;
9824 	}
9825 
9826 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9827 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9828 		connp->conn_minor_arena = ip_minor_arena_la;
9829 	} else {
9830 		/*
9831 		 * Either minor numbers in the large arena were exhausted
9832 		 * or a non socket application is doing the open.
9833 		 * Try to allocate from the small arena.
9834 		 */
9835 		if ((connp->conn_dev =
9836 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9837 			/* CONN_DEC_REF takes care of netstack_rele() */
9838 			q->q_ptr = WR(q)->q_ptr = NULL;
9839 			CONN_DEC_REF(connp);
9840 			return (EBUSY);
9841 		}
9842 		connp->conn_minor_arena = ip_minor_arena_sa;
9843 	}
9844 
9845 	maj = getemajor(*devp);
9846 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9847 
9848 	/*
9849 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9850 	 */
9851 	connp->conn_cred = credp;
9852 
9853 	/*
9854 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9855 	 */
9856 	connp->conn_recv = ip_conn_input;
9857 
9858 	crhold(connp->conn_cred);
9859 
9860 	/*
9861 	 * If the caller has the process-wide flag set, then default to MAC
9862 	 * exempt mode.  This allows read-down to unlabeled hosts.
9863 	 */
9864 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9865 		connp->conn_mac_exempt = B_TRUE;
9866 
9867 	connp->conn_rq = q;
9868 	connp->conn_wq = WR(q);
9869 
9870 	/* Non-zero default values */
9871 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9872 
9873 	/*
9874 	 * Make the conn globally visible to walkers
9875 	 */
9876 	ASSERT(connp->conn_ref == 1);
9877 	mutex_enter(&connp->conn_lock);
9878 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9879 	mutex_exit(&connp->conn_lock);
9880 
9881 	qprocson(q);
9882 
9883 	return (0);
9884 }
9885 
9886 /*
9887  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9888  * Note that there is no race since either ip_output function works - it
9889  * is just an optimization to enter the best ip_output routine directly.
9890  */
9891 void
9892 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9893     ip_stack_t *ipst)
9894 {
9895 	if (isv6)  {
9896 		if (bump_mib) {
9897 			BUMP_MIB(&ipst->ips_ip6_mib,
9898 			    ipIfStatsOutSwitchIPVersion);
9899 		}
9900 		connp->conn_send = ip_output_v6;
9901 		connp->conn_pkt_isv6 = B_TRUE;
9902 	} else {
9903 		if (bump_mib) {
9904 			BUMP_MIB(&ipst->ips_ip_mib,
9905 			    ipIfStatsOutSwitchIPVersion);
9906 		}
9907 		connp->conn_send = ip_output;
9908 		connp->conn_pkt_isv6 = B_FALSE;
9909 	}
9910 
9911 }
9912 
9913 /*
9914  * See if IPsec needs loading because of the options in mp.
9915  */
9916 static boolean_t
9917 ipsec_opt_present(mblk_t *mp)
9918 {
9919 	uint8_t *optcp, *next_optcp, *opt_endcp;
9920 	struct opthdr *opt;
9921 	struct T_opthdr *topt;
9922 	int opthdr_len;
9923 	t_uscalar_t optname, optlevel;
9924 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9925 	ipsec_req_t *ipsr;
9926 
9927 	/*
9928 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9929 	 * return TRUE.
9930 	 */
9931 
9932 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9933 	opt_endcp = optcp + tor->OPT_length;
9934 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9935 		opthdr_len = sizeof (struct T_opthdr);
9936 	} else {		/* O_OPTMGMT_REQ */
9937 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9938 		opthdr_len = sizeof (struct opthdr);
9939 	}
9940 	for (; optcp < opt_endcp; optcp = next_optcp) {
9941 		if (optcp + opthdr_len > opt_endcp)
9942 			return (B_FALSE);	/* Not enough option header. */
9943 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9944 			topt = (struct T_opthdr *)optcp;
9945 			optlevel = topt->level;
9946 			optname = topt->name;
9947 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9948 		} else {
9949 			opt = (struct opthdr *)optcp;
9950 			optlevel = opt->level;
9951 			optname = opt->name;
9952 			next_optcp = optcp + opthdr_len +
9953 			    _TPI_ALIGN_OPT(opt->len);
9954 		}
9955 		if ((next_optcp < optcp) || /* wraparound pointer space */
9956 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9957 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9958 			return (B_FALSE); /* bad option buffer */
9959 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9960 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9961 			/*
9962 			 * Check to see if it's an all-bypass or all-zeroes
9963 			 * IPsec request.  Don't bother loading IPsec if
9964 			 * the socket doesn't want to use it.  (A good example
9965 			 * is a bypass request.)
9966 			 *
9967 			 * Basically, if any of the non-NEVER bits are set,
9968 			 * load IPsec.
9969 			 */
9970 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9971 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9972 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9973 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9974 			    != 0)
9975 				return (B_TRUE);
9976 		}
9977 	}
9978 	return (B_FALSE);
9979 }
9980 
9981 /*
9982  * If conn is is waiting for ipsec to finish loading, kick it.
9983  */
9984 /* ARGSUSED */
9985 static void
9986 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9987 {
9988 	t_scalar_t	optreq_prim;
9989 	mblk_t		*mp;
9990 	cred_t		*cr;
9991 	int		err = 0;
9992 
9993 	/*
9994 	 * This function is called, after ipsec loading is complete.
9995 	 * Since IP checks exclusively and atomically (i.e it prevents
9996 	 * ipsec load from completing until ip_optcom_req completes)
9997 	 * whether ipsec load is complete, there cannot be a race with IP
9998 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9999 	 */
10000 	mutex_enter(&connp->conn_lock);
10001 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10002 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10003 		mp = connp->conn_ipsec_opt_mp;
10004 		connp->conn_ipsec_opt_mp = NULL;
10005 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10006 		mutex_exit(&connp->conn_lock);
10007 
10008 		/*
10009 		 * All Solaris components should pass a db_credp
10010 		 * for this TPI message, hence we ASSERT.
10011 		 * But in case there is some other M_PROTO that looks
10012 		 * like a TPI message sent by some other kernel
10013 		 * component, we check and return an error.
10014 		 */
10015 		cr = msg_getcred(mp, NULL);
10016 		ASSERT(cr != NULL);
10017 		if (cr == NULL) {
10018 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10019 			if (mp != NULL)
10020 				qreply(connp->conn_wq, mp);
10021 			return;
10022 		}
10023 
10024 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10025 
10026 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10027 		if (optreq_prim == T_OPTMGMT_REQ) {
10028 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10029 			    &ip_opt_obj, B_FALSE);
10030 		} else {
10031 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10032 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10033 			    &ip_opt_obj, B_FALSE);
10034 		}
10035 		if (err != EINPROGRESS)
10036 			CONN_OPER_PENDING_DONE(connp);
10037 		return;
10038 	}
10039 	mutex_exit(&connp->conn_lock);
10040 }
10041 
10042 /*
10043  * Called from the ipsec_loader thread, outside any perimeter, to tell
10044  * ip qenable any of the queues waiting for the ipsec loader to
10045  * complete.
10046  */
10047 void
10048 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10049 {
10050 	netstack_t *ns = ipss->ipsec_netstack;
10051 
10052 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10053 }
10054 
10055 /*
10056  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10057  * determines the grp on which it has to become exclusive, queues the mp
10058  * and IPSQ draining restarts the optmgmt
10059  */
10060 static boolean_t
10061 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10062 {
10063 	conn_t *connp = Q_TO_CONN(q);
10064 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10065 
10066 	/*
10067 	 * Take IPsec requests and treat them special.
10068 	 */
10069 	if (ipsec_opt_present(mp)) {
10070 		/* First check if IPsec is loaded. */
10071 		mutex_enter(&ipss->ipsec_loader_lock);
10072 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10073 			mutex_exit(&ipss->ipsec_loader_lock);
10074 			return (B_FALSE);
10075 		}
10076 		mutex_enter(&connp->conn_lock);
10077 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10078 
10079 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10080 		connp->conn_ipsec_opt_mp = mp;
10081 		mutex_exit(&connp->conn_lock);
10082 		mutex_exit(&ipss->ipsec_loader_lock);
10083 
10084 		ipsec_loader_loadnow(ipss);
10085 		return (B_TRUE);
10086 	}
10087 	return (B_FALSE);
10088 }
10089 
10090 /*
10091  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10092  * all of them are copied to the conn_t. If the req is "zero", the policy is
10093  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10094  * fields.
10095  * We keep only the latest setting of the policy and thus policy setting
10096  * is not incremental/cumulative.
10097  *
10098  * Requests to set policies with multiple alternative actions will
10099  * go through a different API.
10100  */
10101 int
10102 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10103 {
10104 	uint_t ah_req = 0;
10105 	uint_t esp_req = 0;
10106 	uint_t se_req = 0;
10107 	ipsec_selkey_t sel;
10108 	ipsec_act_t *actp = NULL;
10109 	uint_t nact;
10110 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10111 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10112 	ipsec_policy_root_t *pr;
10113 	ipsec_policy_head_t *ph;
10114 	int fam;
10115 	boolean_t is_pol_reset;
10116 	int error = 0;
10117 	netstack_t	*ns = connp->conn_netstack;
10118 	ip_stack_t	*ipst = ns->netstack_ip;
10119 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10120 
10121 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10122 
10123 	/*
10124 	 * The IP_SEC_OPT option does not allow variable length parameters,
10125 	 * hence a request cannot be NULL.
10126 	 */
10127 	if (req == NULL)
10128 		return (EINVAL);
10129 
10130 	ah_req = req->ipsr_ah_req;
10131 	esp_req = req->ipsr_esp_req;
10132 	se_req = req->ipsr_self_encap_req;
10133 
10134 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10135 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10136 		return (EINVAL);
10137 
10138 	/*
10139 	 * Are we dealing with a request to reset the policy (i.e.
10140 	 * zero requests).
10141 	 */
10142 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10143 	    (esp_req & REQ_MASK) == 0 &&
10144 	    (se_req & REQ_MASK) == 0);
10145 
10146 	if (!is_pol_reset) {
10147 		/*
10148 		 * If we couldn't load IPsec, fail with "protocol
10149 		 * not supported".
10150 		 * IPsec may not have been loaded for a request with zero
10151 		 * policies, so we don't fail in this case.
10152 		 */
10153 		mutex_enter(&ipss->ipsec_loader_lock);
10154 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10155 			mutex_exit(&ipss->ipsec_loader_lock);
10156 			return (EPROTONOSUPPORT);
10157 		}
10158 		mutex_exit(&ipss->ipsec_loader_lock);
10159 
10160 		/*
10161 		 * Test for valid requests. Invalid algorithms
10162 		 * need to be tested by IPsec code because new
10163 		 * algorithms can be added dynamically.
10164 		 */
10165 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10166 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10167 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10168 			return (EINVAL);
10169 		}
10170 
10171 		/*
10172 		 * Only privileged users can issue these
10173 		 * requests.
10174 		 */
10175 		if (((ah_req & IPSEC_PREF_NEVER) ||
10176 		    (esp_req & IPSEC_PREF_NEVER) ||
10177 		    (se_req & IPSEC_PREF_NEVER)) &&
10178 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10179 			return (EPERM);
10180 		}
10181 
10182 		/*
10183 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10184 		 * are mutually exclusive.
10185 		 */
10186 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10187 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10188 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10189 			/* Both of them are set */
10190 			return (EINVAL);
10191 		}
10192 	}
10193 
10194 	mutex_enter(&connp->conn_lock);
10195 
10196 	/*
10197 	 * If we have already cached policies in ip_bind_connected*(), don't
10198 	 * let them change now. We cache policies for connections
10199 	 * whose src,dst [addr, port] is known.
10200 	 */
10201 	if (connp->conn_policy_cached) {
10202 		mutex_exit(&connp->conn_lock);
10203 		return (EINVAL);
10204 	}
10205 
10206 	/*
10207 	 * We have a zero policies, reset the connection policy if already
10208 	 * set. This will cause the connection to inherit the
10209 	 * global policy, if any.
10210 	 */
10211 	if (is_pol_reset) {
10212 		if (connp->conn_policy != NULL) {
10213 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10214 			connp->conn_policy = NULL;
10215 		}
10216 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10217 		connp->conn_in_enforce_policy = B_FALSE;
10218 		connp->conn_out_enforce_policy = B_FALSE;
10219 		mutex_exit(&connp->conn_lock);
10220 		return (0);
10221 	}
10222 
10223 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10224 	    ipst->ips_netstack);
10225 	if (ph == NULL)
10226 		goto enomem;
10227 
10228 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10229 	if (actp == NULL)
10230 		goto enomem;
10231 
10232 	/*
10233 	 * Always allocate IPv4 policy entries, since they can also
10234 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10235 	 */
10236 	bzero(&sel, sizeof (sel));
10237 	sel.ipsl_valid = IPSL_IPV4;
10238 
10239 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10240 	    ipst->ips_netstack);
10241 	if (pin4 == NULL)
10242 		goto enomem;
10243 
10244 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10245 	    ipst->ips_netstack);
10246 	if (pout4 == NULL)
10247 		goto enomem;
10248 
10249 	if (connp->conn_af_isv6) {
10250 		/*
10251 		 * We're looking at a v6 socket, also allocate the
10252 		 * v6-specific entries...
10253 		 */
10254 		sel.ipsl_valid = IPSL_IPV6;
10255 		pin6 = ipsec_policy_create(&sel, actp, nact,
10256 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10257 		if (pin6 == NULL)
10258 			goto enomem;
10259 
10260 		pout6 = ipsec_policy_create(&sel, actp, nact,
10261 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10262 		if (pout6 == NULL)
10263 			goto enomem;
10264 
10265 		/*
10266 		 * .. and file them away in the right place.
10267 		 */
10268 		fam = IPSEC_AF_V6;
10269 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10270 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10271 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10272 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10273 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10274 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10275 	}
10276 
10277 	ipsec_actvec_free(actp, nact);
10278 
10279 	/*
10280 	 * File the v4 policies.
10281 	 */
10282 	fam = IPSEC_AF_V4;
10283 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10284 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10285 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10286 
10287 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10288 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10289 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10290 
10291 	/*
10292 	 * If the requests need security, set enforce_policy.
10293 	 * If the requests are IPSEC_PREF_NEVER, one should
10294 	 * still set conn_out_enforce_policy so that an ipsec_out
10295 	 * gets attached in ip_wput. This is needed so that
10296 	 * for connections that we don't cache policy in ip_bind,
10297 	 * if global policy matches in ip_wput_attach_policy, we
10298 	 * don't wrongly inherit global policy. Similarly, we need
10299 	 * to set conn_in_enforce_policy also so that we don't verify
10300 	 * policy wrongly.
10301 	 */
10302 	if ((ah_req & REQ_MASK) != 0 ||
10303 	    (esp_req & REQ_MASK) != 0 ||
10304 	    (se_req & REQ_MASK) != 0) {
10305 		connp->conn_in_enforce_policy = B_TRUE;
10306 		connp->conn_out_enforce_policy = B_TRUE;
10307 		connp->conn_flags |= IPCL_CHECK_POLICY;
10308 	}
10309 
10310 	mutex_exit(&connp->conn_lock);
10311 	return (error);
10312 #undef REQ_MASK
10313 
10314 	/*
10315 	 * Common memory-allocation-failure exit path.
10316 	 */
10317 enomem:
10318 	mutex_exit(&connp->conn_lock);
10319 	if (actp != NULL)
10320 		ipsec_actvec_free(actp, nact);
10321 	if (pin4 != NULL)
10322 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10323 	if (pout4 != NULL)
10324 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10325 	if (pin6 != NULL)
10326 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10327 	if (pout6 != NULL)
10328 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10329 	return (ENOMEM);
10330 }
10331 
10332 /*
10333  * Only for options that pass in an IP addr. Currently only V4 options
10334  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10335  * So this function assumes level is IPPROTO_IP
10336  */
10337 int
10338 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10339     mblk_t *first_mp)
10340 {
10341 	ipif_t *ipif = NULL;
10342 	int error;
10343 	ill_t *ill;
10344 	int zoneid;
10345 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10346 
10347 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10348 
10349 	if (addr != INADDR_ANY || checkonly) {
10350 		ASSERT(connp != NULL);
10351 		zoneid = IPCL_ZONEID(connp);
10352 		if (option == IP_NEXTHOP) {
10353 			ipif = ipif_lookup_onlink_addr(addr,
10354 			    connp->conn_zoneid, ipst);
10355 		} else {
10356 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10357 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10358 			    &error, ipst);
10359 		}
10360 		if (ipif == NULL) {
10361 			if (error == EINPROGRESS)
10362 				return (error);
10363 			if ((option == IP_MULTICAST_IF) ||
10364 			    (option == IP_NEXTHOP))
10365 				return (EHOSTUNREACH);
10366 			else
10367 				return (EINVAL);
10368 		} else if (checkonly) {
10369 			if (option == IP_MULTICAST_IF) {
10370 				ill = ipif->ipif_ill;
10371 				/* not supported by the virtual network iface */
10372 				if (IS_VNI(ill)) {
10373 					ipif_refrele(ipif);
10374 					return (EINVAL);
10375 				}
10376 			}
10377 			ipif_refrele(ipif);
10378 			return (0);
10379 		}
10380 		ill = ipif->ipif_ill;
10381 		mutex_enter(&connp->conn_lock);
10382 		mutex_enter(&ill->ill_lock);
10383 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10384 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10385 			mutex_exit(&ill->ill_lock);
10386 			mutex_exit(&connp->conn_lock);
10387 			ipif_refrele(ipif);
10388 			return (option == IP_MULTICAST_IF ?
10389 			    EHOSTUNREACH : EINVAL);
10390 		}
10391 	} else {
10392 		mutex_enter(&connp->conn_lock);
10393 	}
10394 
10395 	/* None of the options below are supported on the VNI */
10396 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10397 		mutex_exit(&ill->ill_lock);
10398 		mutex_exit(&connp->conn_lock);
10399 		ipif_refrele(ipif);
10400 		return (EINVAL);
10401 	}
10402 
10403 	switch (option) {
10404 	case IP_MULTICAST_IF:
10405 		connp->conn_multicast_ipif = ipif;
10406 		break;
10407 	case IP_NEXTHOP:
10408 		connp->conn_nexthop_v4 = addr;
10409 		connp->conn_nexthop_set = B_TRUE;
10410 		break;
10411 	}
10412 
10413 	if (ipif != NULL) {
10414 		mutex_exit(&ill->ill_lock);
10415 		mutex_exit(&connp->conn_lock);
10416 		ipif_refrele(ipif);
10417 		return (0);
10418 	}
10419 	mutex_exit(&connp->conn_lock);
10420 	/* We succeded in cleared the option */
10421 	return (0);
10422 }
10423 
10424 /*
10425  * For options that pass in an ifindex specifying the ill. V6 options always
10426  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10427  */
10428 int
10429 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10430     int level, int option, mblk_t *first_mp)
10431 {
10432 	ill_t *ill = NULL;
10433 	int error = 0;
10434 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10435 
10436 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10437 	if (ifindex != 0) {
10438 		ASSERT(connp != NULL);
10439 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10440 		    first_mp, ip_restart_optmgmt, &error, ipst);
10441 		if (ill != NULL) {
10442 			if (checkonly) {
10443 				/* not supported by the virtual network iface */
10444 				if (IS_VNI(ill)) {
10445 					ill_refrele(ill);
10446 					return (EINVAL);
10447 				}
10448 				ill_refrele(ill);
10449 				return (0);
10450 			}
10451 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10452 			    0, NULL)) {
10453 				ill_refrele(ill);
10454 				ill = NULL;
10455 				mutex_enter(&connp->conn_lock);
10456 				goto setit;
10457 			}
10458 			mutex_enter(&connp->conn_lock);
10459 			mutex_enter(&ill->ill_lock);
10460 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10461 				mutex_exit(&ill->ill_lock);
10462 				mutex_exit(&connp->conn_lock);
10463 				ill_refrele(ill);
10464 				ill = NULL;
10465 				mutex_enter(&connp->conn_lock);
10466 			}
10467 			goto setit;
10468 		} else if (error == EINPROGRESS) {
10469 			return (error);
10470 		} else {
10471 			error = 0;
10472 		}
10473 	}
10474 	mutex_enter(&connp->conn_lock);
10475 setit:
10476 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10477 
10478 	/*
10479 	 * The options below assume that the ILL (if any) transmits and/or
10480 	 * receives traffic. Neither of which is true for the virtual network
10481 	 * interface, so fail setting these on a VNI.
10482 	 */
10483 	if (IS_VNI(ill)) {
10484 		ASSERT(ill != NULL);
10485 		mutex_exit(&ill->ill_lock);
10486 		mutex_exit(&connp->conn_lock);
10487 		ill_refrele(ill);
10488 		return (EINVAL);
10489 	}
10490 
10491 	if (level == IPPROTO_IP) {
10492 		switch (option) {
10493 		case IP_BOUND_IF:
10494 			connp->conn_incoming_ill = ill;
10495 			connp->conn_outgoing_ill = ill;
10496 			break;
10497 
10498 		case IP_MULTICAST_IF:
10499 			/*
10500 			 * This option is an internal special. The socket
10501 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10502 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10503 			 * specifies an ifindex and we try first on V6 ill's.
10504 			 * If we don't find one, we they try using on v4 ill's
10505 			 * intenally and we come here.
10506 			 */
10507 			if (!checkonly && ill != NULL) {
10508 				ipif_t	*ipif;
10509 				ipif = ill->ill_ipif;
10510 
10511 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10512 					mutex_exit(&ill->ill_lock);
10513 					mutex_exit(&connp->conn_lock);
10514 					ill_refrele(ill);
10515 					ill = NULL;
10516 					mutex_enter(&connp->conn_lock);
10517 				} else {
10518 					connp->conn_multicast_ipif = ipif;
10519 				}
10520 			}
10521 			break;
10522 
10523 		case IP_DHCPINIT_IF:
10524 			if (connp->conn_dhcpinit_ill != NULL) {
10525 				/*
10526 				 * We've locked the conn so conn_cleanup_ill()
10527 				 * cannot clear conn_dhcpinit_ill -- so it's
10528 				 * safe to access the ill.
10529 				 */
10530 				ill_t *oill = connp->conn_dhcpinit_ill;
10531 
10532 				ASSERT(oill->ill_dhcpinit != 0);
10533 				atomic_dec_32(&oill->ill_dhcpinit);
10534 				connp->conn_dhcpinit_ill = NULL;
10535 			}
10536 
10537 			if (ill != NULL) {
10538 				connp->conn_dhcpinit_ill = ill;
10539 				atomic_inc_32(&ill->ill_dhcpinit);
10540 			}
10541 			break;
10542 		}
10543 	} else {
10544 		switch (option) {
10545 		case IPV6_BOUND_IF:
10546 			connp->conn_incoming_ill = ill;
10547 			connp->conn_outgoing_ill = ill;
10548 			break;
10549 
10550 		case IPV6_MULTICAST_IF:
10551 			/*
10552 			 * Set conn_multicast_ill to be the IPv6 ill.
10553 			 * Set conn_multicast_ipif to be an IPv4 ipif
10554 			 * for ifindex to make IPv4 mapped addresses
10555 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10556 			 * Even if no IPv6 ill exists for the ifindex
10557 			 * we need to check for an IPv4 ifindex in order
10558 			 * for this to work with mapped addresses. In that
10559 			 * case only set conn_multicast_ipif.
10560 			 */
10561 			if (!checkonly) {
10562 				if (ifindex == 0) {
10563 					connp->conn_multicast_ill = NULL;
10564 					connp->conn_multicast_ipif = NULL;
10565 				} else if (ill != NULL) {
10566 					connp->conn_multicast_ill = ill;
10567 				}
10568 			}
10569 			break;
10570 		}
10571 	}
10572 
10573 	if (ill != NULL) {
10574 		mutex_exit(&ill->ill_lock);
10575 		mutex_exit(&connp->conn_lock);
10576 		ill_refrele(ill);
10577 		return (0);
10578 	}
10579 	mutex_exit(&connp->conn_lock);
10580 	/*
10581 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10582 	 * locate the ill and could not set the option (ifindex != 0)
10583 	 */
10584 	return (ifindex == 0 ? 0 : EINVAL);
10585 }
10586 
10587 /* This routine sets socket options. */
10588 /* ARGSUSED */
10589 int
10590 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10591     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10592     void *dummy, cred_t *cr, mblk_t *first_mp)
10593 {
10594 	int		*i1 = (int *)invalp;
10595 	conn_t		*connp = Q_TO_CONN(q);
10596 	int		error = 0;
10597 	boolean_t	checkonly;
10598 	ire_t		*ire;
10599 	boolean_t	found;
10600 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10601 
10602 	switch (optset_context) {
10603 
10604 	case SETFN_OPTCOM_CHECKONLY:
10605 		checkonly = B_TRUE;
10606 		/*
10607 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10608 		 * inlen != 0 implies value supplied and
10609 		 * 	we have to "pretend" to set it.
10610 		 * inlen == 0 implies that there is no
10611 		 * 	value part in T_CHECK request and just validation
10612 		 * done elsewhere should be enough, we just return here.
10613 		 */
10614 		if (inlen == 0) {
10615 			*outlenp = 0;
10616 			return (0);
10617 		}
10618 		break;
10619 	case SETFN_OPTCOM_NEGOTIATE:
10620 	case SETFN_UD_NEGOTIATE:
10621 	case SETFN_CONN_NEGOTIATE:
10622 		checkonly = B_FALSE;
10623 		break;
10624 	default:
10625 		/*
10626 		 * We should never get here
10627 		 */
10628 		*outlenp = 0;
10629 		return (EINVAL);
10630 	}
10631 
10632 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10633 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10634 
10635 	/*
10636 	 * For fixed length options, no sanity check
10637 	 * of passed in length is done. It is assumed *_optcom_req()
10638 	 * routines do the right thing.
10639 	 */
10640 
10641 	switch (level) {
10642 	case SOL_SOCKET:
10643 		/*
10644 		 * conn_lock protects the bitfields, and is used to
10645 		 * set the fields atomically.
10646 		 */
10647 		switch (name) {
10648 		case SO_BROADCAST:
10649 			if (!checkonly) {
10650 				/* TODO: use value someplace? */
10651 				mutex_enter(&connp->conn_lock);
10652 				connp->conn_broadcast = *i1 ? 1 : 0;
10653 				mutex_exit(&connp->conn_lock);
10654 			}
10655 			break;	/* goto sizeof (int) option return */
10656 		case SO_USELOOPBACK:
10657 			if (!checkonly) {
10658 				/* TODO: use value someplace? */
10659 				mutex_enter(&connp->conn_lock);
10660 				connp->conn_loopback = *i1 ? 1 : 0;
10661 				mutex_exit(&connp->conn_lock);
10662 			}
10663 			break;	/* goto sizeof (int) option return */
10664 		case SO_DONTROUTE:
10665 			if (!checkonly) {
10666 				mutex_enter(&connp->conn_lock);
10667 				connp->conn_dontroute = *i1 ? 1 : 0;
10668 				mutex_exit(&connp->conn_lock);
10669 			}
10670 			break;	/* goto sizeof (int) option return */
10671 		case SO_REUSEADDR:
10672 			if (!checkonly) {
10673 				mutex_enter(&connp->conn_lock);
10674 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10675 				mutex_exit(&connp->conn_lock);
10676 			}
10677 			break;	/* goto sizeof (int) option return */
10678 		case SO_PROTOTYPE:
10679 			if (!checkonly) {
10680 				mutex_enter(&connp->conn_lock);
10681 				connp->conn_proto = *i1;
10682 				mutex_exit(&connp->conn_lock);
10683 			}
10684 			break;	/* goto sizeof (int) option return */
10685 		case SO_ALLZONES:
10686 			if (!checkonly) {
10687 				mutex_enter(&connp->conn_lock);
10688 				if (IPCL_IS_BOUND(connp)) {
10689 					mutex_exit(&connp->conn_lock);
10690 					return (EINVAL);
10691 				}
10692 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10693 				mutex_exit(&connp->conn_lock);
10694 			}
10695 			break;	/* goto sizeof (int) option return */
10696 		case SO_ANON_MLP:
10697 			if (!checkonly) {
10698 				mutex_enter(&connp->conn_lock);
10699 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10700 				mutex_exit(&connp->conn_lock);
10701 			}
10702 			break;	/* goto sizeof (int) option return */
10703 		case SO_MAC_EXEMPT:
10704 			if (secpolicy_net_mac_aware(cr) != 0 ||
10705 			    IPCL_IS_BOUND(connp))
10706 				return (EACCES);
10707 			if (!checkonly) {
10708 				mutex_enter(&connp->conn_lock);
10709 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10710 				mutex_exit(&connp->conn_lock);
10711 			}
10712 			break;	/* goto sizeof (int) option return */
10713 		default:
10714 			/*
10715 			 * "soft" error (negative)
10716 			 * option not handled at this level
10717 			 * Note: Do not modify *outlenp
10718 			 */
10719 			return (-EINVAL);
10720 		}
10721 		break;
10722 	case IPPROTO_IP:
10723 		switch (name) {
10724 		case IP_NEXTHOP:
10725 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10726 				return (EPERM);
10727 			/* FALLTHRU */
10728 		case IP_MULTICAST_IF: {
10729 			ipaddr_t addr = *i1;
10730 
10731 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10732 			    first_mp);
10733 			if (error != 0)
10734 				return (error);
10735 			break;	/* goto sizeof (int) option return */
10736 		}
10737 
10738 		case IP_MULTICAST_TTL:
10739 			/* Recorded in transport above IP */
10740 			*outvalp = *invalp;
10741 			*outlenp = sizeof (uchar_t);
10742 			return (0);
10743 		case IP_MULTICAST_LOOP:
10744 			if (!checkonly) {
10745 				mutex_enter(&connp->conn_lock);
10746 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10747 				mutex_exit(&connp->conn_lock);
10748 			}
10749 			*outvalp = *invalp;
10750 			*outlenp = sizeof (uchar_t);
10751 			return (0);
10752 		case IP_ADD_MEMBERSHIP:
10753 		case MCAST_JOIN_GROUP:
10754 		case IP_DROP_MEMBERSHIP:
10755 		case MCAST_LEAVE_GROUP: {
10756 			struct ip_mreq *mreqp;
10757 			struct group_req *greqp;
10758 			ire_t *ire;
10759 			boolean_t done = B_FALSE;
10760 			ipaddr_t group, ifaddr;
10761 			struct sockaddr_in *sin;
10762 			uint32_t *ifindexp;
10763 			boolean_t mcast_opt = B_TRUE;
10764 			mcast_record_t fmode;
10765 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10766 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10767 
10768 			switch (name) {
10769 			case IP_ADD_MEMBERSHIP:
10770 				mcast_opt = B_FALSE;
10771 				/* FALLTHRU */
10772 			case MCAST_JOIN_GROUP:
10773 				fmode = MODE_IS_EXCLUDE;
10774 				optfn = ip_opt_add_group;
10775 				break;
10776 
10777 			case IP_DROP_MEMBERSHIP:
10778 				mcast_opt = B_FALSE;
10779 				/* FALLTHRU */
10780 			case MCAST_LEAVE_GROUP:
10781 				fmode = MODE_IS_INCLUDE;
10782 				optfn = ip_opt_delete_group;
10783 				break;
10784 			}
10785 
10786 			if (mcast_opt) {
10787 				greqp = (struct group_req *)i1;
10788 				sin = (struct sockaddr_in *)&greqp->gr_group;
10789 				if (sin->sin_family != AF_INET) {
10790 					*outlenp = 0;
10791 					return (ENOPROTOOPT);
10792 				}
10793 				group = (ipaddr_t)sin->sin_addr.s_addr;
10794 				ifaddr = INADDR_ANY;
10795 				ifindexp = &greqp->gr_interface;
10796 			} else {
10797 				mreqp = (struct ip_mreq *)i1;
10798 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10799 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10800 				ifindexp = NULL;
10801 			}
10802 
10803 			/*
10804 			 * In the multirouting case, we need to replicate
10805 			 * the request on all interfaces that will take part
10806 			 * in replication.  We do so because multirouting is
10807 			 * reflective, thus we will probably receive multi-
10808 			 * casts on those interfaces.
10809 			 * The ip_multirt_apply_membership() succeeds if the
10810 			 * operation succeeds on at least one interface.
10811 			 */
10812 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10813 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10814 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10815 			if (ire != NULL) {
10816 				if (ire->ire_flags & RTF_MULTIRT) {
10817 					error = ip_multirt_apply_membership(
10818 					    optfn, ire, connp, checkonly, group,
10819 					    fmode, INADDR_ANY, first_mp);
10820 					done = B_TRUE;
10821 				}
10822 				ire_refrele(ire);
10823 			}
10824 			if (!done) {
10825 				error = optfn(connp, checkonly, group, ifaddr,
10826 				    ifindexp, fmode, INADDR_ANY, first_mp);
10827 			}
10828 			if (error) {
10829 				/*
10830 				 * EINPROGRESS is a soft error, needs retry
10831 				 * so don't make *outlenp zero.
10832 				 */
10833 				if (error != EINPROGRESS)
10834 					*outlenp = 0;
10835 				return (error);
10836 			}
10837 			/* OK return - copy input buffer into output buffer */
10838 			if (invalp != outvalp) {
10839 				/* don't trust bcopy for identical src/dst */
10840 				bcopy(invalp, outvalp, inlen);
10841 			}
10842 			*outlenp = inlen;
10843 			return (0);
10844 		}
10845 		case IP_BLOCK_SOURCE:
10846 		case IP_UNBLOCK_SOURCE:
10847 		case IP_ADD_SOURCE_MEMBERSHIP:
10848 		case IP_DROP_SOURCE_MEMBERSHIP:
10849 		case MCAST_BLOCK_SOURCE:
10850 		case MCAST_UNBLOCK_SOURCE:
10851 		case MCAST_JOIN_SOURCE_GROUP:
10852 		case MCAST_LEAVE_SOURCE_GROUP: {
10853 			struct ip_mreq_source *imreqp;
10854 			struct group_source_req *gsreqp;
10855 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10856 			uint32_t ifindex = 0;
10857 			mcast_record_t fmode;
10858 			struct sockaddr_in *sin;
10859 			ire_t *ire;
10860 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10861 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10862 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10863 
10864 			switch (name) {
10865 			case IP_BLOCK_SOURCE:
10866 				mcast_opt = B_FALSE;
10867 				/* FALLTHRU */
10868 			case MCAST_BLOCK_SOURCE:
10869 				fmode = MODE_IS_EXCLUDE;
10870 				optfn = ip_opt_add_group;
10871 				break;
10872 
10873 			case IP_UNBLOCK_SOURCE:
10874 				mcast_opt = B_FALSE;
10875 				/* FALLTHRU */
10876 			case MCAST_UNBLOCK_SOURCE:
10877 				fmode = MODE_IS_EXCLUDE;
10878 				optfn = ip_opt_delete_group;
10879 				break;
10880 
10881 			case IP_ADD_SOURCE_MEMBERSHIP:
10882 				mcast_opt = B_FALSE;
10883 				/* FALLTHRU */
10884 			case MCAST_JOIN_SOURCE_GROUP:
10885 				fmode = MODE_IS_INCLUDE;
10886 				optfn = ip_opt_add_group;
10887 				break;
10888 
10889 			case IP_DROP_SOURCE_MEMBERSHIP:
10890 				mcast_opt = B_FALSE;
10891 				/* FALLTHRU */
10892 			case MCAST_LEAVE_SOURCE_GROUP:
10893 				fmode = MODE_IS_INCLUDE;
10894 				optfn = ip_opt_delete_group;
10895 				break;
10896 			}
10897 
10898 			if (mcast_opt) {
10899 				gsreqp = (struct group_source_req *)i1;
10900 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10901 					*outlenp = 0;
10902 					return (ENOPROTOOPT);
10903 				}
10904 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10905 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10906 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10907 				src = (ipaddr_t)sin->sin_addr.s_addr;
10908 				ifindex = gsreqp->gsr_interface;
10909 			} else {
10910 				imreqp = (struct ip_mreq_source *)i1;
10911 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10912 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10913 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10914 			}
10915 
10916 			/*
10917 			 * In the multirouting case, we need to replicate
10918 			 * the request as noted in the mcast cases above.
10919 			 */
10920 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10921 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10922 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10923 			if (ire != NULL) {
10924 				if (ire->ire_flags & RTF_MULTIRT) {
10925 					error = ip_multirt_apply_membership(
10926 					    optfn, ire, connp, checkonly, grp,
10927 					    fmode, src, first_mp);
10928 					done = B_TRUE;
10929 				}
10930 				ire_refrele(ire);
10931 			}
10932 			if (!done) {
10933 				error = optfn(connp, checkonly, grp, ifaddr,
10934 				    &ifindex, fmode, src, first_mp);
10935 			}
10936 			if (error != 0) {
10937 				/*
10938 				 * EINPROGRESS is a soft error, needs retry
10939 				 * so don't make *outlenp zero.
10940 				 */
10941 				if (error != EINPROGRESS)
10942 					*outlenp = 0;
10943 				return (error);
10944 			}
10945 			/* OK return - copy input buffer into output buffer */
10946 			if (invalp != outvalp) {
10947 				bcopy(invalp, outvalp, inlen);
10948 			}
10949 			*outlenp = inlen;
10950 			return (0);
10951 		}
10952 		case IP_SEC_OPT:
10953 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10954 			if (error != 0) {
10955 				*outlenp = 0;
10956 				return (error);
10957 			}
10958 			break;
10959 		case IP_HDRINCL:
10960 		case IP_OPTIONS:
10961 		case T_IP_OPTIONS:
10962 		case IP_TOS:
10963 		case T_IP_TOS:
10964 		case IP_TTL:
10965 		case IP_RECVDSTADDR:
10966 		case IP_RECVOPTS:
10967 			/* OK return - copy input buffer into output buffer */
10968 			if (invalp != outvalp) {
10969 				/* don't trust bcopy for identical src/dst */
10970 				bcopy(invalp, outvalp, inlen);
10971 			}
10972 			*outlenp = inlen;
10973 			return (0);
10974 		case IP_RECVIF:
10975 			/* Retrieve the inbound interface index */
10976 			if (!checkonly) {
10977 				mutex_enter(&connp->conn_lock);
10978 				connp->conn_recvif = *i1 ? 1 : 0;
10979 				mutex_exit(&connp->conn_lock);
10980 			}
10981 			break;	/* goto sizeof (int) option return */
10982 		case IP_RECVPKTINFO:
10983 			if (!checkonly) {
10984 				mutex_enter(&connp->conn_lock);
10985 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10986 				mutex_exit(&connp->conn_lock);
10987 			}
10988 			break;	/* goto sizeof (int) option return */
10989 		case IP_RECVSLLA:
10990 			/* Retrieve the source link layer address */
10991 			if (!checkonly) {
10992 				mutex_enter(&connp->conn_lock);
10993 				connp->conn_recvslla = *i1 ? 1 : 0;
10994 				mutex_exit(&connp->conn_lock);
10995 			}
10996 			break;	/* goto sizeof (int) option return */
10997 		case MRT_INIT:
10998 		case MRT_DONE:
10999 		case MRT_ADD_VIF:
11000 		case MRT_DEL_VIF:
11001 		case MRT_ADD_MFC:
11002 		case MRT_DEL_MFC:
11003 		case MRT_ASSERT:
11004 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11005 				*outlenp = 0;
11006 				return (error);
11007 			}
11008 			error = ip_mrouter_set((int)name, q, checkonly,
11009 			    (uchar_t *)invalp, inlen, first_mp);
11010 			if (error) {
11011 				*outlenp = 0;
11012 				return (error);
11013 			}
11014 			/* OK return - copy input buffer into output buffer */
11015 			if (invalp != outvalp) {
11016 				/* don't trust bcopy for identical src/dst */
11017 				bcopy(invalp, outvalp, inlen);
11018 			}
11019 			*outlenp = inlen;
11020 			return (0);
11021 		case IP_BOUND_IF:
11022 		case IP_DHCPINIT_IF:
11023 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11024 			    level, name, first_mp);
11025 			if (error != 0)
11026 				return (error);
11027 			break; 		/* goto sizeof (int) option return */
11028 
11029 		case IP_UNSPEC_SRC:
11030 			/* Allow sending with a zero source address */
11031 			if (!checkonly) {
11032 				mutex_enter(&connp->conn_lock);
11033 				connp->conn_unspec_src = *i1 ? 1 : 0;
11034 				mutex_exit(&connp->conn_lock);
11035 			}
11036 			break;	/* goto sizeof (int) option return */
11037 		default:
11038 			/*
11039 			 * "soft" error (negative)
11040 			 * option not handled at this level
11041 			 * Note: Do not modify *outlenp
11042 			 */
11043 			return (-EINVAL);
11044 		}
11045 		break;
11046 	case IPPROTO_IPV6:
11047 		switch (name) {
11048 		case IPV6_BOUND_IF:
11049 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11050 			    level, name, first_mp);
11051 			if (error != 0)
11052 				return (error);
11053 			break; 		/* goto sizeof (int) option return */
11054 
11055 		case IPV6_MULTICAST_IF:
11056 			/*
11057 			 * The only possible errors are EINPROGRESS and
11058 			 * EINVAL. EINPROGRESS will be restarted and is not
11059 			 * a hard error. We call this option on both V4 and V6
11060 			 * If both return EINVAL, then this call returns
11061 			 * EINVAL. If at least one of them succeeds we
11062 			 * return success.
11063 			 */
11064 			found = B_FALSE;
11065 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11066 			    level, name, first_mp);
11067 			if (error == EINPROGRESS)
11068 				return (error);
11069 			if (error == 0)
11070 				found = B_TRUE;
11071 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11072 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11073 			if (error == 0)
11074 				found = B_TRUE;
11075 			if (!found)
11076 				return (error);
11077 			break; 		/* goto sizeof (int) option return */
11078 
11079 		case IPV6_MULTICAST_HOPS:
11080 			/* Recorded in transport above IP */
11081 			break;	/* goto sizeof (int) option return */
11082 		case IPV6_MULTICAST_LOOP:
11083 			if (!checkonly) {
11084 				mutex_enter(&connp->conn_lock);
11085 				connp->conn_multicast_loop = *i1;
11086 				mutex_exit(&connp->conn_lock);
11087 			}
11088 			break;	/* goto sizeof (int) option return */
11089 		case IPV6_JOIN_GROUP:
11090 		case MCAST_JOIN_GROUP:
11091 		case IPV6_LEAVE_GROUP:
11092 		case MCAST_LEAVE_GROUP: {
11093 			struct ipv6_mreq *ip_mreqp;
11094 			struct group_req *greqp;
11095 			ire_t *ire;
11096 			boolean_t done = B_FALSE;
11097 			in6_addr_t groupv6;
11098 			uint32_t ifindex;
11099 			boolean_t mcast_opt = B_TRUE;
11100 			mcast_record_t fmode;
11101 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11102 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11103 
11104 			switch (name) {
11105 			case IPV6_JOIN_GROUP:
11106 				mcast_opt = B_FALSE;
11107 				/* FALLTHRU */
11108 			case MCAST_JOIN_GROUP:
11109 				fmode = MODE_IS_EXCLUDE;
11110 				optfn = ip_opt_add_group_v6;
11111 				break;
11112 
11113 			case IPV6_LEAVE_GROUP:
11114 				mcast_opt = B_FALSE;
11115 				/* FALLTHRU */
11116 			case MCAST_LEAVE_GROUP:
11117 				fmode = MODE_IS_INCLUDE;
11118 				optfn = ip_opt_delete_group_v6;
11119 				break;
11120 			}
11121 
11122 			if (mcast_opt) {
11123 				struct sockaddr_in *sin;
11124 				struct sockaddr_in6 *sin6;
11125 				greqp = (struct group_req *)i1;
11126 				if (greqp->gr_group.ss_family == AF_INET) {
11127 					sin = (struct sockaddr_in *)
11128 					    &(greqp->gr_group);
11129 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11130 					    &groupv6);
11131 				} else {
11132 					sin6 = (struct sockaddr_in6 *)
11133 					    &(greqp->gr_group);
11134 					groupv6 = sin6->sin6_addr;
11135 				}
11136 				ifindex = greqp->gr_interface;
11137 			} else {
11138 				ip_mreqp = (struct ipv6_mreq *)i1;
11139 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11140 				ifindex = ip_mreqp->ipv6mr_interface;
11141 			}
11142 			/*
11143 			 * In the multirouting case, we need to replicate
11144 			 * the request on all interfaces that will take part
11145 			 * in replication.  We do so because multirouting is
11146 			 * reflective, thus we will probably receive multi-
11147 			 * casts on those interfaces.
11148 			 * The ip_multirt_apply_membership_v6() succeeds if
11149 			 * the operation succeeds on at least one interface.
11150 			 */
11151 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11152 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11153 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11154 			if (ire != NULL) {
11155 				if (ire->ire_flags & RTF_MULTIRT) {
11156 					error = ip_multirt_apply_membership_v6(
11157 					    optfn, ire, connp, checkonly,
11158 					    &groupv6, fmode, &ipv6_all_zeros,
11159 					    first_mp);
11160 					done = B_TRUE;
11161 				}
11162 				ire_refrele(ire);
11163 			}
11164 			if (!done) {
11165 				error = optfn(connp, checkonly, &groupv6,
11166 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11167 			}
11168 			if (error) {
11169 				/*
11170 				 * EINPROGRESS is a soft error, needs retry
11171 				 * so don't make *outlenp zero.
11172 				 */
11173 				if (error != EINPROGRESS)
11174 					*outlenp = 0;
11175 				return (error);
11176 			}
11177 			/* OK return - copy input buffer into output buffer */
11178 			if (invalp != outvalp) {
11179 				/* don't trust bcopy for identical src/dst */
11180 				bcopy(invalp, outvalp, inlen);
11181 			}
11182 			*outlenp = inlen;
11183 			return (0);
11184 		}
11185 		case MCAST_BLOCK_SOURCE:
11186 		case MCAST_UNBLOCK_SOURCE:
11187 		case MCAST_JOIN_SOURCE_GROUP:
11188 		case MCAST_LEAVE_SOURCE_GROUP: {
11189 			struct group_source_req *gsreqp;
11190 			in6_addr_t v6grp, v6src;
11191 			uint32_t ifindex;
11192 			mcast_record_t fmode;
11193 			ire_t *ire;
11194 			boolean_t done = B_FALSE;
11195 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11196 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11197 
11198 			switch (name) {
11199 			case MCAST_BLOCK_SOURCE:
11200 				fmode = MODE_IS_EXCLUDE;
11201 				optfn = ip_opt_add_group_v6;
11202 				break;
11203 			case MCAST_UNBLOCK_SOURCE:
11204 				fmode = MODE_IS_EXCLUDE;
11205 				optfn = ip_opt_delete_group_v6;
11206 				break;
11207 			case MCAST_JOIN_SOURCE_GROUP:
11208 				fmode = MODE_IS_INCLUDE;
11209 				optfn = ip_opt_add_group_v6;
11210 				break;
11211 			case MCAST_LEAVE_SOURCE_GROUP:
11212 				fmode = MODE_IS_INCLUDE;
11213 				optfn = ip_opt_delete_group_v6;
11214 				break;
11215 			}
11216 
11217 			gsreqp = (struct group_source_req *)i1;
11218 			ifindex = gsreqp->gsr_interface;
11219 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11220 				struct sockaddr_in *s;
11221 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11222 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11223 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11224 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11225 			} else {
11226 				struct sockaddr_in6 *s6;
11227 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11228 				v6grp = s6->sin6_addr;
11229 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11230 				v6src = s6->sin6_addr;
11231 			}
11232 
11233 			/*
11234 			 * In the multirouting case, we need to replicate
11235 			 * the request as noted in the mcast cases above.
11236 			 */
11237 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11238 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11239 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11240 			if (ire != NULL) {
11241 				if (ire->ire_flags & RTF_MULTIRT) {
11242 					error = ip_multirt_apply_membership_v6(
11243 					    optfn, ire, connp, checkonly,
11244 					    &v6grp, fmode, &v6src, first_mp);
11245 					done = B_TRUE;
11246 				}
11247 				ire_refrele(ire);
11248 			}
11249 			if (!done) {
11250 				error = optfn(connp, checkonly, &v6grp,
11251 				    ifindex, fmode, &v6src, first_mp);
11252 			}
11253 			if (error != 0) {
11254 				/*
11255 				 * EINPROGRESS is a soft error, needs retry
11256 				 * so don't make *outlenp zero.
11257 				 */
11258 				if (error != EINPROGRESS)
11259 					*outlenp = 0;
11260 				return (error);
11261 			}
11262 			/* OK return - copy input buffer into output buffer */
11263 			if (invalp != outvalp) {
11264 				bcopy(invalp, outvalp, inlen);
11265 			}
11266 			*outlenp = inlen;
11267 			return (0);
11268 		}
11269 		case IPV6_UNICAST_HOPS:
11270 			/* Recorded in transport above IP */
11271 			break;	/* goto sizeof (int) option return */
11272 		case IPV6_UNSPEC_SRC:
11273 			/* Allow sending with a zero source address */
11274 			if (!checkonly) {
11275 				mutex_enter(&connp->conn_lock);
11276 				connp->conn_unspec_src = *i1 ? 1 : 0;
11277 				mutex_exit(&connp->conn_lock);
11278 			}
11279 			break;	/* goto sizeof (int) option return */
11280 		case IPV6_RECVPKTINFO:
11281 			if (!checkonly) {
11282 				mutex_enter(&connp->conn_lock);
11283 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11284 				mutex_exit(&connp->conn_lock);
11285 			}
11286 			break;	/* goto sizeof (int) option return */
11287 		case IPV6_RECVTCLASS:
11288 			if (!checkonly) {
11289 				if (*i1 < 0 || *i1 > 1) {
11290 					return (EINVAL);
11291 				}
11292 				mutex_enter(&connp->conn_lock);
11293 				connp->conn_ipv6_recvtclass = *i1;
11294 				mutex_exit(&connp->conn_lock);
11295 			}
11296 			break;
11297 		case IPV6_RECVPATHMTU:
11298 			if (!checkonly) {
11299 				if (*i1 < 0 || *i1 > 1) {
11300 					return (EINVAL);
11301 				}
11302 				mutex_enter(&connp->conn_lock);
11303 				connp->conn_ipv6_recvpathmtu = *i1;
11304 				mutex_exit(&connp->conn_lock);
11305 			}
11306 			break;
11307 		case IPV6_RECVHOPLIMIT:
11308 			if (!checkonly) {
11309 				mutex_enter(&connp->conn_lock);
11310 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11311 				mutex_exit(&connp->conn_lock);
11312 			}
11313 			break;	/* goto sizeof (int) option return */
11314 		case IPV6_RECVHOPOPTS:
11315 			if (!checkonly) {
11316 				mutex_enter(&connp->conn_lock);
11317 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11318 				mutex_exit(&connp->conn_lock);
11319 			}
11320 			break;	/* goto sizeof (int) option return */
11321 		case IPV6_RECVDSTOPTS:
11322 			if (!checkonly) {
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;	/* goto sizeof (int) option return */
11328 		case IPV6_RECVRTHDR:
11329 			if (!checkonly) {
11330 				mutex_enter(&connp->conn_lock);
11331 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11332 				mutex_exit(&connp->conn_lock);
11333 			}
11334 			break;	/* goto sizeof (int) option return */
11335 		case IPV6_RECVRTHDRDSTOPTS:
11336 			if (!checkonly) {
11337 				mutex_enter(&connp->conn_lock);
11338 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11339 				mutex_exit(&connp->conn_lock);
11340 			}
11341 			break;	/* goto sizeof (int) option return */
11342 		case IPV6_PKTINFO:
11343 			if (inlen == 0)
11344 				return (-EINVAL);	/* clearing option */
11345 			error = ip6_set_pktinfo(cr, connp,
11346 			    (struct in6_pktinfo *)invalp);
11347 			if (error != 0)
11348 				*outlenp = 0;
11349 			else
11350 				*outlenp = inlen;
11351 			return (error);
11352 		case IPV6_NEXTHOP: {
11353 			struct sockaddr_in6 *sin6;
11354 
11355 			/* Verify that the nexthop is reachable */
11356 			if (inlen == 0)
11357 				return (-EINVAL);	/* clearing option */
11358 
11359 			sin6 = (struct sockaddr_in6 *)invalp;
11360 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11361 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11362 			    NULL, MATCH_IRE_DEFAULT, ipst);
11363 
11364 			if (ire == NULL) {
11365 				*outlenp = 0;
11366 				return (EHOSTUNREACH);
11367 			}
11368 			ire_refrele(ire);
11369 			return (-EINVAL);
11370 		}
11371 		case IPV6_SEC_OPT:
11372 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11373 			if (error != 0) {
11374 				*outlenp = 0;
11375 				return (error);
11376 			}
11377 			break;
11378 		case IPV6_SRC_PREFERENCES: {
11379 			/*
11380 			 * This is implemented strictly in the ip module
11381 			 * (here and in tcp_opt_*() to accomodate tcp
11382 			 * sockets).  Modules above ip pass this option
11383 			 * down here since ip is the only one that needs to
11384 			 * be aware of source address preferences.
11385 			 *
11386 			 * This socket option only affects connected
11387 			 * sockets that haven't already bound to a specific
11388 			 * IPv6 address.  In other words, sockets that
11389 			 * don't call bind() with an address other than the
11390 			 * unspecified address and that call connect().
11391 			 * ip_bind_connected_v6() passes these preferences
11392 			 * to the ipif_select_source_v6() function.
11393 			 */
11394 			if (inlen != sizeof (uint32_t))
11395 				return (EINVAL);
11396 			error = ip6_set_src_preferences(connp,
11397 			    *(uint32_t *)invalp);
11398 			if (error != 0) {
11399 				*outlenp = 0;
11400 				return (error);
11401 			} else {
11402 				*outlenp = sizeof (uint32_t);
11403 			}
11404 			break;
11405 		}
11406 		case IPV6_V6ONLY:
11407 			if (*i1 < 0 || *i1 > 1) {
11408 				return (EINVAL);
11409 			}
11410 			mutex_enter(&connp->conn_lock);
11411 			connp->conn_ipv6_v6only = *i1;
11412 			mutex_exit(&connp->conn_lock);
11413 			break;
11414 		default:
11415 			return (-EINVAL);
11416 		}
11417 		break;
11418 	default:
11419 		/*
11420 		 * "soft" error (negative)
11421 		 * option not handled at this level
11422 		 * Note: Do not modify *outlenp
11423 		 */
11424 		return (-EINVAL);
11425 	}
11426 	/*
11427 	 * Common case of return from an option that is sizeof (int)
11428 	 */
11429 	*(int *)outvalp = *i1;
11430 	*outlenp = sizeof (int);
11431 	return (0);
11432 }
11433 
11434 /*
11435  * This routine gets default values of certain options whose default
11436  * values are maintained by protocol specific code
11437  */
11438 /* ARGSUSED */
11439 int
11440 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11441 {
11442 	int *i1 = (int *)ptr;
11443 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11444 
11445 	switch (level) {
11446 	case IPPROTO_IP:
11447 		switch (name) {
11448 		case IP_MULTICAST_TTL:
11449 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11450 			return (sizeof (uchar_t));
11451 		case IP_MULTICAST_LOOP:
11452 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11453 			return (sizeof (uchar_t));
11454 		default:
11455 			return (-1);
11456 		}
11457 	case IPPROTO_IPV6:
11458 		switch (name) {
11459 		case IPV6_UNICAST_HOPS:
11460 			*i1 = ipst->ips_ipv6_def_hops;
11461 			return (sizeof (int));
11462 		case IPV6_MULTICAST_HOPS:
11463 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11464 			return (sizeof (int));
11465 		case IPV6_MULTICAST_LOOP:
11466 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11467 			return (sizeof (int));
11468 		case IPV6_V6ONLY:
11469 			*i1 = 1;
11470 			return (sizeof (int));
11471 		default:
11472 			return (-1);
11473 		}
11474 	default:
11475 		return (-1);
11476 	}
11477 	/* NOTREACHED */
11478 }
11479 
11480 /*
11481  * Given a destination address and a pointer to where to put the information
11482  * this routine fills in the mtuinfo.
11483  */
11484 int
11485 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11486     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11487 {
11488 	ire_t *ire;
11489 	ip_stack_t	*ipst = ns->netstack_ip;
11490 
11491 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11492 		return (-1);
11493 
11494 	bzero(mtuinfo, sizeof (*mtuinfo));
11495 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11496 	mtuinfo->ip6m_addr.sin6_port = port;
11497 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11498 
11499 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11500 	if (ire != NULL) {
11501 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11502 		ire_refrele(ire);
11503 	} else {
11504 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11505 	}
11506 	return (sizeof (struct ip6_mtuinfo));
11507 }
11508 
11509 /*
11510  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11511  * checking of cred and that ip_g_mrouter is set should be done and
11512  * isn't.  This doesn't matter as the error checking is done properly for the
11513  * other MRT options coming in through ip_opt_set.
11514  */
11515 int
11516 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11517 {
11518 	conn_t		*connp = Q_TO_CONN(q);
11519 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11520 
11521 	switch (level) {
11522 	case IPPROTO_IP:
11523 		switch (name) {
11524 		case MRT_VERSION:
11525 		case MRT_ASSERT:
11526 			(void) ip_mrouter_get(name, q, ptr);
11527 			return (sizeof (int));
11528 		case IP_SEC_OPT:
11529 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11530 		case IP_NEXTHOP:
11531 			if (connp->conn_nexthop_set) {
11532 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11533 				return (sizeof (ipaddr_t));
11534 			} else
11535 				return (0);
11536 		case IP_RECVPKTINFO:
11537 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11538 			return (sizeof (int));
11539 		default:
11540 			break;
11541 		}
11542 		break;
11543 	case IPPROTO_IPV6:
11544 		switch (name) {
11545 		case IPV6_SEC_OPT:
11546 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11547 		case IPV6_SRC_PREFERENCES: {
11548 			return (ip6_get_src_preferences(connp,
11549 			    (uint32_t *)ptr));
11550 		}
11551 		case IPV6_V6ONLY:
11552 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11553 			return (sizeof (int));
11554 		case IPV6_PATHMTU:
11555 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11556 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11557 		default:
11558 			break;
11559 		}
11560 		break;
11561 	default:
11562 		break;
11563 	}
11564 	return (-1);
11565 }
11566 /* Named Dispatch routine to get a current value out of our parameter table. */
11567 /* ARGSUSED */
11568 static int
11569 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11570 {
11571 	ipparam_t *ippa = (ipparam_t *)cp;
11572 
11573 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11574 	return (0);
11575 }
11576 
11577 /* ARGSUSED */
11578 static int
11579 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11580 {
11581 
11582 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11583 	return (0);
11584 }
11585 
11586 /*
11587  * Set ip{,6}_forwarding values.  This means walking through all of the
11588  * ill's and toggling their forwarding values.
11589  */
11590 /* ARGSUSED */
11591 static int
11592 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11593 {
11594 	long new_value;
11595 	int *forwarding_value = (int *)cp;
11596 	ill_t *ill;
11597 	boolean_t isv6;
11598 	ill_walk_context_t ctx;
11599 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11600 
11601 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11602 
11603 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11604 	    new_value < 0 || new_value > 1) {
11605 		return (EINVAL);
11606 	}
11607 
11608 	*forwarding_value = new_value;
11609 
11610 	/*
11611 	 * Regardless of the current value of ip_forwarding, set all per-ill
11612 	 * values of ip_forwarding to the value being set.
11613 	 *
11614 	 * Bring all the ill's up to date with the new global value.
11615 	 */
11616 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11617 
11618 	if (isv6)
11619 		ill = ILL_START_WALK_V6(&ctx, ipst);
11620 	else
11621 		ill = ILL_START_WALK_V4(&ctx, ipst);
11622 
11623 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11624 		(void) ill_forward_set(ill, new_value != 0);
11625 
11626 	rw_exit(&ipst->ips_ill_g_lock);
11627 	return (0);
11628 }
11629 
11630 /*
11631  * Walk through the param array specified registering each element with the
11632  * Named Dispatch handler. This is called only during init. So it is ok
11633  * not to acquire any locks
11634  */
11635 static boolean_t
11636 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11637     ipndp_t *ipnd, size_t ipnd_cnt)
11638 {
11639 	for (; ippa_cnt-- > 0; ippa++) {
11640 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11641 			if (!nd_load(ndp, ippa->ip_param_name,
11642 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11643 				nd_free(ndp);
11644 				return (B_FALSE);
11645 			}
11646 		}
11647 	}
11648 
11649 	for (; ipnd_cnt-- > 0; ipnd++) {
11650 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11651 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11652 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11653 			    ipnd->ip_ndp_data)) {
11654 				nd_free(ndp);
11655 				return (B_FALSE);
11656 			}
11657 		}
11658 	}
11659 
11660 	return (B_TRUE);
11661 }
11662 
11663 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11664 /* ARGSUSED */
11665 static int
11666 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11667 {
11668 	long		new_value;
11669 	ipparam_t	*ippa = (ipparam_t *)cp;
11670 
11671 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11672 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11673 		return (EINVAL);
11674 	}
11675 	ippa->ip_param_value = new_value;
11676 	return (0);
11677 }
11678 
11679 /*
11680  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11681  * When an ipf is passed here for the first time, if
11682  * we already have in-order fragments on the queue, we convert from the fast-
11683  * path reassembly scheme to the hard-case scheme.  From then on, additional
11684  * fragments are reassembled here.  We keep track of the start and end offsets
11685  * of each piece, and the number of holes in the chain.  When the hole count
11686  * goes to zero, we are done!
11687  *
11688  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11689  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11690  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11691  * after the call to ip_reassemble().
11692  */
11693 int
11694 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11695     size_t msg_len)
11696 {
11697 	uint_t	end;
11698 	mblk_t	*next_mp;
11699 	mblk_t	*mp1;
11700 	uint_t	offset;
11701 	boolean_t incr_dups = B_TRUE;
11702 	boolean_t offset_zero_seen = B_FALSE;
11703 	boolean_t pkt_boundary_checked = B_FALSE;
11704 
11705 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11706 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11707 
11708 	/* Add in byte count */
11709 	ipf->ipf_count += msg_len;
11710 	if (ipf->ipf_end) {
11711 		/*
11712 		 * We were part way through in-order reassembly, but now there
11713 		 * is a hole.  We walk through messages already queued, and
11714 		 * mark them for hard case reassembly.  We know that up till
11715 		 * now they were in order starting from offset zero.
11716 		 */
11717 		offset = 0;
11718 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11719 			IP_REASS_SET_START(mp1, offset);
11720 			if (offset == 0) {
11721 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11722 				offset = -ipf->ipf_nf_hdr_len;
11723 			}
11724 			offset += mp1->b_wptr - mp1->b_rptr;
11725 			IP_REASS_SET_END(mp1, offset);
11726 		}
11727 		/* One hole at the end. */
11728 		ipf->ipf_hole_cnt = 1;
11729 		/* Brand it as a hard case, forever. */
11730 		ipf->ipf_end = 0;
11731 	}
11732 	/* Walk through all the new pieces. */
11733 	do {
11734 		end = start + (mp->b_wptr - mp->b_rptr);
11735 		/*
11736 		 * If start is 0, decrease 'end' only for the first mblk of
11737 		 * the fragment. Otherwise 'end' can get wrong value in the
11738 		 * second pass of the loop if first mblk is exactly the
11739 		 * size of ipf_nf_hdr_len.
11740 		 */
11741 		if (start == 0 && !offset_zero_seen) {
11742 			/* First segment */
11743 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11744 			end -= ipf->ipf_nf_hdr_len;
11745 			offset_zero_seen = B_TRUE;
11746 		}
11747 		next_mp = mp->b_cont;
11748 		/*
11749 		 * We are checking to see if there is any interesing data
11750 		 * to process.  If there isn't and the mblk isn't the
11751 		 * one which carries the unfragmentable header then we
11752 		 * drop it.  It's possible to have just the unfragmentable
11753 		 * header come through without any data.  That needs to be
11754 		 * saved.
11755 		 *
11756 		 * If the assert at the top of this function holds then the
11757 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11758 		 * is infrequently traveled enough that the test is left in
11759 		 * to protect against future code changes which break that
11760 		 * invariant.
11761 		 */
11762 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11763 			/* Empty.  Blast it. */
11764 			IP_REASS_SET_START(mp, 0);
11765 			IP_REASS_SET_END(mp, 0);
11766 			/*
11767 			 * If the ipf points to the mblk we are about to free,
11768 			 * update ipf to point to the next mblk (or NULL
11769 			 * if none).
11770 			 */
11771 			if (ipf->ipf_mp->b_cont == mp)
11772 				ipf->ipf_mp->b_cont = next_mp;
11773 			freeb(mp);
11774 			continue;
11775 		}
11776 		mp->b_cont = NULL;
11777 		IP_REASS_SET_START(mp, start);
11778 		IP_REASS_SET_END(mp, end);
11779 		if (!ipf->ipf_tail_mp) {
11780 			ipf->ipf_tail_mp = mp;
11781 			ipf->ipf_mp->b_cont = mp;
11782 			if (start == 0 || !more) {
11783 				ipf->ipf_hole_cnt = 1;
11784 				/*
11785 				 * if the first fragment comes in more than one
11786 				 * mblk, this loop will be executed for each
11787 				 * mblk. Need to adjust hole count so exiting
11788 				 * this routine will leave hole count at 1.
11789 				 */
11790 				if (next_mp)
11791 					ipf->ipf_hole_cnt++;
11792 			} else
11793 				ipf->ipf_hole_cnt = 2;
11794 			continue;
11795 		} else if (ipf->ipf_last_frag_seen && !more &&
11796 		    !pkt_boundary_checked) {
11797 			/*
11798 			 * We check datagram boundary only if this fragment
11799 			 * claims to be the last fragment and we have seen a
11800 			 * last fragment in the past too. We do this only
11801 			 * once for a given fragment.
11802 			 *
11803 			 * start cannot be 0 here as fragments with start=0
11804 			 * and MF=0 gets handled as a complete packet. These
11805 			 * fragments should not reach here.
11806 			 */
11807 
11808 			if (start + msgdsize(mp) !=
11809 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11810 				/*
11811 				 * We have two fragments both of which claim
11812 				 * to be the last fragment but gives conflicting
11813 				 * information about the whole datagram size.
11814 				 * Something fishy is going on. Drop the
11815 				 * fragment and free up the reassembly list.
11816 				 */
11817 				return (IP_REASS_FAILED);
11818 			}
11819 
11820 			/*
11821 			 * We shouldn't come to this code block again for this
11822 			 * particular fragment.
11823 			 */
11824 			pkt_boundary_checked = B_TRUE;
11825 		}
11826 
11827 		/* New stuff at or beyond tail? */
11828 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11829 		if (start >= offset) {
11830 			if (ipf->ipf_last_frag_seen) {
11831 				/* current fragment is beyond last fragment */
11832 				return (IP_REASS_FAILED);
11833 			}
11834 			/* Link it on end. */
11835 			ipf->ipf_tail_mp->b_cont = mp;
11836 			ipf->ipf_tail_mp = mp;
11837 			if (more) {
11838 				if (start != offset)
11839 					ipf->ipf_hole_cnt++;
11840 			} else if (start == offset && next_mp == NULL)
11841 					ipf->ipf_hole_cnt--;
11842 			continue;
11843 		}
11844 		mp1 = ipf->ipf_mp->b_cont;
11845 		offset = IP_REASS_START(mp1);
11846 		/* New stuff at the front? */
11847 		if (start < offset) {
11848 			if (start == 0) {
11849 				if (end >= offset) {
11850 					/* Nailed the hole at the begining. */
11851 					ipf->ipf_hole_cnt--;
11852 				}
11853 			} else if (end < offset) {
11854 				/*
11855 				 * A hole, stuff, and a hole where there used
11856 				 * to be just a hole.
11857 				 */
11858 				ipf->ipf_hole_cnt++;
11859 			}
11860 			mp->b_cont = mp1;
11861 			/* Check for overlap. */
11862 			while (end > offset) {
11863 				if (end < IP_REASS_END(mp1)) {
11864 					mp->b_wptr -= end - offset;
11865 					IP_REASS_SET_END(mp, offset);
11866 					BUMP_MIB(ill->ill_ip_mib,
11867 					    ipIfStatsReasmPartDups);
11868 					break;
11869 				}
11870 				/* Did we cover another hole? */
11871 				if ((mp1->b_cont &&
11872 				    IP_REASS_END(mp1) !=
11873 				    IP_REASS_START(mp1->b_cont) &&
11874 				    end >= IP_REASS_START(mp1->b_cont)) ||
11875 				    (!ipf->ipf_last_frag_seen && !more)) {
11876 					ipf->ipf_hole_cnt--;
11877 				}
11878 				/* Clip out mp1. */
11879 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11880 					/*
11881 					 * After clipping out mp1, this guy
11882 					 * is now hanging off the end.
11883 					 */
11884 					ipf->ipf_tail_mp = mp;
11885 				}
11886 				IP_REASS_SET_START(mp1, 0);
11887 				IP_REASS_SET_END(mp1, 0);
11888 				/* Subtract byte count */
11889 				ipf->ipf_count -= mp1->b_datap->db_lim -
11890 				    mp1->b_datap->db_base;
11891 				freeb(mp1);
11892 				BUMP_MIB(ill->ill_ip_mib,
11893 				    ipIfStatsReasmPartDups);
11894 				mp1 = mp->b_cont;
11895 				if (!mp1)
11896 					break;
11897 				offset = IP_REASS_START(mp1);
11898 			}
11899 			ipf->ipf_mp->b_cont = mp;
11900 			continue;
11901 		}
11902 		/*
11903 		 * The new piece starts somewhere between the start of the head
11904 		 * and before the end of the tail.
11905 		 */
11906 		for (; mp1; mp1 = mp1->b_cont) {
11907 			offset = IP_REASS_END(mp1);
11908 			if (start < offset) {
11909 				if (end <= offset) {
11910 					/* Nothing new. */
11911 					IP_REASS_SET_START(mp, 0);
11912 					IP_REASS_SET_END(mp, 0);
11913 					/* Subtract byte count */
11914 					ipf->ipf_count -= mp->b_datap->db_lim -
11915 					    mp->b_datap->db_base;
11916 					if (incr_dups) {
11917 						ipf->ipf_num_dups++;
11918 						incr_dups = B_FALSE;
11919 					}
11920 					freeb(mp);
11921 					BUMP_MIB(ill->ill_ip_mib,
11922 					    ipIfStatsReasmDuplicates);
11923 					break;
11924 				}
11925 				/*
11926 				 * Trim redundant stuff off beginning of new
11927 				 * piece.
11928 				 */
11929 				IP_REASS_SET_START(mp, offset);
11930 				mp->b_rptr += offset - start;
11931 				BUMP_MIB(ill->ill_ip_mib,
11932 				    ipIfStatsReasmPartDups);
11933 				start = offset;
11934 				if (!mp1->b_cont) {
11935 					/*
11936 					 * After trimming, this guy is now
11937 					 * hanging off the end.
11938 					 */
11939 					mp1->b_cont = mp;
11940 					ipf->ipf_tail_mp = mp;
11941 					if (!more) {
11942 						ipf->ipf_hole_cnt--;
11943 					}
11944 					break;
11945 				}
11946 			}
11947 			if (start >= IP_REASS_START(mp1->b_cont))
11948 				continue;
11949 			/* Fill a hole */
11950 			if (start > offset)
11951 				ipf->ipf_hole_cnt++;
11952 			mp->b_cont = mp1->b_cont;
11953 			mp1->b_cont = mp;
11954 			mp1 = mp->b_cont;
11955 			offset = IP_REASS_START(mp1);
11956 			if (end >= offset) {
11957 				ipf->ipf_hole_cnt--;
11958 				/* Check for overlap. */
11959 				while (end > offset) {
11960 					if (end < IP_REASS_END(mp1)) {
11961 						mp->b_wptr -= end - offset;
11962 						IP_REASS_SET_END(mp, offset);
11963 						/*
11964 						 * TODO we might bump
11965 						 * this up twice if there is
11966 						 * overlap at both ends.
11967 						 */
11968 						BUMP_MIB(ill->ill_ip_mib,
11969 						    ipIfStatsReasmPartDups);
11970 						break;
11971 					}
11972 					/* Did we cover another hole? */
11973 					if ((mp1->b_cont &&
11974 					    IP_REASS_END(mp1)
11975 					    != IP_REASS_START(mp1->b_cont) &&
11976 					    end >=
11977 					    IP_REASS_START(mp1->b_cont)) ||
11978 					    (!ipf->ipf_last_frag_seen &&
11979 					    !more)) {
11980 						ipf->ipf_hole_cnt--;
11981 					}
11982 					/* Clip out mp1. */
11983 					if ((mp->b_cont = mp1->b_cont) ==
11984 					    NULL) {
11985 						/*
11986 						 * After clipping out mp1,
11987 						 * this guy is now hanging
11988 						 * off the end.
11989 						 */
11990 						ipf->ipf_tail_mp = mp;
11991 					}
11992 					IP_REASS_SET_START(mp1, 0);
11993 					IP_REASS_SET_END(mp1, 0);
11994 					/* Subtract byte count */
11995 					ipf->ipf_count -=
11996 					    mp1->b_datap->db_lim -
11997 					    mp1->b_datap->db_base;
11998 					freeb(mp1);
11999 					BUMP_MIB(ill->ill_ip_mib,
12000 					    ipIfStatsReasmPartDups);
12001 					mp1 = mp->b_cont;
12002 					if (!mp1)
12003 						break;
12004 					offset = IP_REASS_START(mp1);
12005 				}
12006 			}
12007 			break;
12008 		}
12009 	} while (start = end, mp = next_mp);
12010 
12011 	/* Fragment just processed could be the last one. Remember this fact */
12012 	if (!more)
12013 		ipf->ipf_last_frag_seen = B_TRUE;
12014 
12015 	/* Still got holes? */
12016 	if (ipf->ipf_hole_cnt)
12017 		return (IP_REASS_PARTIAL);
12018 	/* Clean up overloaded fields to avoid upstream disasters. */
12019 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12020 		IP_REASS_SET_START(mp1, 0);
12021 		IP_REASS_SET_END(mp1, 0);
12022 	}
12023 	return (IP_REASS_COMPLETE);
12024 }
12025 
12026 /*
12027  * ipsec processing for the fast path, used for input UDP Packets
12028  * Returns true if ready for passup to UDP.
12029  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12030  * was an ESP-in-UDP packet, etc.).
12031  */
12032 static boolean_t
12033 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12034     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12035 {
12036 	uint32_t	ill_index;
12037 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12038 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12039 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12040 	udp_t		*udp = connp->conn_udp;
12041 
12042 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12043 	/* The ill_index of the incoming ILL */
12044 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12045 
12046 	/* pass packet up to the transport */
12047 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12048 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12049 		    NULL, mctl_present);
12050 		if (*first_mpp == NULL) {
12051 			return (B_FALSE);
12052 		}
12053 	}
12054 
12055 	/* Initiate IPPF processing for fastpath UDP */
12056 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12057 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12058 		if (*mpp == NULL) {
12059 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12060 			    "deferred/dropped during IPPF processing\n"));
12061 			return (B_FALSE);
12062 		}
12063 	}
12064 	/*
12065 	 * Remove 0-spi if it's 0, or move everything behind
12066 	 * the UDP header over it and forward to ESP via
12067 	 * ip_proto_input().
12068 	 */
12069 	if (udp->udp_nat_t_endpoint) {
12070 		if (mctl_present) {
12071 			/* mctl_present *shouldn't* happen. */
12072 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12073 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12074 			    &ipss->ipsec_dropper);
12075 			*first_mpp = NULL;
12076 			return (B_FALSE);
12077 		}
12078 
12079 		/* "ill" is "recv_ill" in actuality. */
12080 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12081 			return (B_FALSE);
12082 
12083 		/* Else continue like a normal UDP packet. */
12084 	}
12085 
12086 	/*
12087 	 * We make the checks as below since we are in the fast path
12088 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12089 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12090 	 */
12091 	if (connp->conn_recvif || connp->conn_recvslla ||
12092 	    connp->conn_ip_recvpktinfo) {
12093 		if (connp->conn_recvif) {
12094 			in_flags = IPF_RECVIF;
12095 		}
12096 		/*
12097 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12098 		 * so the flag passed to ip_add_info is based on IP version
12099 		 * of connp.
12100 		 */
12101 		if (connp->conn_ip_recvpktinfo) {
12102 			if (connp->conn_af_isv6) {
12103 				/*
12104 				 * V6 only needs index
12105 				 */
12106 				in_flags |= IPF_RECVIF;
12107 			} else {
12108 				/*
12109 				 * V4 needs index + matching address.
12110 				 */
12111 				in_flags |= IPF_RECVADDR;
12112 			}
12113 		}
12114 		if (connp->conn_recvslla) {
12115 			in_flags |= IPF_RECVSLLA;
12116 		}
12117 		/*
12118 		 * since in_flags are being set ill will be
12119 		 * referenced in ip_add_info, so it better not
12120 		 * be NULL.
12121 		 */
12122 		/*
12123 		 * the actual data will be contained in b_cont
12124 		 * upon successful return of the following call.
12125 		 * If the call fails then the original mblk is
12126 		 * returned.
12127 		 */
12128 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12129 		    ipst);
12130 	}
12131 
12132 	return (B_TRUE);
12133 }
12134 
12135 /*
12136  * Fragmentation reassembly.  Each ILL has a hash table for
12137  * queuing packets undergoing reassembly for all IPIFs
12138  * associated with the ILL.  The hash is based on the packet
12139  * IP ident field.  The ILL frag hash table was allocated
12140  * as a timer block at the time the ILL was created.  Whenever
12141  * there is anything on the reassembly queue, the timer will
12142  * be running.  Returns B_TRUE if successful else B_FALSE;
12143  * frees mp on failure.
12144  */
12145 static boolean_t
12146 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12147     uint32_t *cksum_val, uint16_t *cksum_flags)
12148 {
12149 	uint32_t	frag_offset_flags;
12150 	mblk_t		*mp = *mpp;
12151 	mblk_t		*t_mp;
12152 	ipaddr_t	dst;
12153 	uint8_t		proto = ipha->ipha_protocol;
12154 	uint32_t	sum_val;
12155 	uint16_t	sum_flags;
12156 	ipf_t		*ipf;
12157 	ipf_t		**ipfp;
12158 	ipfb_t		*ipfb;
12159 	uint16_t	ident;
12160 	uint32_t	offset;
12161 	ipaddr_t	src;
12162 	uint_t		hdr_length;
12163 	uint32_t	end;
12164 	mblk_t		*mp1;
12165 	mblk_t		*tail_mp;
12166 	size_t		count;
12167 	size_t		msg_len;
12168 	uint8_t		ecn_info = 0;
12169 	uint32_t	packet_size;
12170 	boolean_t	pruned = B_FALSE;
12171 	ip_stack_t *ipst = ill->ill_ipst;
12172 
12173 	if (cksum_val != NULL)
12174 		*cksum_val = 0;
12175 	if (cksum_flags != NULL)
12176 		*cksum_flags = 0;
12177 
12178 	/*
12179 	 * Drop the fragmented as early as possible, if
12180 	 * we don't have resource(s) to re-assemble.
12181 	 */
12182 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12183 		freemsg(mp);
12184 		return (B_FALSE);
12185 	}
12186 
12187 	/* Check for fragmentation offset; return if there's none */
12188 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12189 	    (IPH_MF | IPH_OFFSET)) == 0)
12190 		return (B_TRUE);
12191 
12192 	/*
12193 	 * We utilize hardware computed checksum info only for UDP since
12194 	 * IP fragmentation is a normal occurrence for the protocol.  In
12195 	 * addition, checksum offload support for IP fragments carrying
12196 	 * UDP payload is commonly implemented across network adapters.
12197 	 */
12198 	ASSERT(recv_ill != NULL);
12199 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12200 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12201 		mblk_t *mp1 = mp->b_cont;
12202 		int32_t len;
12203 
12204 		/* Record checksum information from the packet */
12205 		sum_val = (uint32_t)DB_CKSUM16(mp);
12206 		sum_flags = DB_CKSUMFLAGS(mp);
12207 
12208 		/* IP payload offset from beginning of mblk */
12209 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12210 
12211 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12212 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12213 		    offset >= DB_CKSUMSTART(mp) &&
12214 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12215 			uint32_t adj;
12216 			/*
12217 			 * Partial checksum has been calculated by hardware
12218 			 * and attached to the packet; in addition, any
12219 			 * prepended extraneous data is even byte aligned.
12220 			 * If any such data exists, we adjust the checksum;
12221 			 * this would also handle any postpended data.
12222 			 */
12223 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12224 			    mp, mp1, len, adj);
12225 
12226 			/* One's complement subtract extraneous checksum */
12227 			if (adj >= sum_val)
12228 				sum_val = ~(adj - sum_val) & 0xFFFF;
12229 			else
12230 				sum_val -= adj;
12231 		}
12232 	} else {
12233 		sum_val = 0;
12234 		sum_flags = 0;
12235 	}
12236 
12237 	/* Clear hardware checksumming flag */
12238 	DB_CKSUMFLAGS(mp) = 0;
12239 
12240 	ident = ipha->ipha_ident;
12241 	offset = (frag_offset_flags << 3) & 0xFFFF;
12242 	src = ipha->ipha_src;
12243 	dst = ipha->ipha_dst;
12244 	hdr_length = IPH_HDR_LENGTH(ipha);
12245 	end = ntohs(ipha->ipha_length) - hdr_length;
12246 
12247 	/* If end == 0 then we have a packet with no data, so just free it */
12248 	if (end == 0) {
12249 		freemsg(mp);
12250 		return (B_FALSE);
12251 	}
12252 
12253 	/* Record the ECN field info. */
12254 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12255 	if (offset != 0) {
12256 		/*
12257 		 * If this isn't the first piece, strip the header, and
12258 		 * add the offset to the end value.
12259 		 */
12260 		mp->b_rptr += hdr_length;
12261 		end += offset;
12262 	}
12263 
12264 	msg_len = MBLKSIZE(mp);
12265 	tail_mp = mp;
12266 	while (tail_mp->b_cont != NULL) {
12267 		tail_mp = tail_mp->b_cont;
12268 		msg_len += MBLKSIZE(tail_mp);
12269 	}
12270 
12271 	/* If the reassembly list for this ILL will get too big, prune it */
12272 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12273 	    ipst->ips_ip_reass_queue_bytes) {
12274 		ill_frag_prune(ill,
12275 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12276 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12277 		pruned = B_TRUE;
12278 	}
12279 
12280 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12281 	mutex_enter(&ipfb->ipfb_lock);
12282 
12283 	ipfp = &ipfb->ipfb_ipf;
12284 	/* Try to find an existing fragment queue for this packet. */
12285 	for (;;) {
12286 		ipf = ipfp[0];
12287 		if (ipf != NULL) {
12288 			/*
12289 			 * It has to match on ident and src/dst address.
12290 			 */
12291 			if (ipf->ipf_ident == ident &&
12292 			    ipf->ipf_src == src &&
12293 			    ipf->ipf_dst == dst &&
12294 			    ipf->ipf_protocol == proto) {
12295 				/*
12296 				 * If we have received too many
12297 				 * duplicate fragments for this packet
12298 				 * free it.
12299 				 */
12300 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12301 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12302 					freemsg(mp);
12303 					mutex_exit(&ipfb->ipfb_lock);
12304 					return (B_FALSE);
12305 				}
12306 				/* Found it. */
12307 				break;
12308 			}
12309 			ipfp = &ipf->ipf_hash_next;
12310 			continue;
12311 		}
12312 
12313 		/*
12314 		 * If we pruned the list, do we want to store this new
12315 		 * fragment?. We apply an optimization here based on the
12316 		 * fact that most fragments will be received in order.
12317 		 * So if the offset of this incoming fragment is zero,
12318 		 * it is the first fragment of a new packet. We will
12319 		 * keep it.  Otherwise drop the fragment, as we have
12320 		 * probably pruned the packet already (since the
12321 		 * packet cannot be found).
12322 		 */
12323 		if (pruned && offset != 0) {
12324 			mutex_exit(&ipfb->ipfb_lock);
12325 			freemsg(mp);
12326 			return (B_FALSE);
12327 		}
12328 
12329 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12330 			/*
12331 			 * Too many fragmented packets in this hash
12332 			 * bucket. Free the oldest.
12333 			 */
12334 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12335 		}
12336 
12337 		/* New guy.  Allocate a frag message. */
12338 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12339 		if (mp1 == NULL) {
12340 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12341 			freemsg(mp);
12342 reass_done:
12343 			mutex_exit(&ipfb->ipfb_lock);
12344 			return (B_FALSE);
12345 		}
12346 
12347 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12348 		mp1->b_cont = mp;
12349 
12350 		/* Initialize the fragment header. */
12351 		ipf = (ipf_t *)mp1->b_rptr;
12352 		ipf->ipf_mp = mp1;
12353 		ipf->ipf_ptphn = ipfp;
12354 		ipfp[0] = ipf;
12355 		ipf->ipf_hash_next = NULL;
12356 		ipf->ipf_ident = ident;
12357 		ipf->ipf_protocol = proto;
12358 		ipf->ipf_src = src;
12359 		ipf->ipf_dst = dst;
12360 		ipf->ipf_nf_hdr_len = 0;
12361 		/* Record reassembly start time. */
12362 		ipf->ipf_timestamp = gethrestime_sec();
12363 		/* Record ipf generation and account for frag header */
12364 		ipf->ipf_gen = ill->ill_ipf_gen++;
12365 		ipf->ipf_count = MBLKSIZE(mp1);
12366 		ipf->ipf_last_frag_seen = B_FALSE;
12367 		ipf->ipf_ecn = ecn_info;
12368 		ipf->ipf_num_dups = 0;
12369 		ipfb->ipfb_frag_pkts++;
12370 		ipf->ipf_checksum = 0;
12371 		ipf->ipf_checksum_flags = 0;
12372 
12373 		/* Store checksum value in fragment header */
12374 		if (sum_flags != 0) {
12375 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12376 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12377 			ipf->ipf_checksum = sum_val;
12378 			ipf->ipf_checksum_flags = sum_flags;
12379 		}
12380 
12381 		/*
12382 		 * We handle reassembly two ways.  In the easy case,
12383 		 * where all the fragments show up in order, we do
12384 		 * minimal bookkeeping, and just clip new pieces on
12385 		 * the end.  If we ever see a hole, then we go off
12386 		 * to ip_reassemble which has to mark the pieces and
12387 		 * keep track of the number of holes, etc.  Obviously,
12388 		 * the point of having both mechanisms is so we can
12389 		 * handle the easy case as efficiently as possible.
12390 		 */
12391 		if (offset == 0) {
12392 			/* Easy case, in-order reassembly so far. */
12393 			ipf->ipf_count += msg_len;
12394 			ipf->ipf_tail_mp = tail_mp;
12395 			/*
12396 			 * Keep track of next expected offset in
12397 			 * ipf_end.
12398 			 */
12399 			ipf->ipf_end = end;
12400 			ipf->ipf_nf_hdr_len = hdr_length;
12401 		} else {
12402 			/* Hard case, hole at the beginning. */
12403 			ipf->ipf_tail_mp = NULL;
12404 			/*
12405 			 * ipf_end == 0 means that we have given up
12406 			 * on easy reassembly.
12407 			 */
12408 			ipf->ipf_end = 0;
12409 
12410 			/* Forget checksum offload from now on */
12411 			ipf->ipf_checksum_flags = 0;
12412 
12413 			/*
12414 			 * ipf_hole_cnt is set by ip_reassemble.
12415 			 * ipf_count is updated by ip_reassemble.
12416 			 * No need to check for return value here
12417 			 * as we don't expect reassembly to complete
12418 			 * or fail for the first fragment itself.
12419 			 */
12420 			(void) ip_reassemble(mp, ipf,
12421 			    (frag_offset_flags & IPH_OFFSET) << 3,
12422 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12423 		}
12424 		/* Update per ipfb and ill byte counts */
12425 		ipfb->ipfb_count += ipf->ipf_count;
12426 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12427 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12428 		/* If the frag timer wasn't already going, start it. */
12429 		mutex_enter(&ill->ill_lock);
12430 		ill_frag_timer_start(ill);
12431 		mutex_exit(&ill->ill_lock);
12432 		goto reass_done;
12433 	}
12434 
12435 	/*
12436 	 * If the packet's flag has changed (it could be coming up
12437 	 * from an interface different than the previous, therefore
12438 	 * possibly different checksum capability), then forget about
12439 	 * any stored checksum states.  Otherwise add the value to
12440 	 * the existing one stored in the fragment header.
12441 	 */
12442 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12443 		sum_val += ipf->ipf_checksum;
12444 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12445 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12446 		ipf->ipf_checksum = sum_val;
12447 	} else if (ipf->ipf_checksum_flags != 0) {
12448 		/* Forget checksum offload from now on */
12449 		ipf->ipf_checksum_flags = 0;
12450 	}
12451 
12452 	/*
12453 	 * We have a new piece of a datagram which is already being
12454 	 * reassembled.  Update the ECN info if all IP fragments
12455 	 * are ECN capable.  If there is one which is not, clear
12456 	 * all the info.  If there is at least one which has CE
12457 	 * code point, IP needs to report that up to transport.
12458 	 */
12459 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12460 		if (ecn_info == IPH_ECN_CE)
12461 			ipf->ipf_ecn = IPH_ECN_CE;
12462 	} else {
12463 		ipf->ipf_ecn = IPH_ECN_NECT;
12464 	}
12465 	if (offset && ipf->ipf_end == offset) {
12466 		/* The new fragment fits at the end */
12467 		ipf->ipf_tail_mp->b_cont = mp;
12468 		/* Update the byte count */
12469 		ipf->ipf_count += msg_len;
12470 		/* Update per ipfb and ill byte counts */
12471 		ipfb->ipfb_count += msg_len;
12472 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12473 		atomic_add_32(&ill->ill_frag_count, msg_len);
12474 		if (frag_offset_flags & IPH_MF) {
12475 			/* More to come. */
12476 			ipf->ipf_end = end;
12477 			ipf->ipf_tail_mp = tail_mp;
12478 			goto reass_done;
12479 		}
12480 	} else {
12481 		/* Go do the hard cases. */
12482 		int ret;
12483 
12484 		if (offset == 0)
12485 			ipf->ipf_nf_hdr_len = hdr_length;
12486 
12487 		/* Save current byte count */
12488 		count = ipf->ipf_count;
12489 		ret = ip_reassemble(mp, ipf,
12490 		    (frag_offset_flags & IPH_OFFSET) << 3,
12491 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12492 		/* Count of bytes added and subtracted (freeb()ed) */
12493 		count = ipf->ipf_count - count;
12494 		if (count) {
12495 			/* Update per ipfb and ill byte counts */
12496 			ipfb->ipfb_count += count;
12497 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12498 			atomic_add_32(&ill->ill_frag_count, count);
12499 		}
12500 		if (ret == IP_REASS_PARTIAL) {
12501 			goto reass_done;
12502 		} else if (ret == IP_REASS_FAILED) {
12503 			/* Reassembly failed. Free up all resources */
12504 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12505 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12506 				IP_REASS_SET_START(t_mp, 0);
12507 				IP_REASS_SET_END(t_mp, 0);
12508 			}
12509 			freemsg(mp);
12510 			goto reass_done;
12511 		}
12512 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12513 	}
12514 	/*
12515 	 * We have completed reassembly.  Unhook the frag header from
12516 	 * the reassembly list.
12517 	 *
12518 	 * Before we free the frag header, record the ECN info
12519 	 * to report back to the transport.
12520 	 */
12521 	ecn_info = ipf->ipf_ecn;
12522 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12523 	ipfp = ipf->ipf_ptphn;
12524 
12525 	/* We need to supply these to caller */
12526 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12527 		sum_val = ipf->ipf_checksum;
12528 	else
12529 		sum_val = 0;
12530 
12531 	mp1 = ipf->ipf_mp;
12532 	count = ipf->ipf_count;
12533 	ipf = ipf->ipf_hash_next;
12534 	if (ipf != NULL)
12535 		ipf->ipf_ptphn = ipfp;
12536 	ipfp[0] = ipf;
12537 	atomic_add_32(&ill->ill_frag_count, -count);
12538 	ASSERT(ipfb->ipfb_count >= count);
12539 	ipfb->ipfb_count -= count;
12540 	ipfb->ipfb_frag_pkts--;
12541 	mutex_exit(&ipfb->ipfb_lock);
12542 	/* Ditch the frag header. */
12543 	mp = mp1->b_cont;
12544 
12545 	freeb(mp1);
12546 
12547 	/* Restore original IP length in header. */
12548 	packet_size = (uint32_t)msgdsize(mp);
12549 	if (packet_size > IP_MAXPACKET) {
12550 		freemsg(mp);
12551 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12552 		return (B_FALSE);
12553 	}
12554 
12555 	if (DB_REF(mp) > 1) {
12556 		mblk_t *mp2 = copymsg(mp);
12557 
12558 		freemsg(mp);
12559 		if (mp2 == NULL) {
12560 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12561 			return (B_FALSE);
12562 		}
12563 		mp = mp2;
12564 	}
12565 	ipha = (ipha_t *)mp->b_rptr;
12566 
12567 	ipha->ipha_length = htons((uint16_t)packet_size);
12568 	/* We're now complete, zip the frag state */
12569 	ipha->ipha_fragment_offset_and_flags = 0;
12570 	/* Record the ECN info. */
12571 	ipha->ipha_type_of_service &= 0xFC;
12572 	ipha->ipha_type_of_service |= ecn_info;
12573 	*mpp = mp;
12574 
12575 	/* Reassembly is successful; return checksum information if needed */
12576 	if (cksum_val != NULL)
12577 		*cksum_val = sum_val;
12578 	if (cksum_flags != NULL)
12579 		*cksum_flags = sum_flags;
12580 
12581 	return (B_TRUE);
12582 }
12583 
12584 /*
12585  * Perform ip header check sum update local options.
12586  * return B_TRUE if all is well, else return B_FALSE and release
12587  * the mp. caller is responsible for decrementing ire ref cnt.
12588  */
12589 static boolean_t
12590 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12591     ip_stack_t *ipst)
12592 {
12593 	mblk_t		*first_mp;
12594 	boolean_t	mctl_present;
12595 	uint16_t	sum;
12596 
12597 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12598 	/*
12599 	 * Don't do the checksum if it has gone through AH/ESP
12600 	 * processing.
12601 	 */
12602 	if (!mctl_present) {
12603 		sum = ip_csum_hdr(ipha);
12604 		if (sum != 0) {
12605 			if (ill != NULL) {
12606 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12607 			} else {
12608 				BUMP_MIB(&ipst->ips_ip_mib,
12609 				    ipIfStatsInCksumErrs);
12610 			}
12611 			freemsg(first_mp);
12612 			return (B_FALSE);
12613 		}
12614 	}
12615 
12616 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12617 		if (mctl_present)
12618 			freeb(first_mp);
12619 		return (B_FALSE);
12620 	}
12621 
12622 	return (B_TRUE);
12623 }
12624 
12625 /*
12626  * All udp packet are delivered to the local host via this routine.
12627  */
12628 void
12629 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12630     ill_t *recv_ill)
12631 {
12632 	uint32_t	sum;
12633 	uint32_t	u1;
12634 	boolean_t	mctl_present;
12635 	conn_t		*connp;
12636 	mblk_t		*first_mp;
12637 	uint16_t	*up;
12638 	ill_t		*ill = (ill_t *)q->q_ptr;
12639 	uint16_t	reass_hck_flags = 0;
12640 	ip_stack_t	*ipst;
12641 
12642 	ASSERT(recv_ill != NULL);
12643 	ipst = recv_ill->ill_ipst;
12644 
12645 #define	rptr    ((uchar_t *)ipha)
12646 
12647 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12648 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12649 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12650 	ASSERT(ill != NULL);
12651 
12652 	/*
12653 	 * FAST PATH for udp packets
12654 	 */
12655 
12656 	/* u1 is # words of IP options */
12657 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12658 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12659 
12660 	/* IP options present */
12661 	if (u1 != 0)
12662 		goto ipoptions;
12663 
12664 	/* Check the IP header checksum.  */
12665 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12666 		/* Clear the IP header h/w cksum flag */
12667 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12668 	} else if (!mctl_present) {
12669 		/*
12670 		 * Don't verify header checksum if this packet is coming
12671 		 * back from AH/ESP as we already did it.
12672 		 */
12673 #define	uph	((uint16_t *)ipha)
12674 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12675 		    uph[6] + uph[7] + uph[8] + uph[9];
12676 #undef	uph
12677 		/* finish doing IP checksum */
12678 		sum = (sum & 0xFFFF) + (sum >> 16);
12679 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12680 		if (sum != 0 && sum != 0xFFFF) {
12681 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12682 			freemsg(first_mp);
12683 			return;
12684 		}
12685 	}
12686 
12687 	/*
12688 	 * Count for SNMP of inbound packets for ire.
12689 	 * if mctl is present this might be a secure packet and
12690 	 * has already been counted for in ip_proto_input().
12691 	 */
12692 	if (!mctl_present) {
12693 		UPDATE_IB_PKT_COUNT(ire);
12694 		ire->ire_last_used_time = lbolt;
12695 	}
12696 
12697 	/* packet part of fragmented IP packet? */
12698 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12699 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12700 		goto fragmented;
12701 	}
12702 
12703 	/* u1 = IP header length (20 bytes) */
12704 	u1 = IP_SIMPLE_HDR_LENGTH;
12705 
12706 	/* packet does not contain complete IP & UDP headers */
12707 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12708 		goto udppullup;
12709 
12710 	/* up points to UDP header */
12711 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12712 #define	iphs    ((uint16_t *)ipha)
12713 
12714 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12715 	if (up[3] != 0) {
12716 		mblk_t *mp1 = mp->b_cont;
12717 		boolean_t cksum_err;
12718 		uint16_t hck_flags = 0;
12719 
12720 		/* Pseudo-header checksum */
12721 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12722 		    iphs[9] + up[2];
12723 
12724 		/*
12725 		 * Revert to software checksum calculation if the interface
12726 		 * isn't capable of checksum offload or if IPsec is present.
12727 		 */
12728 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12729 			hck_flags = DB_CKSUMFLAGS(mp);
12730 
12731 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12732 			IP_STAT(ipst, ip_in_sw_cksum);
12733 
12734 		IP_CKSUM_RECV(hck_flags, u1,
12735 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12736 		    (int32_t)((uchar_t *)up - rptr),
12737 		    mp, mp1, cksum_err);
12738 
12739 		if (cksum_err) {
12740 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12741 			if (hck_flags & HCK_FULLCKSUM)
12742 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12743 			else if (hck_flags & HCK_PARTIALCKSUM)
12744 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12745 			else
12746 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12747 
12748 			freemsg(first_mp);
12749 			return;
12750 		}
12751 	}
12752 
12753 	/* Non-fragmented broadcast or multicast packet? */
12754 	if (ire->ire_type == IRE_BROADCAST)
12755 		goto udpslowpath;
12756 
12757 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12758 	    ire->ire_zoneid, ipst)) != NULL) {
12759 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12760 		IP_STAT(ipst, ip_udp_fast_path);
12761 
12762 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12763 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12764 			freemsg(mp);
12765 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12766 		} else {
12767 			if (!mctl_present) {
12768 				BUMP_MIB(ill->ill_ip_mib,
12769 				    ipIfStatsHCInDelivers);
12770 			}
12771 			/*
12772 			 * mp and first_mp can change.
12773 			 */
12774 			if (ip_udp_check(q, connp, recv_ill,
12775 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12776 				/* Send it upstream */
12777 				(connp->conn_recv)(connp, mp, NULL);
12778 			}
12779 		}
12780 		/*
12781 		 * freeb() cannot deal with null mblk being passed
12782 		 * in and first_mp can be set to null in the call
12783 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12784 		 */
12785 		if (mctl_present && first_mp != NULL) {
12786 			freeb(first_mp);
12787 		}
12788 		CONN_DEC_REF(connp);
12789 		return;
12790 	}
12791 
12792 	/*
12793 	 * if we got here we know the packet is not fragmented and
12794 	 * has no options. The classifier could not find a conn_t and
12795 	 * most likely its an icmp packet so send it through slow path.
12796 	 */
12797 
12798 	goto udpslowpath;
12799 
12800 ipoptions:
12801 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12802 		goto slow_done;
12803 	}
12804 
12805 	UPDATE_IB_PKT_COUNT(ire);
12806 	ire->ire_last_used_time = lbolt;
12807 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12808 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12809 fragmented:
12810 		/*
12811 		 * "sum" and "reass_hck_flags" are non-zero if the
12812 		 * reassembled packet has a valid hardware computed
12813 		 * checksum information associated with it.
12814 		 */
12815 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12816 		    &reass_hck_flags)) {
12817 			goto slow_done;
12818 		}
12819 
12820 		/*
12821 		 * Make sure that first_mp points back to mp as
12822 		 * the mp we came in with could have changed in
12823 		 * ip_rput_fragment().
12824 		 */
12825 		ASSERT(!mctl_present);
12826 		ipha = (ipha_t *)mp->b_rptr;
12827 		first_mp = mp;
12828 	}
12829 
12830 	/* Now we have a complete datagram, destined for this machine. */
12831 	u1 = IPH_HDR_LENGTH(ipha);
12832 	/* Pull up the UDP header, if necessary. */
12833 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12834 udppullup:
12835 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12836 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12837 			freemsg(first_mp);
12838 			goto slow_done;
12839 		}
12840 		ipha = (ipha_t *)mp->b_rptr;
12841 	}
12842 
12843 	/*
12844 	 * Validate the checksum for the reassembled packet; for the
12845 	 * pullup case we calculate the payload checksum in software.
12846 	 */
12847 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12848 	if (up[3] != 0) {
12849 		boolean_t cksum_err;
12850 
12851 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12852 			IP_STAT(ipst, ip_in_sw_cksum);
12853 
12854 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12855 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12856 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12857 		    iphs[9] + up[2], sum, cksum_err);
12858 
12859 		if (cksum_err) {
12860 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12861 
12862 			if (reass_hck_flags & HCK_FULLCKSUM)
12863 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12864 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12865 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12866 			else
12867 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12868 
12869 			freemsg(first_mp);
12870 			goto slow_done;
12871 		}
12872 	}
12873 udpslowpath:
12874 
12875 	/* Clear hardware checksum flag to be safe */
12876 	DB_CKSUMFLAGS(mp) = 0;
12877 
12878 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12879 	    (ire->ire_type == IRE_BROADCAST),
12880 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12881 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12882 
12883 slow_done:
12884 	IP_STAT(ipst, ip_udp_slow_path);
12885 	return;
12886 
12887 #undef  iphs
12888 #undef  rptr
12889 }
12890 
12891 /* ARGSUSED */
12892 static mblk_t *
12893 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12894     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12895     ill_rx_ring_t *ill_ring)
12896 {
12897 	conn_t		*connp;
12898 	uint32_t	sum;
12899 	uint32_t	u1;
12900 	uint16_t	*up;
12901 	int		offset;
12902 	ssize_t		len;
12903 	mblk_t		*mp1;
12904 	boolean_t	syn_present = B_FALSE;
12905 	tcph_t		*tcph;
12906 	uint_t		tcph_flags;
12907 	uint_t		ip_hdr_len;
12908 	ill_t		*ill = (ill_t *)q->q_ptr;
12909 	zoneid_t	zoneid = ire->ire_zoneid;
12910 	boolean_t	cksum_err;
12911 	uint16_t	hck_flags = 0;
12912 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12913 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12914 
12915 #define	rptr	((uchar_t *)ipha)
12916 
12917 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12918 	ASSERT(ill != NULL);
12919 
12920 	/*
12921 	 * FAST PATH for tcp packets
12922 	 */
12923 
12924 	/* u1 is # words of IP options */
12925 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12926 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12927 
12928 	/* IP options present */
12929 	if (u1) {
12930 		goto ipoptions;
12931 	} else if (!mctl_present) {
12932 		/* Check the IP header checksum.  */
12933 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12934 			/* Clear the IP header h/w cksum flag */
12935 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12936 		} else if (!mctl_present) {
12937 			/*
12938 			 * Don't verify header checksum if this packet
12939 			 * is coming back from AH/ESP as we already did it.
12940 			 */
12941 #define	uph	((uint16_t *)ipha)
12942 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12943 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12944 #undef	uph
12945 			/* finish doing IP checksum */
12946 			sum = (sum & 0xFFFF) + (sum >> 16);
12947 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12948 			if (sum != 0 && sum != 0xFFFF) {
12949 				BUMP_MIB(ill->ill_ip_mib,
12950 				    ipIfStatsInCksumErrs);
12951 				goto error;
12952 			}
12953 		}
12954 	}
12955 
12956 	if (!mctl_present) {
12957 		UPDATE_IB_PKT_COUNT(ire);
12958 		ire->ire_last_used_time = lbolt;
12959 	}
12960 
12961 	/* packet part of fragmented IP packet? */
12962 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12963 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12964 		goto fragmented;
12965 	}
12966 
12967 	/* u1 = IP header length (20 bytes) */
12968 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12969 
12970 	/* does packet contain IP+TCP headers? */
12971 	len = mp->b_wptr - rptr;
12972 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12973 		IP_STAT(ipst, ip_tcppullup);
12974 		goto tcppullup;
12975 	}
12976 
12977 	/* TCP options present? */
12978 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12979 
12980 	/*
12981 	 * If options need to be pulled up, then goto tcpoptions.
12982 	 * otherwise we are still in the fast path
12983 	 */
12984 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12985 		IP_STAT(ipst, ip_tcpoptions);
12986 		goto tcpoptions;
12987 	}
12988 
12989 	/* multiple mblks of tcp data? */
12990 	if ((mp1 = mp->b_cont) != NULL) {
12991 		/* more then two? */
12992 		if (mp1->b_cont != NULL) {
12993 			IP_STAT(ipst, ip_multipkttcp);
12994 			goto multipkttcp;
12995 		}
12996 		len += mp1->b_wptr - mp1->b_rptr;
12997 	}
12998 
12999 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13000 
13001 	/* part of pseudo checksum */
13002 
13003 	/* TCP datagram length */
13004 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13005 
13006 #define	iphs    ((uint16_t *)ipha)
13007 
13008 #ifdef	_BIG_ENDIAN
13009 	u1 += IPPROTO_TCP;
13010 #else
13011 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13012 #endif
13013 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13014 
13015 	/*
13016 	 * Revert to software checksum calculation if the interface
13017 	 * isn't capable of checksum offload or if IPsec is present.
13018 	 */
13019 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13020 		hck_flags = DB_CKSUMFLAGS(mp);
13021 
13022 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13023 		IP_STAT(ipst, ip_in_sw_cksum);
13024 
13025 	IP_CKSUM_RECV(hck_flags, u1,
13026 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13027 	    (int32_t)((uchar_t *)up - rptr),
13028 	    mp, mp1, cksum_err);
13029 
13030 	if (cksum_err) {
13031 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13032 
13033 		if (hck_flags & HCK_FULLCKSUM)
13034 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13035 		else if (hck_flags & HCK_PARTIALCKSUM)
13036 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13037 		else
13038 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13039 
13040 		goto error;
13041 	}
13042 
13043 try_again:
13044 
13045 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13046 	    zoneid, ipst)) == NULL) {
13047 		/* Send the TH_RST */
13048 		goto no_conn;
13049 	}
13050 
13051 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13052 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13053 
13054 	/*
13055 	 * TCP FAST PATH for AF_INET socket.
13056 	 *
13057 	 * TCP fast path to avoid extra work. An AF_INET socket type
13058 	 * does not have facility to receive extra information via
13059 	 * ip_process or ip_add_info. Also, when the connection was
13060 	 * established, we made a check if this connection is impacted
13061 	 * by any global IPsec policy or per connection policy (a
13062 	 * policy that comes in effect later will not apply to this
13063 	 * connection). Since all this can be determined at the
13064 	 * connection establishment time, a quick check of flags
13065 	 * can avoid extra work.
13066 	 */
13067 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13068 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13069 		ASSERT(first_mp == mp);
13070 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13071 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13072 			SET_SQUEUE(mp, tcp_rput_data, connp);
13073 			return (mp);
13074 		}
13075 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13076 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13077 		SET_SQUEUE(mp, tcp_input, connp);
13078 		return (mp);
13079 	}
13080 
13081 	if (tcph_flags == TH_SYN) {
13082 		if (IPCL_IS_TCP(connp)) {
13083 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13084 			DB_CKSUMSTART(mp) =
13085 			    (intptr_t)ip_squeue_get(ill_ring);
13086 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13087 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13088 				BUMP_MIB(ill->ill_ip_mib,
13089 				    ipIfStatsHCInDelivers);
13090 				SET_SQUEUE(mp, connp->conn_recv, connp);
13091 				return (mp);
13092 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13093 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13094 				BUMP_MIB(ill->ill_ip_mib,
13095 				    ipIfStatsHCInDelivers);
13096 				ip_squeue_enter_unbound++;
13097 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13098 				    connp);
13099 				return (mp);
13100 			}
13101 			syn_present = B_TRUE;
13102 		}
13103 	}
13104 
13105 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13106 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13107 
13108 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13109 		/* No need to send this packet to TCP */
13110 		if ((flags & TH_RST) || (flags & TH_URG)) {
13111 			CONN_DEC_REF(connp);
13112 			freemsg(first_mp);
13113 			return (NULL);
13114 		}
13115 		if (flags & TH_ACK) {
13116 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13117 			    ipst->ips_netstack->netstack_tcp, connp);
13118 			CONN_DEC_REF(connp);
13119 			return (NULL);
13120 		}
13121 
13122 		CONN_DEC_REF(connp);
13123 		freemsg(first_mp);
13124 		return (NULL);
13125 	}
13126 
13127 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13128 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13129 		    ipha, NULL, mctl_present);
13130 		if (first_mp == NULL) {
13131 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13132 			CONN_DEC_REF(connp);
13133 			return (NULL);
13134 		}
13135 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13136 			ASSERT(syn_present);
13137 			if (mctl_present) {
13138 				ASSERT(first_mp != mp);
13139 				first_mp->b_datap->db_struioflag |=
13140 				    STRUIO_POLICY;
13141 			} else {
13142 				ASSERT(first_mp == mp);
13143 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13144 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13145 			}
13146 		} else {
13147 			/*
13148 			 * Discard first_mp early since we're dealing with a
13149 			 * fully-connected conn_t and tcp doesn't do policy in
13150 			 * this case.
13151 			 */
13152 			if (mctl_present) {
13153 				freeb(first_mp);
13154 				mctl_present = B_FALSE;
13155 			}
13156 			first_mp = mp;
13157 		}
13158 	}
13159 
13160 	/* Initiate IPPF processing for fastpath */
13161 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13162 		uint32_t	ill_index;
13163 
13164 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13165 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13166 		if (mp == NULL) {
13167 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13168 			    "deferred/dropped during IPPF processing\n"));
13169 			CONN_DEC_REF(connp);
13170 			if (mctl_present)
13171 				freeb(first_mp);
13172 			return (NULL);
13173 		} else if (mctl_present) {
13174 			/*
13175 			 * ip_process might return a new mp.
13176 			 */
13177 			ASSERT(first_mp != mp);
13178 			first_mp->b_cont = mp;
13179 		} else {
13180 			first_mp = mp;
13181 		}
13182 
13183 	}
13184 
13185 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13186 		/*
13187 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13188 		 * make sure IPF_RECVIF is passed to ip_add_info.
13189 		 */
13190 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13191 		    IPCL_ZONEID(connp), ipst);
13192 		if (mp == NULL) {
13193 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13194 			CONN_DEC_REF(connp);
13195 			if (mctl_present)
13196 				freeb(first_mp);
13197 			return (NULL);
13198 		} else if (mctl_present) {
13199 			/*
13200 			 * ip_add_info might return a new mp.
13201 			 */
13202 			ASSERT(first_mp != mp);
13203 			first_mp->b_cont = mp;
13204 		} else {
13205 			first_mp = mp;
13206 		}
13207 	}
13208 
13209 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13210 	if (IPCL_IS_TCP(connp)) {
13211 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13212 		return (first_mp);
13213 	} else {
13214 		/* SOCK_RAW, IPPROTO_TCP case */
13215 		(connp->conn_recv)(connp, first_mp, NULL);
13216 		CONN_DEC_REF(connp);
13217 		return (NULL);
13218 	}
13219 
13220 no_conn:
13221 	/* Initiate IPPf processing, if needed. */
13222 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13223 		uint32_t ill_index;
13224 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13225 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13226 		if (first_mp == NULL) {
13227 			return (NULL);
13228 		}
13229 	}
13230 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13231 
13232 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13233 	    ipst->ips_netstack->netstack_tcp, NULL);
13234 	return (NULL);
13235 ipoptions:
13236 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13237 		goto slow_done;
13238 	}
13239 
13240 	UPDATE_IB_PKT_COUNT(ire);
13241 	ire->ire_last_used_time = lbolt;
13242 
13243 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13244 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13245 fragmented:
13246 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13247 			if (mctl_present)
13248 				freeb(first_mp);
13249 			goto slow_done;
13250 		}
13251 		/*
13252 		 * Make sure that first_mp points back to mp as
13253 		 * the mp we came in with could have changed in
13254 		 * ip_rput_fragment().
13255 		 */
13256 		ASSERT(!mctl_present);
13257 		ipha = (ipha_t *)mp->b_rptr;
13258 		first_mp = mp;
13259 	}
13260 
13261 	/* Now we have a complete datagram, destined for this machine. */
13262 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13263 
13264 	len = mp->b_wptr - mp->b_rptr;
13265 	/* Pull up a minimal TCP header, if necessary. */
13266 	if (len < (u1 + 20)) {
13267 tcppullup:
13268 		if (!pullupmsg(mp, u1 + 20)) {
13269 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13270 			goto error;
13271 		}
13272 		ipha = (ipha_t *)mp->b_rptr;
13273 		len = mp->b_wptr - mp->b_rptr;
13274 	}
13275 
13276 	/*
13277 	 * Extract the offset field from the TCP header.  As usual, we
13278 	 * try to help the compiler more than the reader.
13279 	 */
13280 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13281 	if (offset != 5) {
13282 tcpoptions:
13283 		if (offset < 5) {
13284 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13285 			goto error;
13286 		}
13287 		/*
13288 		 * There must be TCP options.
13289 		 * Make sure we can grab them.
13290 		 */
13291 		offset <<= 2;
13292 		offset += u1;
13293 		if (len < offset) {
13294 			if (!pullupmsg(mp, offset)) {
13295 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13296 				goto error;
13297 			}
13298 			ipha = (ipha_t *)mp->b_rptr;
13299 			len = mp->b_wptr - rptr;
13300 		}
13301 	}
13302 
13303 	/* Get the total packet length in len, including headers. */
13304 	if (mp->b_cont) {
13305 multipkttcp:
13306 		len = msgdsize(mp);
13307 	}
13308 
13309 	/*
13310 	 * Check the TCP checksum by pulling together the pseudo-
13311 	 * header checksum, and passing it to ip_csum to be added in
13312 	 * with the TCP datagram.
13313 	 *
13314 	 * Since we are not using the hwcksum if available we must
13315 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13316 	 * If either of these fails along the way the mblk is freed.
13317 	 * If this logic ever changes and mblk is reused to say send
13318 	 * ICMP's back, then this flag may need to be cleared in
13319 	 * other places as well.
13320 	 */
13321 	DB_CKSUMFLAGS(mp) = 0;
13322 
13323 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13324 
13325 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13326 #ifdef	_BIG_ENDIAN
13327 	u1 += IPPROTO_TCP;
13328 #else
13329 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13330 #endif
13331 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13332 	/*
13333 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13334 	 */
13335 	IP_STAT(ipst, ip_in_sw_cksum);
13336 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13337 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13338 		goto error;
13339 	}
13340 
13341 	IP_STAT(ipst, ip_tcp_slow_path);
13342 	goto try_again;
13343 #undef  iphs
13344 #undef  rptr
13345 
13346 error:
13347 	freemsg(first_mp);
13348 slow_done:
13349 	return (NULL);
13350 }
13351 
13352 /* ARGSUSED */
13353 static void
13354 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13355     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13356 {
13357 	conn_t		*connp;
13358 	uint32_t	sum;
13359 	uint32_t	u1;
13360 	ssize_t		len;
13361 	sctp_hdr_t	*sctph;
13362 	zoneid_t	zoneid = ire->ire_zoneid;
13363 	uint32_t	pktsum;
13364 	uint32_t	calcsum;
13365 	uint32_t	ports;
13366 	in6_addr_t	map_src, map_dst;
13367 	ill_t		*ill = (ill_t *)q->q_ptr;
13368 	ip_stack_t	*ipst;
13369 	sctp_stack_t	*sctps;
13370 	boolean_t	sctp_csum_err = B_FALSE;
13371 
13372 	ASSERT(recv_ill != NULL);
13373 	ipst = recv_ill->ill_ipst;
13374 	sctps = ipst->ips_netstack->netstack_sctp;
13375 
13376 #define	rptr	((uchar_t *)ipha)
13377 
13378 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13379 	ASSERT(ill != NULL);
13380 
13381 	/* u1 is # words of IP options */
13382 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13383 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13384 
13385 	/* IP options present */
13386 	if (u1 > 0) {
13387 		goto ipoptions;
13388 	} else {
13389 		/* Check the IP header checksum.  */
13390 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13391 		    !mctl_present) {
13392 #define	uph	((uint16_t *)ipha)
13393 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13394 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13395 #undef	uph
13396 			/* finish doing IP checksum */
13397 			sum = (sum & 0xFFFF) + (sum >> 16);
13398 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13399 			/*
13400 			 * Don't verify header checksum if this packet
13401 			 * is coming back from AH/ESP as we already did it.
13402 			 */
13403 			if (sum != 0 && sum != 0xFFFF) {
13404 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13405 				goto error;
13406 			}
13407 		}
13408 		/*
13409 		 * Since there is no SCTP h/w cksum support yet, just
13410 		 * clear the flag.
13411 		 */
13412 		DB_CKSUMFLAGS(mp) = 0;
13413 	}
13414 
13415 	/*
13416 	 * Don't verify header checksum if this packet is coming
13417 	 * back from AH/ESP as we already did it.
13418 	 */
13419 	if (!mctl_present) {
13420 		UPDATE_IB_PKT_COUNT(ire);
13421 		ire->ire_last_used_time = lbolt;
13422 	}
13423 
13424 	/* packet part of fragmented IP packet? */
13425 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13426 	if (u1 & (IPH_MF | IPH_OFFSET))
13427 		goto fragmented;
13428 
13429 	/* u1 = IP header length (20 bytes) */
13430 	u1 = IP_SIMPLE_HDR_LENGTH;
13431 
13432 find_sctp_client:
13433 	/* Pullup if we don't have the sctp common header. */
13434 	len = MBLKL(mp);
13435 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13436 		if (mp->b_cont == NULL ||
13437 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13438 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13439 			goto error;
13440 		}
13441 		ipha = (ipha_t *)mp->b_rptr;
13442 		len = MBLKL(mp);
13443 	}
13444 
13445 	sctph = (sctp_hdr_t *)(rptr + u1);
13446 #ifdef	DEBUG
13447 	if (!skip_sctp_cksum) {
13448 #endif
13449 		pktsum = sctph->sh_chksum;
13450 		sctph->sh_chksum = 0;
13451 		calcsum = sctp_cksum(mp, u1);
13452 		sctph->sh_chksum = pktsum;
13453 		if (calcsum != pktsum)
13454 			sctp_csum_err = B_TRUE;
13455 #ifdef	DEBUG	/* skip_sctp_cksum */
13456 	}
13457 #endif
13458 	/* get the ports */
13459 	ports = *(uint32_t *)&sctph->sh_sport;
13460 
13461 	IRE_REFRELE(ire);
13462 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13463 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13464 	if (sctp_csum_err) {
13465 		/*
13466 		 * No potential sctp checksum errors go to the Sun
13467 		 * sctp stack however they might be Adler-32 summed
13468 		 * packets a userland stack bound to a raw IP socket
13469 		 * could reasonably use. Note though that Adler-32 is
13470 		 * a long deprecated algorithm and customer sctp
13471 		 * networks should eventually migrate to CRC-32 at
13472 		 * which time this facility should be removed.
13473 		 */
13474 		flags |= IP_FF_SCTP_CSUM_ERR;
13475 		goto no_conn;
13476 	}
13477 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13478 	    sctps)) == NULL) {
13479 		/* Check for raw socket or OOTB handling */
13480 		goto no_conn;
13481 	}
13482 
13483 	/* Found a client; up it goes */
13484 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13485 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13486 	return;
13487 
13488 no_conn:
13489 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13490 	    ports, mctl_present, flags, B_TRUE, zoneid);
13491 	return;
13492 
13493 ipoptions:
13494 	DB_CKSUMFLAGS(mp) = 0;
13495 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13496 		goto slow_done;
13497 
13498 	UPDATE_IB_PKT_COUNT(ire);
13499 	ire->ire_last_used_time = lbolt;
13500 
13501 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13502 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13503 fragmented:
13504 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13505 			goto slow_done;
13506 		/*
13507 		 * Make sure that first_mp points back to mp as
13508 		 * the mp we came in with could have changed in
13509 		 * ip_rput_fragment().
13510 		 */
13511 		ASSERT(!mctl_present);
13512 		ipha = (ipha_t *)mp->b_rptr;
13513 		first_mp = mp;
13514 	}
13515 
13516 	/* Now we have a complete datagram, destined for this machine. */
13517 	u1 = IPH_HDR_LENGTH(ipha);
13518 	goto find_sctp_client;
13519 #undef  iphs
13520 #undef  rptr
13521 
13522 error:
13523 	freemsg(first_mp);
13524 slow_done:
13525 	IRE_REFRELE(ire);
13526 }
13527 
13528 #define	VER_BITS	0xF0
13529 #define	VERSION_6	0x60
13530 
13531 static boolean_t
13532 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13533     ipaddr_t *dstp, ip_stack_t *ipst)
13534 {
13535 	uint_t	opt_len;
13536 	ipha_t *ipha;
13537 	ssize_t len;
13538 	uint_t	pkt_len;
13539 
13540 	ASSERT(ill != NULL);
13541 	IP_STAT(ipst, ip_ipoptions);
13542 	ipha = *iphapp;
13543 
13544 #define	rptr    ((uchar_t *)ipha)
13545 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13546 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13547 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13548 		freemsg(mp);
13549 		return (B_FALSE);
13550 	}
13551 
13552 	/* multiple mblk or too short */
13553 	pkt_len = ntohs(ipha->ipha_length);
13554 
13555 	/* Get the number of words of IP options in the IP header. */
13556 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13557 	if (opt_len) {
13558 		/* IP Options present!  Validate and process. */
13559 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13560 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13561 			goto done;
13562 		}
13563 		/*
13564 		 * Recompute complete header length and make sure we
13565 		 * have access to all of it.
13566 		 */
13567 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13568 		if (len > (mp->b_wptr - rptr)) {
13569 			if (len > pkt_len) {
13570 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13571 				goto done;
13572 			}
13573 			if (!pullupmsg(mp, len)) {
13574 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13575 				goto done;
13576 			}
13577 			ipha = (ipha_t *)mp->b_rptr;
13578 		}
13579 		/*
13580 		 * Go off to ip_rput_options which returns the next hop
13581 		 * destination address, which may have been affected
13582 		 * by source routing.
13583 		 */
13584 		IP_STAT(ipst, ip_opt);
13585 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13586 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13587 			return (B_FALSE);
13588 		}
13589 	}
13590 	*iphapp = ipha;
13591 	return (B_TRUE);
13592 done:
13593 	/* clear b_prev - used by ip_mroute_decap */
13594 	mp->b_prev = NULL;
13595 	freemsg(mp);
13596 	return (B_FALSE);
13597 #undef  rptr
13598 }
13599 
13600 /*
13601  * Deal with the fact that there is no ire for the destination.
13602  */
13603 static ire_t *
13604 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13605 {
13606 	ipha_t	*ipha;
13607 	ill_t	*ill;
13608 	ire_t	*ire;
13609 	ip_stack_t *ipst;
13610 	enum	ire_forward_action ret_action;
13611 
13612 	ipha = (ipha_t *)mp->b_rptr;
13613 	ill = (ill_t *)q->q_ptr;
13614 
13615 	ASSERT(ill != NULL);
13616 	ipst = ill->ill_ipst;
13617 
13618 	/*
13619 	 * No IRE for this destination, so it can't be for us.
13620 	 * Unless we are forwarding, drop the packet.
13621 	 * We have to let source routed packets through
13622 	 * since we don't yet know if they are 'ping -l'
13623 	 * packets i.e. if they will go out over the
13624 	 * same interface as they came in on.
13625 	 */
13626 	if (ll_multicast) {
13627 		freemsg(mp);
13628 		return (NULL);
13629 	}
13630 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13631 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13632 		freemsg(mp);
13633 		return (NULL);
13634 	}
13635 
13636 	/*
13637 	 * Mark this packet as having originated externally.
13638 	 *
13639 	 * For non-forwarding code path, ire_send later double
13640 	 * checks this interface to see if it is still exists
13641 	 * post-ARP resolution.
13642 	 *
13643 	 * Also, IPQOS uses this to differentiate between
13644 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13645 	 * QOS packet processing in ip_wput_attach_llhdr().
13646 	 * The QoS module can mark the b_band for a fastpath message
13647 	 * or the dl_priority field in a unitdata_req header for
13648 	 * CoS marking. This info can only be found in
13649 	 * ip_wput_attach_llhdr().
13650 	 */
13651 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13652 	/*
13653 	 * Clear the indication that this may have a hardware checksum
13654 	 * as we are not using it
13655 	 */
13656 	DB_CKSUMFLAGS(mp) = 0;
13657 
13658 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13659 	    msg_getlabel(mp), ipst);
13660 
13661 	if (ire == NULL && ret_action == Forward_check_multirt) {
13662 		/* Let ip_newroute handle CGTP  */
13663 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13664 		return (NULL);
13665 	}
13666 
13667 	if (ire != NULL)
13668 		return (ire);
13669 
13670 	mp->b_prev = mp->b_next = 0;
13671 
13672 	if (ret_action == Forward_blackhole) {
13673 		freemsg(mp);
13674 		return (NULL);
13675 	}
13676 	/* send icmp unreachable */
13677 	q = WR(q);
13678 	/* Sent by forwarding path, and router is global zone */
13679 	if (ip_source_routed(ipha, ipst)) {
13680 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13681 		    GLOBAL_ZONEID, ipst);
13682 	} else {
13683 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13684 		    ipst);
13685 	}
13686 
13687 	return (NULL);
13688 
13689 }
13690 
13691 /*
13692  * check ip header length and align it.
13693  */
13694 static boolean_t
13695 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13696 {
13697 	ssize_t len;
13698 	ill_t *ill;
13699 	ipha_t	*ipha;
13700 
13701 	len = MBLKL(mp);
13702 
13703 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13704 		ill = (ill_t *)q->q_ptr;
13705 
13706 		if (!OK_32PTR(mp->b_rptr))
13707 			IP_STAT(ipst, ip_notaligned1);
13708 		else
13709 			IP_STAT(ipst, ip_notaligned2);
13710 		/* Guard against bogus device drivers */
13711 		if (len < 0) {
13712 			/* clear b_prev - used by ip_mroute_decap */
13713 			mp->b_prev = NULL;
13714 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13715 			freemsg(mp);
13716 			return (B_FALSE);
13717 		}
13718 
13719 		if (ip_rput_pullups++ == 0) {
13720 			ipha = (ipha_t *)mp->b_rptr;
13721 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13722 			    "ip_check_and_align_header: %s forced us to "
13723 			    " pullup pkt, hdr len %ld, hdr addr %p",
13724 			    ill->ill_name, len, (void *)ipha);
13725 		}
13726 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13727 			/* clear b_prev - used by ip_mroute_decap */
13728 			mp->b_prev = NULL;
13729 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13730 			freemsg(mp);
13731 			return (B_FALSE);
13732 		}
13733 	}
13734 	return (B_TRUE);
13735 }
13736 
13737 /*
13738  * Handle the situation where a packet came in on `ill' but matched an IRE
13739  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13740  * for interface statistics.
13741  */
13742 ire_t *
13743 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13744 {
13745 	ire_t		*new_ire;
13746 	ill_t		*ire_ill;
13747 	uint_t		ifindex;
13748 	ip_stack_t	*ipst = ill->ill_ipst;
13749 	boolean_t	strict_check = B_FALSE;
13750 
13751 	/*
13752 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13753 	 * issue (e.g. packet received on an underlying interface matched an
13754 	 * IRE_LOCAL on its associated group interface).
13755 	 */
13756 	if (ire->ire_rfq != NULL &&
13757 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13758 		return (ire);
13759 	}
13760 
13761 	/*
13762 	 * Do another ire lookup here, using the ingress ill, to see if the
13763 	 * interface is in a usesrc group.
13764 	 * As long as the ills belong to the same group, we don't consider
13765 	 * them to be arriving on the wrong interface. Thus, if the switch
13766 	 * is doing inbound load spreading, we won't drop packets when the
13767 	 * ip*_strict_dst_multihoming switch is on.
13768 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13769 	 * where the local address may not be unique. In this case we were
13770 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13771 	 * actually returned. The new lookup, which is more specific, should
13772 	 * only find the IRE_LOCAL associated with the ingress ill if one
13773 	 * exists.
13774 	 */
13775 
13776 	if (ire->ire_ipversion == IPV4_VERSION) {
13777 		if (ipst->ips_ip_strict_dst_multihoming)
13778 			strict_check = B_TRUE;
13779 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13780 		    ill->ill_ipif, ALL_ZONES, NULL,
13781 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13782 	} else {
13783 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13784 		if (ipst->ips_ipv6_strict_dst_multihoming)
13785 			strict_check = B_TRUE;
13786 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13787 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13788 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13789 	}
13790 	/*
13791 	 * If the same ire that was returned in ip_input() is found then this
13792 	 * is an indication that usesrc groups are in use. The packet
13793 	 * arrived on a different ill in the group than the one associated with
13794 	 * the destination address.  If a different ire was found then the same
13795 	 * IP address must be hosted on multiple ills. This is possible with
13796 	 * unnumbered point2point interfaces. We switch to use this new ire in
13797 	 * order to have accurate interface statistics.
13798 	 */
13799 	if (new_ire != NULL) {
13800 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13801 			ire_refrele(ire);
13802 			ire = new_ire;
13803 		} else {
13804 			ire_refrele(new_ire);
13805 		}
13806 		return (ire);
13807 	} else if ((ire->ire_rfq == NULL) &&
13808 	    (ire->ire_ipversion == IPV4_VERSION)) {
13809 		/*
13810 		 * The best match could have been the original ire which
13811 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13812 		 * the strict multihoming checks are irrelevant as we consider
13813 		 * local addresses hosted on lo0 to be interface agnostic. We
13814 		 * only expect a null ire_rfq on IREs which are associated with
13815 		 * lo0 hence we can return now.
13816 		 */
13817 		return (ire);
13818 	}
13819 
13820 	/*
13821 	 * Chase pointers once and store locally.
13822 	 */
13823 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13824 	    (ill_t *)(ire->ire_rfq->q_ptr);
13825 	ifindex = ill->ill_usesrc_ifindex;
13826 
13827 	/*
13828 	 * Check if it's a legal address on the 'usesrc' interface.
13829 	 */
13830 	if ((ifindex != 0) && (ire_ill != NULL) &&
13831 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13832 		return (ire);
13833 	}
13834 
13835 	/*
13836 	 * If the ip*_strict_dst_multihoming switch is on then we can
13837 	 * only accept this packet if the interface is marked as routing.
13838 	 */
13839 	if (!(strict_check))
13840 		return (ire);
13841 
13842 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13843 	    ILLF_ROUTER) != 0) {
13844 		return (ire);
13845 	}
13846 
13847 	ire_refrele(ire);
13848 	return (NULL);
13849 }
13850 
13851 /*
13852  *
13853  * This is the fast forward path. If we are here, we dont need to
13854  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13855  * needed to find the nexthop in this case is much simpler
13856  */
13857 ire_t *
13858 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13859 {
13860 	ipha_t	*ipha;
13861 	ire_t	*src_ire;
13862 	ill_t	*stq_ill;
13863 	uint_t	hlen;
13864 	uint_t	pkt_len;
13865 	uint32_t sum;
13866 	queue_t	*dev_q;
13867 	ip_stack_t *ipst = ill->ill_ipst;
13868 	mblk_t *fpmp;
13869 	enum	ire_forward_action ret_action;
13870 
13871 	ipha = (ipha_t *)mp->b_rptr;
13872 
13873 	if (ire != NULL &&
13874 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13875 	    ire->ire_zoneid != ALL_ZONES) {
13876 		/*
13877 		 * Should only use IREs that are visible to the global
13878 		 * zone for forwarding.
13879 		 */
13880 		ire_refrele(ire);
13881 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13882 		/*
13883 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13884 		 * transient cases. In such case, just drop the packet
13885 		 */
13886 		if (ire->ire_type != IRE_CACHE)
13887 			goto drop;
13888 	}
13889 
13890 	/*
13891 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13892 	 * The loopback address check for both src and dst has already
13893 	 * been checked in ip_input
13894 	 */
13895 
13896 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13897 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13898 		goto drop;
13899 	}
13900 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13901 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13902 
13903 	if (src_ire != NULL) {
13904 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13905 		ire_refrele(src_ire);
13906 		goto drop;
13907 	}
13908 
13909 	/* No ire cache of nexthop. So first create one  */
13910 	if (ire == NULL) {
13911 
13912 		ire = ire_forward_simple(dst, &ret_action, ipst);
13913 
13914 		/*
13915 		 * We only come to ip_fast_forward if ip_cgtp_filter
13916 		 * is not set. So ire_forward() should not return with
13917 		 * Forward_check_multirt as the next action.
13918 		 */
13919 		ASSERT(ret_action != Forward_check_multirt);
13920 		if (ire == NULL) {
13921 			/* An attempt was made to forward the packet */
13922 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13923 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13924 			mp->b_prev = mp->b_next = 0;
13925 			/* send icmp unreachable */
13926 			/* Sent by forwarding path, and router is global zone */
13927 			if (ret_action == Forward_ret_icmp_err) {
13928 				if (ip_source_routed(ipha, ipst)) {
13929 					icmp_unreachable(ill->ill_wq, mp,
13930 					    ICMP_SOURCE_ROUTE_FAILED,
13931 					    GLOBAL_ZONEID, ipst);
13932 				} else {
13933 					icmp_unreachable(ill->ill_wq, mp,
13934 					    ICMP_HOST_UNREACHABLE,
13935 					    GLOBAL_ZONEID, ipst);
13936 				}
13937 			} else {
13938 				freemsg(mp);
13939 			}
13940 			return (NULL);
13941 		}
13942 	}
13943 
13944 	/*
13945 	 * Forwarding fastpath exception case:
13946 	 * If any of the following are true, we take the slowpath:
13947 	 *	o forwarding is not enabled
13948 	 *	o incoming and outgoing interface are the same, or in the same
13949 	 *	  IPMP group.
13950 	 *	o corresponding ire is in incomplete state
13951 	 *	o packet needs fragmentation
13952 	 *	o ARP cache is not resolved
13953 	 *
13954 	 * The codeflow from here on is thus:
13955 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13956 	 */
13957 	pkt_len = ntohs(ipha->ipha_length);
13958 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13959 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13960 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13961 	    (ire->ire_nce == NULL) ||
13962 	    (pkt_len > ire->ire_max_frag) ||
13963 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13964 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13965 	    ipha->ipha_ttl <= 1) {
13966 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13967 		    ipha, ill, B_FALSE, B_TRUE);
13968 		return (ire);
13969 	}
13970 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13971 
13972 	DTRACE_PROBE4(ip4__forwarding__start,
13973 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13974 
13975 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13976 	    ipst->ips_ipv4firewall_forwarding,
13977 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13978 
13979 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13980 
13981 	if (mp == NULL)
13982 		goto drop;
13983 
13984 	mp->b_datap->db_struioun.cksum.flags = 0;
13985 	/* Adjust the checksum to reflect the ttl decrement. */
13986 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13987 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13988 	ipha->ipha_ttl--;
13989 
13990 	/*
13991 	 * Write the link layer header.  We can do this safely here,
13992 	 * because we have already tested to make sure that the IP
13993 	 * policy is not set, and that we have a fast path destination
13994 	 * header.
13995 	 */
13996 	mp->b_rptr -= hlen;
13997 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13998 
13999 	UPDATE_IB_PKT_COUNT(ire);
14000 	ire->ire_last_used_time = lbolt;
14001 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14002 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14003 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14004 
14005 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14006 		dev_q = ire->ire_stq->q_next;
14007 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14008 			goto indiscard;
14009 	}
14010 
14011 	DTRACE_PROBE4(ip4__physical__out__start,
14012 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14013 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14014 	    ipst->ips_ipv4firewall_physical_out,
14015 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14016 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14017 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14018 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14019 	    ip6_t *, NULL, int, 0);
14020 
14021 	if (mp != NULL) {
14022 		if (ipst->ips_ipobs_enabled) {
14023 			zoneid_t szone;
14024 
14025 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14026 			    ipst, ALL_ZONES);
14027 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14028 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14029 		}
14030 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14031 	}
14032 	return (ire);
14033 
14034 indiscard:
14035 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14036 drop:
14037 	if (mp != NULL)
14038 		freemsg(mp);
14039 	return (ire);
14040 
14041 }
14042 
14043 /*
14044  * This function is called in the forwarding slowpath, when
14045  * either the ire lacks the link-layer address, or the packet needs
14046  * further processing(eg. fragmentation), before transmission.
14047  */
14048 
14049 static void
14050 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14051     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14052 {
14053 	queue_t		*dev_q;
14054 	ire_t		*src_ire;
14055 	ip_stack_t	*ipst = ill->ill_ipst;
14056 	boolean_t	same_illgrp = B_FALSE;
14057 
14058 	ASSERT(ire->ire_stq != NULL);
14059 
14060 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14061 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14062 
14063 	/*
14064 	 * If the caller of this function is ip_fast_forward() skip the
14065 	 * next three checks as it does not apply.
14066 	 */
14067 	if (from_ip_fast_forward)
14068 		goto skip;
14069 
14070 	if (ll_multicast != 0) {
14071 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14072 		goto drop_pkt;
14073 	}
14074 
14075 	/*
14076 	 * check if ipha_src is a broadcast address. Note that this
14077 	 * check is redundant when we get here from ip_fast_forward()
14078 	 * which has already done this check. However, since we can
14079 	 * also get here from ip_rput_process_broadcast() or, for
14080 	 * for the slow path through ip_fast_forward(), we perform
14081 	 * the check again for code-reusability
14082 	 */
14083 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14084 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14085 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14086 		if (src_ire != NULL)
14087 			ire_refrele(src_ire);
14088 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14089 		ip2dbg(("ip_rput_process_forward: Received packet with"
14090 		    " bad src/dst address on %s\n", ill->ill_name));
14091 		goto drop_pkt;
14092 	}
14093 
14094 	/*
14095 	 * Check if we want to forward this one at this time.
14096 	 * We allow source routed packets on a host provided that
14097 	 * they go out the same ill or illgrp as they came in on.
14098 	 *
14099 	 * XXX To be quicker, we may wish to not chase pointers to
14100 	 * get the ILLF_ROUTER flag and instead store the
14101 	 * forwarding policy in the ire.  An unfortunate
14102 	 * side-effect of that would be requiring an ire flush
14103 	 * whenever the ILLF_ROUTER flag changes.
14104 	 */
14105 skip:
14106 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14107 
14108 	if (((ill->ill_flags &
14109 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14110 	    !(ip_source_routed(ipha, ipst) &&
14111 	    (ire->ire_rfq == q || same_illgrp))) {
14112 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14113 		if (ip_source_routed(ipha, ipst)) {
14114 			q = WR(q);
14115 			/*
14116 			 * Clear the indication that this may have
14117 			 * hardware checksum as we are not using it.
14118 			 */
14119 			DB_CKSUMFLAGS(mp) = 0;
14120 			/* Sent by forwarding path, and router is global zone */
14121 			icmp_unreachable(q, mp,
14122 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14123 			return;
14124 		}
14125 		goto drop_pkt;
14126 	}
14127 
14128 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14129 
14130 	/* Packet is being forwarded. Turning off hwcksum flag. */
14131 	DB_CKSUMFLAGS(mp) = 0;
14132 	if (ipst->ips_ip_g_send_redirects) {
14133 		/*
14134 		 * Check whether the incoming interface and outgoing
14135 		 * interface is part of the same group. If so,
14136 		 * send redirects.
14137 		 *
14138 		 * Check the source address to see if it originated
14139 		 * on the same logical subnet it is going back out on.
14140 		 * If so, we should be able to send it a redirect.
14141 		 * Avoid sending a redirect if the destination
14142 		 * is directly connected (i.e., ipha_dst is the same
14143 		 * as ire_gateway_addr or the ire_addr of the
14144 		 * nexthop IRE_CACHE ), or if the packet was source
14145 		 * routed out this interface.
14146 		 */
14147 		ipaddr_t src, nhop;
14148 		mblk_t	*mp1;
14149 		ire_t	*nhop_ire = NULL;
14150 
14151 		/*
14152 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14153 		 * If so, send redirects.
14154 		 */
14155 		if ((ire->ire_rfq == q || same_illgrp) &&
14156 		    !ip_source_routed(ipha, ipst)) {
14157 
14158 			nhop = (ire->ire_gateway_addr != 0 ?
14159 			    ire->ire_gateway_addr : ire->ire_addr);
14160 
14161 			if (ipha->ipha_dst == nhop) {
14162 				/*
14163 				 * We avoid sending a redirect if the
14164 				 * destination is directly connected
14165 				 * because it is possible that multiple
14166 				 * IP subnets may have been configured on
14167 				 * the link, and the source may not
14168 				 * be on the same subnet as ip destination,
14169 				 * even though they are on the same
14170 				 * physical link.
14171 				 */
14172 				goto sendit;
14173 			}
14174 
14175 			src = ipha->ipha_src;
14176 
14177 			/*
14178 			 * We look up the interface ire for the nexthop,
14179 			 * to see if ipha_src is in the same subnet
14180 			 * as the nexthop.
14181 			 *
14182 			 * Note that, if, in the future, IRE_CACHE entries
14183 			 * are obsoleted,  this lookup will not be needed,
14184 			 * as the ire passed to this function will be the
14185 			 * same as the nhop_ire computed below.
14186 			 */
14187 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14188 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14189 			    0, NULL, MATCH_IRE_TYPE, ipst);
14190 
14191 			if (nhop_ire != NULL) {
14192 				if ((src & nhop_ire->ire_mask) ==
14193 				    (nhop & nhop_ire->ire_mask)) {
14194 					/*
14195 					 * The source is directly connected.
14196 					 * Just copy the ip header (which is
14197 					 * in the first mblk)
14198 					 */
14199 					mp1 = copyb(mp);
14200 					if (mp1 != NULL) {
14201 						icmp_send_redirect(WR(q), mp1,
14202 						    nhop, ipst);
14203 					}
14204 				}
14205 				ire_refrele(nhop_ire);
14206 			}
14207 		}
14208 	}
14209 sendit:
14210 	dev_q = ire->ire_stq->q_next;
14211 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14212 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14213 		freemsg(mp);
14214 		return;
14215 	}
14216 
14217 	ip_rput_forward(ire, ipha, mp, ill);
14218 	return;
14219 
14220 drop_pkt:
14221 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14222 	freemsg(mp);
14223 }
14224 
14225 ire_t *
14226 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14227     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14228 {
14229 	queue_t		*q;
14230 	uint16_t	hcksumflags;
14231 	ip_stack_t	*ipst = ill->ill_ipst;
14232 
14233 	q = *qp;
14234 
14235 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14236 
14237 	/*
14238 	 * Clear the indication that this may have hardware
14239 	 * checksum as we are not using it for forwarding.
14240 	 */
14241 	hcksumflags = DB_CKSUMFLAGS(mp);
14242 	DB_CKSUMFLAGS(mp) = 0;
14243 
14244 	/*
14245 	 * Directed broadcast forwarding: if the packet came in over a
14246 	 * different interface then it is routed out over we can forward it.
14247 	 */
14248 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14249 		ire_refrele(ire);
14250 		freemsg(mp);
14251 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14252 		return (NULL);
14253 	}
14254 	/*
14255 	 * For multicast we have set dst to be INADDR_BROADCAST
14256 	 * for delivering to all STREAMS.
14257 	 */
14258 	if (!CLASSD(ipha->ipha_dst)) {
14259 		ire_t *new_ire;
14260 		ipif_t *ipif;
14261 
14262 		ipif = ipif_get_next_ipif(NULL, ill);
14263 		if (ipif == NULL) {
14264 discard:		ire_refrele(ire);
14265 			freemsg(mp);
14266 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14267 			return (NULL);
14268 		}
14269 		new_ire = ire_ctable_lookup(dst, 0, 0,
14270 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14271 		ipif_refrele(ipif);
14272 
14273 		if (new_ire != NULL) {
14274 			/*
14275 			 * If the matching IRE_BROADCAST is part of an IPMP
14276 			 * group, then drop the packet unless our ill has been
14277 			 * nominated to receive for the group.
14278 			 */
14279 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14280 			    new_ire->ire_rfq != q) {
14281 				ire_refrele(new_ire);
14282 				goto discard;
14283 			}
14284 
14285 			/*
14286 			 * In the special case of multirouted broadcast
14287 			 * packets, we unconditionally need to "gateway"
14288 			 * them to the appropriate interface here.
14289 			 * In the normal case, this cannot happen, because
14290 			 * there is no broadcast IRE tagged with the
14291 			 * RTF_MULTIRT flag.
14292 			 */
14293 			if (new_ire->ire_flags & RTF_MULTIRT) {
14294 				ire_refrele(new_ire);
14295 				if (ire->ire_rfq != NULL) {
14296 					q = ire->ire_rfq;
14297 					*qp = q;
14298 				}
14299 			} else {
14300 				ire_refrele(ire);
14301 				ire = new_ire;
14302 			}
14303 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14304 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14305 				/*
14306 				 * Free the message if
14307 				 * ip_g_forward_directed_bcast is turned
14308 				 * off for non-local broadcast.
14309 				 */
14310 				ire_refrele(ire);
14311 				freemsg(mp);
14312 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14313 				return (NULL);
14314 			}
14315 		} else {
14316 			/*
14317 			 * This CGTP packet successfully passed the
14318 			 * CGTP filter, but the related CGTP
14319 			 * broadcast IRE has not been found,
14320 			 * meaning that the redundant ipif is
14321 			 * probably down. However, if we discarded
14322 			 * this packet, its duplicate would be
14323 			 * filtered out by the CGTP filter so none
14324 			 * of them would get through. So we keep
14325 			 * going with this one.
14326 			 */
14327 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14328 			if (ire->ire_rfq != NULL) {
14329 				q = ire->ire_rfq;
14330 				*qp = q;
14331 			}
14332 		}
14333 	}
14334 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14335 		/*
14336 		 * Verify that there are not more then one
14337 		 * IRE_BROADCAST with this broadcast address which
14338 		 * has ire_stq set.
14339 		 * TODO: simplify, loop over all IRE's
14340 		 */
14341 		ire_t	*ire1;
14342 		int	num_stq = 0;
14343 		mblk_t	*mp1;
14344 
14345 		/* Find the first one with ire_stq set */
14346 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14347 		for (ire1 = ire; ire1 &&
14348 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14349 		    ire1 = ire1->ire_next)
14350 			;
14351 		if (ire1) {
14352 			ire_refrele(ire);
14353 			ire = ire1;
14354 			IRE_REFHOLD(ire);
14355 		}
14356 
14357 		/* Check if there are additional ones with stq set */
14358 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14359 			if (ire->ire_addr != ire1->ire_addr)
14360 				break;
14361 			if (ire1->ire_stq) {
14362 				num_stq++;
14363 				break;
14364 			}
14365 		}
14366 		rw_exit(&ire->ire_bucket->irb_lock);
14367 		if (num_stq == 1 && ire->ire_stq != NULL) {
14368 			ip1dbg(("ip_rput_process_broadcast: directed "
14369 			    "broadcast to 0x%x\n",
14370 			    ntohl(ire->ire_addr)));
14371 			mp1 = copymsg(mp);
14372 			if (mp1) {
14373 				switch (ipha->ipha_protocol) {
14374 				case IPPROTO_UDP:
14375 					ip_udp_input(q, mp1, ipha, ire, ill);
14376 					break;
14377 				default:
14378 					ip_proto_input(q, mp1, ipha, ire, ill,
14379 					    0);
14380 					break;
14381 				}
14382 			}
14383 			/*
14384 			 * Adjust ttl to 2 (1+1 - the forward engine
14385 			 * will decrement it by one.
14386 			 */
14387 			if (ip_csum_hdr(ipha)) {
14388 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14389 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14390 				freemsg(mp);
14391 				ire_refrele(ire);
14392 				return (NULL);
14393 			}
14394 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14395 			ipha->ipha_hdr_checksum = 0;
14396 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14397 			ip_rput_process_forward(q, mp, ire, ipha,
14398 			    ill, ll_multicast, B_FALSE);
14399 			ire_refrele(ire);
14400 			return (NULL);
14401 		}
14402 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14403 		    ntohl(ire->ire_addr)));
14404 	}
14405 
14406 	/* Restore any hardware checksum flags */
14407 	DB_CKSUMFLAGS(mp) = hcksumflags;
14408 	return (ire);
14409 }
14410 
14411 /* ARGSUSED */
14412 static boolean_t
14413 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14414     int *ll_multicast, ipaddr_t *dstp)
14415 {
14416 	ip_stack_t	*ipst = ill->ill_ipst;
14417 
14418 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14419 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14420 	    ntohs(ipha->ipha_length));
14421 
14422 	/*
14423 	 * So that we don't end up with dups, only one ill in an IPMP group is
14424 	 * nominated to receive multicast traffic.
14425 	 */
14426 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14427 		goto drop_pkt;
14428 
14429 	/*
14430 	 * Forward packets only if we have joined the allmulti
14431 	 * group on this interface.
14432 	 */
14433 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14434 		int retval;
14435 
14436 		/*
14437 		 * Clear the indication that this may have hardware
14438 		 * checksum as we are not using it.
14439 		 */
14440 		DB_CKSUMFLAGS(mp) = 0;
14441 		retval = ip_mforward(ill, ipha, mp);
14442 		/* ip_mforward updates mib variables if needed */
14443 		/* clear b_prev - used by ip_mroute_decap */
14444 		mp->b_prev = NULL;
14445 
14446 		switch (retval) {
14447 		case 0:
14448 			/*
14449 			 * pkt is okay and arrived on phyint.
14450 			 *
14451 			 * If we are running as a multicast router
14452 			 * we need to see all IGMP and/or PIM packets.
14453 			 */
14454 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14455 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14456 				goto done;
14457 			}
14458 			break;
14459 		case -1:
14460 			/* pkt is mal-formed, toss it */
14461 			goto drop_pkt;
14462 		case 1:
14463 			/* pkt is okay and arrived on a tunnel */
14464 			/*
14465 			 * If we are running a multicast router
14466 			 *  we need to see all igmp packets.
14467 			 */
14468 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14469 				*dstp = INADDR_BROADCAST;
14470 				*ll_multicast = 1;
14471 				return (B_FALSE);
14472 			}
14473 
14474 			goto drop_pkt;
14475 		}
14476 	}
14477 
14478 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14479 		/*
14480 		 * This might just be caused by the fact that
14481 		 * multiple IP Multicast addresses map to the same
14482 		 * link layer multicast - no need to increment counter!
14483 		 */
14484 		freemsg(mp);
14485 		return (B_TRUE);
14486 	}
14487 done:
14488 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14489 	/*
14490 	 * This assumes the we deliver to all streams for multicast
14491 	 * and broadcast packets.
14492 	 */
14493 	*dstp = INADDR_BROADCAST;
14494 	*ll_multicast = 1;
14495 	return (B_FALSE);
14496 drop_pkt:
14497 	ip2dbg(("ip_rput: drop pkt\n"));
14498 	freemsg(mp);
14499 	return (B_TRUE);
14500 }
14501 
14502 /*
14503  * This function is used to both return an indication of whether or not
14504  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14505  * and in doing so, determine whether or not it is broadcast vs multicast.
14506  * For it to be a broadcast packet, we must have the appropriate mblk_t
14507  * hanging off the ill_t.  If this is either not present or doesn't match
14508  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14509  * to be multicast.  Thus NICs that have no broadcast address (or no
14510  * capability for one, such as point to point links) cannot return as
14511  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14512  * the return values simplifies the current use of the return value of this
14513  * function, which is to pass through the multicast/broadcast characteristic
14514  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14515  * changing the return value to some other symbol demands the appropriate
14516  * "translation" when hpe_flags is set prior to calling hook_run() for
14517  * packet events.
14518  */
14519 int
14520 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14521 {
14522 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14523 	mblk_t *bmp;
14524 
14525 	if (ind->dl_group_address) {
14526 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14527 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14528 		    MBLKL(mb) &&
14529 		    (bmp = ill->ill_bcast_mp) != NULL) {
14530 			dl_unitdata_req_t *dlur;
14531 			uint8_t *bphys_addr;
14532 
14533 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14534 			if (ill->ill_sap_length < 0)
14535 				bphys_addr = (uchar_t *)dlur +
14536 				    dlur->dl_dest_addr_offset;
14537 			else
14538 				bphys_addr = (uchar_t *)dlur +
14539 				    dlur->dl_dest_addr_offset +
14540 				    ill->ill_sap_length;
14541 
14542 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14543 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14544 				return (HPE_BROADCAST);
14545 			}
14546 			return (HPE_MULTICAST);
14547 		}
14548 		return (HPE_MULTICAST);
14549 	}
14550 	return (0);
14551 }
14552 
14553 static boolean_t
14554 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14555     int *ll_multicast, mblk_t **mpp)
14556 {
14557 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14558 	boolean_t must_copy = B_FALSE;
14559 	struct iocblk   *iocp;
14560 	ipha_t		*ipha;
14561 	ip_stack_t	*ipst = ill->ill_ipst;
14562 
14563 #define	rptr    ((uchar_t *)ipha)
14564 
14565 	first_mp = *first_mpp;
14566 	mp = *mpp;
14567 
14568 	ASSERT(first_mp == mp);
14569 
14570 	/*
14571 	 * if db_ref > 1 then copymsg and free original. Packet may be
14572 	 * changed and do not want other entity who has a reference to this
14573 	 * message to trip over the changes. This is a blind change because
14574 	 * trying to catch all places that might change packet is too
14575 	 * difficult (since it may be a module above this one)
14576 	 *
14577 	 * This corresponds to the non-fast path case. We walk down the full
14578 	 * chain in this case, and check the db_ref count of all the dblks,
14579 	 * and do a copymsg if required. It is possible that the db_ref counts
14580 	 * of the data blocks in the mblk chain can be different.
14581 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14582 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14583 	 * 'snoop' is running.
14584 	 */
14585 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14586 		if (mp1->b_datap->db_ref > 1) {
14587 			must_copy = B_TRUE;
14588 			break;
14589 		}
14590 	}
14591 
14592 	if (must_copy) {
14593 		mp1 = copymsg(mp);
14594 		if (mp1 == NULL) {
14595 			for (mp1 = mp; mp1 != NULL;
14596 			    mp1 = mp1->b_cont) {
14597 				mp1->b_next = NULL;
14598 				mp1->b_prev = NULL;
14599 			}
14600 			freemsg(mp);
14601 			if (ill != NULL) {
14602 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14603 			} else {
14604 				BUMP_MIB(&ipst->ips_ip_mib,
14605 				    ipIfStatsInDiscards);
14606 			}
14607 			return (B_TRUE);
14608 		}
14609 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14610 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14611 			/* Copy b_prev - used by ip_mroute_decap */
14612 			to_mp->b_prev = from_mp->b_prev;
14613 			from_mp->b_prev = NULL;
14614 		}
14615 		*first_mpp = first_mp = mp1;
14616 		freemsg(mp);
14617 		mp = mp1;
14618 		*mpp = mp1;
14619 	}
14620 
14621 	ipha = (ipha_t *)mp->b_rptr;
14622 
14623 	/*
14624 	 * previous code has a case for M_DATA.
14625 	 * We want to check how that happens.
14626 	 */
14627 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14628 	switch (first_mp->b_datap->db_type) {
14629 	case M_PROTO:
14630 	case M_PCPROTO:
14631 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14632 		    DL_UNITDATA_IND) {
14633 			/* Go handle anything other than data elsewhere. */
14634 			ip_rput_dlpi(q, mp);
14635 			return (B_TRUE);
14636 		}
14637 
14638 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14639 		/* Ditch the DLPI header. */
14640 		mp1 = mp->b_cont;
14641 		ASSERT(first_mp == mp);
14642 		*first_mpp = mp1;
14643 		freeb(mp);
14644 		*mpp = mp1;
14645 		return (B_FALSE);
14646 	case M_IOCACK:
14647 		ip1dbg(("got iocack "));
14648 		iocp = (struct iocblk *)mp->b_rptr;
14649 		switch (iocp->ioc_cmd) {
14650 		case DL_IOC_HDR_INFO:
14651 			ill = (ill_t *)q->q_ptr;
14652 			ill_fastpath_ack(ill, mp);
14653 			return (B_TRUE);
14654 		case SIOCSTUNPARAM:
14655 		case OSIOCSTUNPARAM:
14656 			/* Go through qwriter_ip */
14657 			break;
14658 		case SIOCGTUNPARAM:
14659 		case OSIOCGTUNPARAM:
14660 			ip_rput_other(NULL, q, mp, NULL);
14661 			return (B_TRUE);
14662 		default:
14663 			putnext(q, mp);
14664 			return (B_TRUE);
14665 		}
14666 		/* FALLTHRU */
14667 	case M_ERROR:
14668 	case M_HANGUP:
14669 		/*
14670 		 * Since this is on the ill stream we unconditionally
14671 		 * bump up the refcount
14672 		 */
14673 		ill_refhold(ill);
14674 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14675 		return (B_TRUE);
14676 	case M_CTL:
14677 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14678 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14679 		    IPHADA_M_CTL)) {
14680 			/*
14681 			 * It's an IPsec accelerated packet.
14682 			 * Make sure that the ill from which we received the
14683 			 * packet has enabled IPsec hardware acceleration.
14684 			 */
14685 			if (!(ill->ill_capabilities &
14686 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14687 				/* IPsec kstats: bean counter */
14688 				freemsg(mp);
14689 				return (B_TRUE);
14690 			}
14691 
14692 			/*
14693 			 * Make mp point to the mblk following the M_CTL,
14694 			 * then process according to type of mp.
14695 			 * After this processing, first_mp will point to
14696 			 * the data-attributes and mp to the pkt following
14697 			 * the M_CTL.
14698 			 */
14699 			mp = first_mp->b_cont;
14700 			if (mp == NULL) {
14701 				freemsg(first_mp);
14702 				return (B_TRUE);
14703 			}
14704 			/*
14705 			 * A Hardware Accelerated packet can only be M_DATA
14706 			 * ESP or AH packet.
14707 			 */
14708 			if (mp->b_datap->db_type != M_DATA) {
14709 				/* non-M_DATA IPsec accelerated packet */
14710 				IPSECHW_DEBUG(IPSECHW_PKT,
14711 				    ("non-M_DATA IPsec accelerated pkt\n"));
14712 				freemsg(first_mp);
14713 				return (B_TRUE);
14714 			}
14715 			ipha = (ipha_t *)mp->b_rptr;
14716 			if (ipha->ipha_protocol != IPPROTO_AH &&
14717 			    ipha->ipha_protocol != IPPROTO_ESP) {
14718 				IPSECHW_DEBUG(IPSECHW_PKT,
14719 				    ("non-M_DATA IPsec accelerated pkt\n"));
14720 				freemsg(first_mp);
14721 				return (B_TRUE);
14722 			}
14723 			*mpp = mp;
14724 			return (B_FALSE);
14725 		}
14726 		putnext(q, mp);
14727 		return (B_TRUE);
14728 	case M_IOCNAK:
14729 		ip1dbg(("got iocnak "));
14730 		iocp = (struct iocblk *)mp->b_rptr;
14731 		switch (iocp->ioc_cmd) {
14732 		case SIOCSTUNPARAM:
14733 		case OSIOCSTUNPARAM:
14734 			/*
14735 			 * Since this is on the ill stream we unconditionally
14736 			 * bump up the refcount
14737 			 */
14738 			ill_refhold(ill);
14739 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14740 			return (B_TRUE);
14741 		case DL_IOC_HDR_INFO:
14742 		case SIOCGTUNPARAM:
14743 		case OSIOCGTUNPARAM:
14744 			ip_rput_other(NULL, q, mp, NULL);
14745 			return (B_TRUE);
14746 		default:
14747 			break;
14748 		}
14749 		/* FALLTHRU */
14750 	default:
14751 		putnext(q, mp);
14752 		return (B_TRUE);
14753 	}
14754 }
14755 
14756 /* Read side put procedure.  Packets coming from the wire arrive here. */
14757 void
14758 ip_rput(queue_t *q, mblk_t *mp)
14759 {
14760 	ill_t	*ill;
14761 	union DL_primitives *dl;
14762 
14763 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14764 
14765 	ill = (ill_t *)q->q_ptr;
14766 
14767 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14768 		/*
14769 		 * If things are opening or closing, only accept high-priority
14770 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14771 		 * created; on close, things hanging off the ill may have been
14772 		 * freed already.)
14773 		 */
14774 		dl = (union DL_primitives *)mp->b_rptr;
14775 		if (DB_TYPE(mp) != M_PCPROTO ||
14776 		    dl->dl_primitive == DL_UNITDATA_IND) {
14777 			/*
14778 			 * SIOC[GS]TUNPARAM ioctls can come here.
14779 			 */
14780 			inet_freemsg(mp);
14781 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14782 			    "ip_rput_end: q %p (%S)", q, "uninit");
14783 			return;
14784 		}
14785 	}
14786 
14787 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14788 	    "ip_rput_end: q %p (%S)", q, "end");
14789 
14790 	ip_input(ill, NULL, mp, NULL);
14791 }
14792 
14793 static mblk_t *
14794 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14795 {
14796 	mblk_t *mp1;
14797 	boolean_t adjusted = B_FALSE;
14798 	ip_stack_t *ipst = ill->ill_ipst;
14799 
14800 	IP_STAT(ipst, ip_db_ref);
14801 	/*
14802 	 * The IP_RECVSLLA option depends on having the
14803 	 * link layer header. First check that:
14804 	 * a> the underlying device is of type ether,
14805 	 * since this option is currently supported only
14806 	 * over ethernet.
14807 	 * b> there is enough room to copy over the link
14808 	 * layer header.
14809 	 *
14810 	 * Once the checks are done, adjust rptr so that
14811 	 * the link layer header will be copied via
14812 	 * copymsg. Note that, IFT_ETHER may be returned
14813 	 * by some non-ethernet drivers but in this case
14814 	 * the second check will fail.
14815 	 */
14816 	if (ill->ill_type == IFT_ETHER &&
14817 	    (mp->b_rptr - mp->b_datap->db_base) >=
14818 	    sizeof (struct ether_header)) {
14819 		mp->b_rptr -= sizeof (struct ether_header);
14820 		adjusted = B_TRUE;
14821 	}
14822 	mp1 = copymsg(mp);
14823 
14824 	if (mp1 == NULL) {
14825 		mp->b_next = NULL;
14826 		/* clear b_prev - used by ip_mroute_decap */
14827 		mp->b_prev = NULL;
14828 		freemsg(mp);
14829 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14830 		return (NULL);
14831 	}
14832 
14833 	if (adjusted) {
14834 		/*
14835 		 * Copy is done. Restore the pointer in
14836 		 * the _new_ mblk
14837 		 */
14838 		mp1->b_rptr += sizeof (struct ether_header);
14839 	}
14840 
14841 	/* Copy b_prev - used by ip_mroute_decap */
14842 	mp1->b_prev = mp->b_prev;
14843 	mp->b_prev = NULL;
14844 
14845 	/* preserve the hardware checksum flags and data, if present */
14846 	if (DB_CKSUMFLAGS(mp) != 0) {
14847 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14848 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14849 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14850 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14851 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14852 	}
14853 
14854 	freemsg(mp);
14855 	return (mp1);
14856 }
14857 
14858 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14859 	if (tail != NULL)					\
14860 		tail->b_next = mp;				\
14861 	else							\
14862 		head = mp;					\
14863 	tail = mp;						\
14864 	cnt++;							\
14865 }
14866 
14867 /*
14868  * Direct read side procedure capable of dealing with chains. GLDv3 based
14869  * drivers call this function directly with mblk chains while STREAMS
14870  * read side procedure ip_rput() calls this for single packet with ip_ring
14871  * set to NULL to process one packet at a time.
14872  *
14873  * The ill will always be valid if this function is called directly from
14874  * the driver.
14875  *
14876  * If ip_input() is called from GLDv3:
14877  *
14878  *   - This must be a non-VLAN IP stream.
14879  *   - 'mp' is either an untagged or a special priority-tagged packet.
14880  *   - Any VLAN tag that was in the MAC header has been stripped.
14881  *
14882  * If the IP header in packet is not 32-bit aligned, every message in the
14883  * chain will be aligned before further operations. This is required on SPARC
14884  * platform.
14885  */
14886 /* ARGSUSED */
14887 void
14888 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14889     struct mac_header_info_s *mhip)
14890 {
14891 	ipaddr_t		dst = NULL;
14892 	ipaddr_t		prev_dst;
14893 	ire_t			*ire = NULL;
14894 	ipha_t			*ipha;
14895 	uint_t			pkt_len;
14896 	ssize_t			len;
14897 	uint_t			opt_len;
14898 	int			ll_multicast;
14899 	int			cgtp_flt_pkt;
14900 	queue_t			*q = ill->ill_rq;
14901 	squeue_t		*curr_sqp = NULL;
14902 	mblk_t 			*head = NULL;
14903 	mblk_t			*tail = NULL;
14904 	mblk_t			*first_mp;
14905 	int			cnt = 0;
14906 	ip_stack_t		*ipst = ill->ill_ipst;
14907 	mblk_t			*mp;
14908 	mblk_t			*dmp;
14909 	uint8_t			tag;
14910 
14911 	ASSERT(mp_chain != NULL);
14912 	ASSERT(ill != NULL);
14913 
14914 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14915 
14916 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14917 
14918 #define	rptr	((uchar_t *)ipha)
14919 
14920 	while (mp_chain != NULL) {
14921 		mp = mp_chain;
14922 		mp_chain = mp_chain->b_next;
14923 		mp->b_next = NULL;
14924 		ll_multicast = 0;
14925 
14926 		/*
14927 		 * We do ire caching from one iteration to
14928 		 * another. In the event the packet chain contains
14929 		 * all packets from the same dst, this caching saves
14930 		 * an ire_cache_lookup for each of the succeeding
14931 		 * packets in a packet chain.
14932 		 */
14933 		prev_dst = dst;
14934 
14935 		/*
14936 		 * if db_ref > 1 then copymsg and free original. Packet
14937 		 * may be changed and we do not want the other entity
14938 		 * who has a reference to this message to trip over the
14939 		 * changes. This is a blind change because trying to
14940 		 * catch all places that might change the packet is too
14941 		 * difficult.
14942 		 *
14943 		 * This corresponds to the fast path case, where we have
14944 		 * a chain of M_DATA mblks.  We check the db_ref count
14945 		 * of only the 1st data block in the mblk chain. There
14946 		 * doesn't seem to be a reason why a device driver would
14947 		 * send up data with varying db_ref counts in the mblk
14948 		 * chain. In any case the Fast path is a private
14949 		 * interface, and our drivers don't do such a thing.
14950 		 * Given the above assumption, there is no need to walk
14951 		 * down the entire mblk chain (which could have a
14952 		 * potential performance problem)
14953 		 *
14954 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14955 		 * to here because of exclusive ip stacks and vnics.
14956 		 * Packets transmitted from exclusive stack over vnic
14957 		 * can have db_ref > 1 and when it gets looped back to
14958 		 * another vnic in a different zone, you have ip_input()
14959 		 * getting dblks with db_ref > 1. So if someone
14960 		 * complains of TCP performance under this scenario,
14961 		 * take a serious look here on the impact of copymsg().
14962 		 */
14963 
14964 		if (DB_REF(mp) > 1) {
14965 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14966 				continue;
14967 		}
14968 
14969 		/*
14970 		 * Check and align the IP header.
14971 		 */
14972 		first_mp = mp;
14973 		if (DB_TYPE(mp) == M_DATA) {
14974 			dmp = mp;
14975 		} else if (DB_TYPE(mp) == M_PROTO &&
14976 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14977 			dmp = mp->b_cont;
14978 		} else {
14979 			dmp = NULL;
14980 		}
14981 		if (dmp != NULL) {
14982 			/*
14983 			 * IP header ptr not aligned?
14984 			 * OR IP header not complete in first mblk
14985 			 */
14986 			if (!OK_32PTR(dmp->b_rptr) ||
14987 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14988 				if (!ip_check_and_align_header(q, dmp, ipst))
14989 					continue;
14990 			}
14991 		}
14992 
14993 		/*
14994 		 * ip_input fast path
14995 		 */
14996 
14997 		/* mblk type is not M_DATA */
14998 		if (DB_TYPE(mp) != M_DATA) {
14999 			if (ip_rput_process_notdata(q, &first_mp, ill,
15000 			    &ll_multicast, &mp))
15001 				continue;
15002 
15003 			/*
15004 			 * The only way we can get here is if we had a
15005 			 * packet that was either a DL_UNITDATA_IND or
15006 			 * an M_CTL for an IPsec accelerated packet.
15007 			 *
15008 			 * In either case, the first_mp will point to
15009 			 * the leading M_PROTO or M_CTL.
15010 			 */
15011 			ASSERT(first_mp != NULL);
15012 		} else if (mhip != NULL) {
15013 			/*
15014 			 * ll_multicast is set here so that it is ready
15015 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15016 			 * manipulates ll_multicast in the same fashion when
15017 			 * called from ip_rput_process_notdata.
15018 			 */
15019 			switch (mhip->mhi_dsttype) {
15020 			case MAC_ADDRTYPE_MULTICAST :
15021 				ll_multicast = HPE_MULTICAST;
15022 				break;
15023 			case MAC_ADDRTYPE_BROADCAST :
15024 				ll_multicast = HPE_BROADCAST;
15025 				break;
15026 			default :
15027 				break;
15028 			}
15029 		}
15030 
15031 		/* Only M_DATA can come here and it is always aligned */
15032 		ASSERT(DB_TYPE(mp) == M_DATA);
15033 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15034 
15035 		ipha = (ipha_t *)mp->b_rptr;
15036 		len = mp->b_wptr - rptr;
15037 		pkt_len = ntohs(ipha->ipha_length);
15038 
15039 		/*
15040 		 * We must count all incoming packets, even if they end
15041 		 * up being dropped later on.
15042 		 */
15043 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15044 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15045 
15046 		/* multiple mblk or too short */
15047 		len -= pkt_len;
15048 		if (len != 0) {
15049 			/*
15050 			 * Make sure we have data length consistent
15051 			 * with the IP header.
15052 			 */
15053 			if (mp->b_cont == NULL) {
15054 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15055 					BUMP_MIB(ill->ill_ip_mib,
15056 					    ipIfStatsInHdrErrors);
15057 					ip2dbg(("ip_input: drop pkt\n"));
15058 					freemsg(mp);
15059 					continue;
15060 				}
15061 				mp->b_wptr = rptr + pkt_len;
15062 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15063 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15064 					BUMP_MIB(ill->ill_ip_mib,
15065 					    ipIfStatsInHdrErrors);
15066 					ip2dbg(("ip_input: drop pkt\n"));
15067 					freemsg(mp);
15068 					continue;
15069 				}
15070 				(void) adjmsg(mp, -len);
15071 				IP_STAT(ipst, ip_multimblk3);
15072 			}
15073 		}
15074 
15075 		/* Obtain the dst of the current packet */
15076 		dst = ipha->ipha_dst;
15077 
15078 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15079 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15080 		    ipha, ip6_t *, NULL, int, 0);
15081 
15082 		/*
15083 		 * The following test for loopback is faster than
15084 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15085 		 * operations.
15086 		 * Note that these addresses are always in network byte order
15087 		 */
15088 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15089 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15090 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15091 			freemsg(mp);
15092 			continue;
15093 		}
15094 
15095 		/*
15096 		 * The event for packets being received from a 'physical'
15097 		 * interface is placed after validation of the source and/or
15098 		 * destination address as being local so that packets can be
15099 		 * redirected to loopback addresses using ipnat.
15100 		 */
15101 		DTRACE_PROBE4(ip4__physical__in__start,
15102 		    ill_t *, ill, ill_t *, NULL,
15103 		    ipha_t *, ipha, mblk_t *, first_mp);
15104 
15105 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15106 		    ipst->ips_ipv4firewall_physical_in,
15107 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15108 
15109 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15110 
15111 		if (first_mp == NULL) {
15112 			continue;
15113 		}
15114 		dst = ipha->ipha_dst;
15115 		/*
15116 		 * Attach any necessary label information to
15117 		 * this packet
15118 		 */
15119 		if (is_system_labeled() &&
15120 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15121 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15122 			freemsg(mp);
15123 			continue;
15124 		}
15125 
15126 		if (ipst->ips_ipobs_enabled) {
15127 			zoneid_t dzone;
15128 
15129 			/*
15130 			 * On the inbound path the src zone will be unknown as
15131 			 * this packet has come from the wire.
15132 			 */
15133 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15134 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15135 			    ill, IPV4_VERSION, 0, ipst);
15136 		}
15137 
15138 		/*
15139 		 * Reuse the cached ire only if the ipha_dst of the previous
15140 		 * packet is the same as the current packet AND it is not
15141 		 * INADDR_ANY.
15142 		 */
15143 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15144 		    (ire != NULL)) {
15145 			ire_refrele(ire);
15146 			ire = NULL;
15147 		}
15148 
15149 		opt_len = ipha->ipha_version_and_hdr_length -
15150 		    IP_SIMPLE_HDR_VERSION;
15151 
15152 		/*
15153 		 * Check to see if we can take the fastpath.
15154 		 * That is possible if the following conditions are met
15155 		 *	o Tsol disabled
15156 		 *	o CGTP disabled
15157 		 *	o ipp_action_count is 0
15158 		 *	o no options in the packet
15159 		 *	o not a RSVP packet
15160 		 * 	o not a multicast packet
15161 		 *	o ill not in IP_DHCPINIT_IF mode
15162 		 */
15163 		if (!is_system_labeled() &&
15164 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15165 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15166 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15167 			if (ire == NULL)
15168 				ire = ire_cache_lookup_simple(dst, ipst);
15169 			/*
15170 			 * Unless forwarding is enabled, dont call
15171 			 * ip_fast_forward(). Incoming packet is for forwarding
15172 			 */
15173 			if ((ill->ill_flags & ILLF_ROUTER) &&
15174 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15175 				ire = ip_fast_forward(ire, dst, ill, mp);
15176 				continue;
15177 			}
15178 			/* incoming packet is for local consumption */
15179 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15180 				goto local;
15181 		}
15182 
15183 		/*
15184 		 * Disable ire caching for anything more complex
15185 		 * than the simple fast path case we checked for above.
15186 		 */
15187 		if (ire != NULL) {
15188 			ire_refrele(ire);
15189 			ire = NULL;
15190 		}
15191 
15192 		/*
15193 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15194 		 * server to unicast DHCP packets to a DHCP client using the
15195 		 * IP address it is offering to the client.  This can be
15196 		 * disabled through the "broadcast bit", but not all DHCP
15197 		 * servers honor that bit.  Therefore, to interoperate with as
15198 		 * many DHCP servers as possible, the DHCP client allows the
15199 		 * server to unicast, but we treat those packets as broadcast
15200 		 * here.  Note that we don't rewrite the packet itself since
15201 		 * (a) that would mess up the checksums and (b) the DHCP
15202 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15203 		 * hand it the packet regardless.
15204 		 */
15205 		if (ill->ill_dhcpinit != 0 &&
15206 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15207 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15208 			udpha_t *udpha;
15209 
15210 			/*
15211 			 * Reload ipha since pullupmsg() can change b_rptr.
15212 			 */
15213 			ipha = (ipha_t *)mp->b_rptr;
15214 			udpha = (udpha_t *)&ipha[1];
15215 
15216 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15217 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15218 				    mblk_t *, mp);
15219 				dst = INADDR_BROADCAST;
15220 			}
15221 		}
15222 
15223 		/* Full-blown slow path */
15224 		if (opt_len != 0) {
15225 			if (len != 0)
15226 				IP_STAT(ipst, ip_multimblk4);
15227 			else
15228 				IP_STAT(ipst, ip_ipoptions);
15229 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15230 			    &dst, ipst))
15231 				continue;
15232 		}
15233 
15234 		/*
15235 		 * Invoke the CGTP (multirouting) filtering module to process
15236 		 * the incoming packet. Packets identified as duplicates
15237 		 * must be discarded. Filtering is active only if the
15238 		 * the ip_cgtp_filter ndd variable is non-zero.
15239 		 */
15240 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15241 		if (ipst->ips_ip_cgtp_filter &&
15242 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15243 			netstackid_t stackid;
15244 
15245 			stackid = ipst->ips_netstack->netstack_stackid;
15246 			cgtp_flt_pkt =
15247 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15248 			    ill->ill_phyint->phyint_ifindex, mp);
15249 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15250 				freemsg(first_mp);
15251 				continue;
15252 			}
15253 		}
15254 
15255 		/*
15256 		 * If rsvpd is running, let RSVP daemon handle its processing
15257 		 * and forwarding of RSVP multicast/unicast packets.
15258 		 * If rsvpd is not running but mrouted is running, RSVP
15259 		 * multicast packets are forwarded as multicast traffic
15260 		 * and RSVP unicast packets are forwarded by unicast router.
15261 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15262 		 * packets are not forwarded, but the unicast packets are
15263 		 * forwarded like unicast traffic.
15264 		 */
15265 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15266 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15267 		    NULL) {
15268 			/* RSVP packet and rsvpd running. Treat as ours */
15269 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15270 			/*
15271 			 * This assumes that we deliver to all streams for
15272 			 * multicast and broadcast packets.
15273 			 * We have to force ll_multicast to 1 to handle the
15274 			 * M_DATA messages passed in from ip_mroute_decap.
15275 			 */
15276 			dst = INADDR_BROADCAST;
15277 			ll_multicast = 1;
15278 		} else if (CLASSD(dst)) {
15279 			/* packet is multicast */
15280 			mp->b_next = NULL;
15281 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15282 			    &ll_multicast, &dst))
15283 				continue;
15284 		}
15285 
15286 		if (ire == NULL) {
15287 			ire = ire_cache_lookup(dst, ALL_ZONES,
15288 			    msg_getlabel(mp), ipst);
15289 		}
15290 
15291 		if (ire != NULL && ire->ire_stq != NULL &&
15292 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15293 		    ire->ire_zoneid != ALL_ZONES) {
15294 			/*
15295 			 * Should only use IREs that are visible from the
15296 			 * global zone for forwarding.
15297 			 */
15298 			ire_refrele(ire);
15299 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15300 			    msg_getlabel(mp), ipst);
15301 		}
15302 
15303 		if (ire == NULL) {
15304 			/*
15305 			 * No IRE for this destination, so it can't be for us.
15306 			 * Unless we are forwarding, drop the packet.
15307 			 * We have to let source routed packets through
15308 			 * since we don't yet know if they are 'ping -l'
15309 			 * packets i.e. if they will go out over the
15310 			 * same interface as they came in on.
15311 			 */
15312 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15313 			if (ire == NULL)
15314 				continue;
15315 		}
15316 
15317 		/*
15318 		 * Broadcast IRE may indicate either broadcast or
15319 		 * multicast packet
15320 		 */
15321 		if (ire->ire_type == IRE_BROADCAST) {
15322 			/*
15323 			 * Skip broadcast checks if packet is UDP multicast;
15324 			 * we'd rather not enter ip_rput_process_broadcast()
15325 			 * unless the packet is broadcast for real, since
15326 			 * that routine is a no-op for multicast.
15327 			 */
15328 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15329 			    !CLASSD(ipha->ipha_dst)) {
15330 				ire = ip_rput_process_broadcast(&q, mp,
15331 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15332 				    ll_multicast);
15333 				if (ire == NULL)
15334 					continue;
15335 			}
15336 		} else if (ire->ire_stq != NULL) {
15337 			/* fowarding? */
15338 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15339 			    ll_multicast, B_FALSE);
15340 			/* ip_rput_process_forward consumed the packet */
15341 			continue;
15342 		}
15343 
15344 local:
15345 		/*
15346 		 * If the queue in the ire is different to the ingress queue
15347 		 * then we need to check to see if we can accept the packet.
15348 		 * Note that for multicast packets and broadcast packets sent
15349 		 * to a broadcast address which is shared between multiple
15350 		 * interfaces we should not do this since we just got a random
15351 		 * broadcast ire.
15352 		 */
15353 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15354 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15355 			if (ire == NULL) {
15356 				/* Drop packet */
15357 				BUMP_MIB(ill->ill_ip_mib,
15358 				    ipIfStatsForwProhibits);
15359 				freemsg(mp);
15360 				continue;
15361 			}
15362 			if (ire->ire_rfq != NULL)
15363 				q = ire->ire_rfq;
15364 		}
15365 
15366 		switch (ipha->ipha_protocol) {
15367 		case IPPROTO_TCP:
15368 			ASSERT(first_mp == mp);
15369 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15370 			    mp, 0, q, ip_ring)) != NULL) {
15371 				if (curr_sqp == NULL) {
15372 					curr_sqp = GET_SQUEUE(mp);
15373 					ASSERT(cnt == 0);
15374 					cnt++;
15375 					head = tail = mp;
15376 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15377 					ASSERT(tail != NULL);
15378 					cnt++;
15379 					tail->b_next = mp;
15380 					tail = mp;
15381 				} else {
15382 					/*
15383 					 * A different squeue. Send the
15384 					 * chain for the previous squeue on
15385 					 * its way. This shouldn't happen
15386 					 * often unless interrupt binding
15387 					 * changes.
15388 					 */
15389 					IP_STAT(ipst, ip_input_multi_squeue);
15390 					SQUEUE_ENTER(curr_sqp, head,
15391 					    tail, cnt, SQ_PROCESS, tag);
15392 					curr_sqp = GET_SQUEUE(mp);
15393 					head = mp;
15394 					tail = mp;
15395 					cnt = 1;
15396 				}
15397 			}
15398 			continue;
15399 		case IPPROTO_UDP:
15400 			ASSERT(first_mp == mp);
15401 			ip_udp_input(q, mp, ipha, ire, ill);
15402 			continue;
15403 		case IPPROTO_SCTP:
15404 			ASSERT(first_mp == mp);
15405 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15406 			    q, dst);
15407 			/* ire has been released by ip_sctp_input */
15408 			ire = NULL;
15409 			continue;
15410 		default:
15411 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15412 			continue;
15413 		}
15414 	}
15415 
15416 	if (ire != NULL)
15417 		ire_refrele(ire);
15418 
15419 	if (head != NULL)
15420 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15421 
15422 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15423 	    "ip_input_end: q %p (%S)", q, "end");
15424 #undef  rptr
15425 }
15426 
15427 /*
15428  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15429  * a chain of packets in the poll mode. The packets have gone through the
15430  * data link processing but not IP processing. For performance and latency
15431  * reasons, the squeue wants to process the chain in line instead of feeding
15432  * it back via ip_input path.
15433  *
15434  * So this is a light weight function which checks to see if the packets
15435  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15436  * but we still do the paranoid check) meant for local machine and we don't
15437  * have labels etc enabled. Packets that meet the criterion are returned to
15438  * the squeue and processed inline while the rest go via ip_input path.
15439  */
15440 /*ARGSUSED*/
15441 mblk_t *
15442 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15443     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15444 {
15445 	mblk_t 		*mp;
15446 	ipaddr_t	dst = NULL;
15447 	ipaddr_t	prev_dst;
15448 	ire_t		*ire = NULL;
15449 	ipha_t		*ipha;
15450 	uint_t		pkt_len;
15451 	ssize_t		len;
15452 	uint_t		opt_len;
15453 	queue_t		*q = ill->ill_rq;
15454 	squeue_t	*curr_sqp;
15455 	mblk_t 		*ahead = NULL;	/* Accepted head */
15456 	mblk_t		*atail = NULL;	/* Accepted tail */
15457 	uint_t		acnt = 0;	/* Accepted count */
15458 	mblk_t		*utail = NULL;	/* Unaccepted head */
15459 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15460 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15461 	ip_stack_t	*ipst = ill->ill_ipst;
15462 
15463 	*cnt = 0;
15464 
15465 	ASSERT(ill != NULL);
15466 	ASSERT(ip_ring != NULL);
15467 
15468 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15469 
15470 #define	rptr	((uchar_t *)ipha)
15471 
15472 	while (mp_chain != NULL) {
15473 		mp = mp_chain;
15474 		mp_chain = mp_chain->b_next;
15475 		mp->b_next = NULL;
15476 
15477 		/*
15478 		 * We do ire caching from one iteration to
15479 		 * another. In the event the packet chain contains
15480 		 * all packets from the same dst, this caching saves
15481 		 * an ire_cache_lookup for each of the succeeding
15482 		 * packets in a packet chain.
15483 		 */
15484 		prev_dst = dst;
15485 
15486 		ipha = (ipha_t *)mp->b_rptr;
15487 		len = mp->b_wptr - rptr;
15488 
15489 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15490 
15491 		/*
15492 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15493 		 * or doesn't have min len, reject.
15494 		 */
15495 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15496 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15497 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15498 			continue;
15499 		}
15500 
15501 		pkt_len = ntohs(ipha->ipha_length);
15502 		if (len != pkt_len) {
15503 			if (len > pkt_len) {
15504 				mp->b_wptr = rptr + pkt_len;
15505 			} else {
15506 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15507 				continue;
15508 			}
15509 		}
15510 
15511 		opt_len = ipha->ipha_version_and_hdr_length -
15512 		    IP_SIMPLE_HDR_VERSION;
15513 		dst = ipha->ipha_dst;
15514 
15515 		/* IP version bad or there are IP options */
15516 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15517 		    mp, &ipha, &dst, ipst)))
15518 			continue;
15519 
15520 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15521 		    (ipst->ips_ip_cgtp_filter &&
15522 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15523 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15524 			continue;
15525 		}
15526 
15527 		/*
15528 		 * Reuse the cached ire only if the ipha_dst of the previous
15529 		 * packet is the same as the current packet AND it is not
15530 		 * INADDR_ANY.
15531 		 */
15532 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15533 		    (ire != NULL)) {
15534 			ire_refrele(ire);
15535 			ire = NULL;
15536 		}
15537 
15538 		if (ire == NULL)
15539 			ire = ire_cache_lookup_simple(dst, ipst);
15540 
15541 		/*
15542 		 * Unless forwarding is enabled, dont call
15543 		 * ip_fast_forward(). Incoming packet is for forwarding
15544 		 */
15545 		if ((ill->ill_flags & ILLF_ROUTER) &&
15546 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15547 
15548 			DTRACE_PROBE4(ip4__physical__in__start,
15549 			    ill_t *, ill, ill_t *, NULL,
15550 			    ipha_t *, ipha, mblk_t *, mp);
15551 
15552 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15553 			    ipst->ips_ipv4firewall_physical_in,
15554 			    ill, NULL, ipha, mp, mp, 0, ipst);
15555 
15556 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15557 
15558 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15559 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15560 			    pkt_len);
15561 
15562 			if (mp != NULL)
15563 				ire = ip_fast_forward(ire, dst, ill, mp);
15564 			continue;
15565 		}
15566 
15567 		/* incoming packet is for local consumption */
15568 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15569 			goto local_accept;
15570 
15571 		/*
15572 		 * Disable ire caching for anything more complex
15573 		 * than the simple fast path case we checked for above.
15574 		 */
15575 		if (ire != NULL) {
15576 			ire_refrele(ire);
15577 			ire = NULL;
15578 		}
15579 
15580 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15581 		    ipst);
15582 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15583 		    ire->ire_stq != NULL) {
15584 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15585 			if (ire != NULL) {
15586 				ire_refrele(ire);
15587 				ire = NULL;
15588 			}
15589 			continue;
15590 		}
15591 
15592 local_accept:
15593 
15594 		if (ire->ire_rfq != q) {
15595 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15596 			if (ire != NULL) {
15597 				ire_refrele(ire);
15598 				ire = NULL;
15599 			}
15600 			continue;
15601 		}
15602 
15603 		/*
15604 		 * The event for packets being received from a 'physical'
15605 		 * interface is placed after validation of the source and/or
15606 		 * destination address as being local so that packets can be
15607 		 * redirected to loopback addresses using ipnat.
15608 		 */
15609 		DTRACE_PROBE4(ip4__physical__in__start,
15610 		    ill_t *, ill, ill_t *, NULL,
15611 		    ipha_t *, ipha, mblk_t *, mp);
15612 
15613 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15614 		    ipst->ips_ipv4firewall_physical_in,
15615 		    ill, NULL, ipha, mp, mp, 0, ipst);
15616 
15617 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15618 
15619 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15620 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15621 
15622 		if (mp != NULL &&
15623 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15624 		    0, q, ip_ring)) != NULL) {
15625 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15626 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15627 			} else {
15628 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15629 				    SQ_FILL, SQTAG_IP_INPUT);
15630 			}
15631 		}
15632 	}
15633 
15634 	if (ire != NULL)
15635 		ire_refrele(ire);
15636 
15637 	if (uhead != NULL)
15638 		ip_input(ill, ip_ring, uhead, NULL);
15639 
15640 	if (ahead != NULL) {
15641 		*last = atail;
15642 		*cnt = acnt;
15643 		return (ahead);
15644 	}
15645 
15646 	return (NULL);
15647 #undef  rptr
15648 }
15649 
15650 static void
15651 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15652     t_uscalar_t err)
15653 {
15654 	if (dl_err == DL_SYSERR) {
15655 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15656 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15657 		    ill->ill_name, dl_primstr(prim), err);
15658 		return;
15659 	}
15660 
15661 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15662 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15663 	    dl_errstr(dl_err));
15664 }
15665 
15666 /*
15667  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15668  * than DL_UNITDATA_IND messages. If we need to process this message
15669  * exclusively, we call qwriter_ip, in which case we also need to call
15670  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15671  */
15672 void
15673 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15674 {
15675 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15676 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15677 	ill_t		*ill = q->q_ptr;
15678 	t_uscalar_t	prim = dloa->dl_primitive;
15679 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15680 
15681 	ip1dbg(("ip_rput_dlpi"));
15682 
15683 	/*
15684 	 * If we received an ACK but didn't send a request for it, then it
15685 	 * can't be part of any pending operation; discard up-front.
15686 	 */
15687 	switch (prim) {
15688 	case DL_ERROR_ACK:
15689 		reqprim = dlea->dl_error_primitive;
15690 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15691 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15692 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15693 		    dlea->dl_unix_errno));
15694 		break;
15695 	case DL_OK_ACK:
15696 		reqprim = dloa->dl_correct_primitive;
15697 		break;
15698 	case DL_INFO_ACK:
15699 		reqprim = DL_INFO_REQ;
15700 		break;
15701 	case DL_BIND_ACK:
15702 		reqprim = DL_BIND_REQ;
15703 		break;
15704 	case DL_PHYS_ADDR_ACK:
15705 		reqprim = DL_PHYS_ADDR_REQ;
15706 		break;
15707 	case DL_NOTIFY_ACK:
15708 		reqprim = DL_NOTIFY_REQ;
15709 		break;
15710 	case DL_CONTROL_ACK:
15711 		reqprim = DL_CONTROL_REQ;
15712 		break;
15713 	case DL_CAPABILITY_ACK:
15714 		reqprim = DL_CAPABILITY_REQ;
15715 		break;
15716 	}
15717 
15718 	if (prim != DL_NOTIFY_IND) {
15719 		if (reqprim == DL_PRIM_INVAL ||
15720 		    !ill_dlpi_pending(ill, reqprim)) {
15721 			/* Not a DLPI message we support or expected */
15722 			freemsg(mp);
15723 			return;
15724 		}
15725 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15726 		    dl_primstr(reqprim)));
15727 	}
15728 
15729 	switch (reqprim) {
15730 	case DL_UNBIND_REQ:
15731 		/*
15732 		 * NOTE: we mark the unbind as complete even if we got a
15733 		 * DL_ERROR_ACK, since there's not much else we can do.
15734 		 */
15735 		mutex_enter(&ill->ill_lock);
15736 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15737 		cv_signal(&ill->ill_cv);
15738 		mutex_exit(&ill->ill_lock);
15739 		break;
15740 
15741 	case DL_ENABMULTI_REQ:
15742 		if (prim == DL_OK_ACK) {
15743 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15744 				ill->ill_dlpi_multicast_state = IDS_OK;
15745 		}
15746 		break;
15747 	}
15748 
15749 	/*
15750 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15751 	 * need to become writer to continue to process it.  Because an
15752 	 * exclusive operation doesn't complete until replies to all queued
15753 	 * DLPI messages have been received, we know we're in the middle of an
15754 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15755 	 *
15756 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15757 	 * Since this is on the ill stream we unconditionally bump up the
15758 	 * refcount without doing ILL_CAN_LOOKUP().
15759 	 */
15760 	ill_refhold(ill);
15761 	if (prim == DL_NOTIFY_IND)
15762 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15763 	else
15764 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15765 }
15766 
15767 /*
15768  * Handling of DLPI messages that require exclusive access to the ipsq.
15769  *
15770  * Need to do ill_pending_mp_release on ioctl completion, which could
15771  * happen here. (along with mi_copy_done)
15772  */
15773 /* ARGSUSED */
15774 static void
15775 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15776 {
15777 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15778 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15779 	int		err = 0;
15780 	ill_t		*ill;
15781 	ipif_t		*ipif = NULL;
15782 	mblk_t		*mp1 = NULL;
15783 	conn_t		*connp = NULL;
15784 	t_uscalar_t	paddrreq;
15785 	mblk_t		*mp_hw;
15786 	boolean_t	success;
15787 	boolean_t	ioctl_aborted = B_FALSE;
15788 	boolean_t	log = B_TRUE;
15789 	ip_stack_t		*ipst;
15790 
15791 	ip1dbg(("ip_rput_dlpi_writer .."));
15792 	ill = (ill_t *)q->q_ptr;
15793 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15794 	ASSERT(IAM_WRITER_ILL(ill));
15795 
15796 	ipst = ill->ill_ipst;
15797 
15798 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15799 	/*
15800 	 * The current ioctl could have been aborted by the user and a new
15801 	 * ioctl to bring up another ill could have started. We could still
15802 	 * get a response from the driver later.
15803 	 */
15804 	if (ipif != NULL && ipif->ipif_ill != ill)
15805 		ioctl_aborted = B_TRUE;
15806 
15807 	switch (dloa->dl_primitive) {
15808 	case DL_ERROR_ACK:
15809 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15810 		    dl_primstr(dlea->dl_error_primitive)));
15811 
15812 		switch (dlea->dl_error_primitive) {
15813 		case DL_DISABMULTI_REQ:
15814 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15815 			break;
15816 		case DL_PROMISCON_REQ:
15817 		case DL_PROMISCOFF_REQ:
15818 		case DL_UNBIND_REQ:
15819 		case DL_ATTACH_REQ:
15820 		case DL_INFO_REQ:
15821 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15822 			break;
15823 		case DL_NOTIFY_REQ:
15824 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15825 			log = B_FALSE;
15826 			break;
15827 		case DL_PHYS_ADDR_REQ:
15828 			/*
15829 			 * For IPv6 only, there are two additional
15830 			 * phys_addr_req's sent to the driver to get the
15831 			 * IPv6 token and lla. This allows IP to acquire
15832 			 * the hardware address format for a given interface
15833 			 * without having built in knowledge of the hardware
15834 			 * address. ill_phys_addr_pend keeps track of the last
15835 			 * DL_PAR sent so we know which response we are
15836 			 * dealing with. ill_dlpi_done will update
15837 			 * ill_phys_addr_pend when it sends the next req.
15838 			 * We don't complete the IOCTL until all three DL_PARs
15839 			 * have been attempted, so set *_len to 0 and break.
15840 			 */
15841 			paddrreq = ill->ill_phys_addr_pend;
15842 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15843 			if (paddrreq == DL_IPV6_TOKEN) {
15844 				ill->ill_token_length = 0;
15845 				log = B_FALSE;
15846 				break;
15847 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15848 				ill->ill_nd_lla_len = 0;
15849 				log = B_FALSE;
15850 				break;
15851 			}
15852 			/*
15853 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15854 			 * We presumably have an IOCTL hanging out waiting
15855 			 * for completion. Find it and complete the IOCTL
15856 			 * with the error noted.
15857 			 * However, ill_dl_phys was called on an ill queue
15858 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15859 			 * set. But the ioctl is known to be pending on ill_wq.
15860 			 */
15861 			if (!ill->ill_ifname_pending)
15862 				break;
15863 			ill->ill_ifname_pending = 0;
15864 			if (!ioctl_aborted)
15865 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15866 			if (mp1 != NULL) {
15867 				/*
15868 				 * This operation (SIOCSLIFNAME) must have
15869 				 * happened on the ill. Assert there is no conn
15870 				 */
15871 				ASSERT(connp == NULL);
15872 				q = ill->ill_wq;
15873 			}
15874 			break;
15875 		case DL_BIND_REQ:
15876 			ill_dlpi_done(ill, DL_BIND_REQ);
15877 			if (ill->ill_ifname_pending)
15878 				break;
15879 			/*
15880 			 * Something went wrong with the bind.  We presumably
15881 			 * have an IOCTL hanging out waiting for completion.
15882 			 * Find it, take down the interface that was coming
15883 			 * up, and complete the IOCTL with the error noted.
15884 			 */
15885 			if (!ioctl_aborted)
15886 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15887 			if (mp1 != NULL) {
15888 				/*
15889 				 * This might be a result of a DL_NOTE_REPLUMB
15890 				 * notification. In that case, connp is NULL.
15891 				 */
15892 				if (connp != NULL)
15893 					q = CONNP_TO_WQ(connp);
15894 
15895 				(void) ipif_down(ipif, NULL, NULL);
15896 				/* error is set below the switch */
15897 			}
15898 			break;
15899 		case DL_ENABMULTI_REQ:
15900 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15901 
15902 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15903 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15904 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15905 				ipif_t *ipif;
15906 
15907 				printf("ip: joining multicasts failed (%d)"
15908 				    " on %s - will use link layer "
15909 				    "broadcasts for multicast\n",
15910 				    dlea->dl_errno, ill->ill_name);
15911 
15912 				/*
15913 				 * Set up the multicast mapping alone.
15914 				 * writer, so ok to access ill->ill_ipif
15915 				 * without any lock.
15916 				 */
15917 				ipif = ill->ill_ipif;
15918 				mutex_enter(&ill->ill_phyint->phyint_lock);
15919 				ill->ill_phyint->phyint_flags |=
15920 				    PHYI_MULTI_BCAST;
15921 				mutex_exit(&ill->ill_phyint->phyint_lock);
15922 
15923 				if (!ill->ill_isv6) {
15924 					(void) ipif_arp_setup_multicast(ipif,
15925 					    NULL);
15926 				} else {
15927 					(void) ipif_ndp_setup_multicast(ipif,
15928 					    NULL);
15929 				}
15930 			}
15931 			freemsg(mp);	/* Don't want to pass this up */
15932 			return;
15933 		case DL_CONTROL_REQ:
15934 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15935 			    "DL_CONTROL_REQ\n"));
15936 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15937 			freemsg(mp);
15938 			return;
15939 		case DL_CAPABILITY_REQ:
15940 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15941 			    "DL_CAPABILITY REQ\n"));
15942 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15943 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15944 			ill_capability_done(ill);
15945 			freemsg(mp);
15946 			return;
15947 		}
15948 		/*
15949 		 * Note the error for IOCTL completion (mp1 is set when
15950 		 * ready to complete ioctl). If ill_ifname_pending_err is
15951 		 * set, an error occured during plumbing (ill_ifname_pending),
15952 		 * so we want to report that error.
15953 		 *
15954 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15955 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15956 		 * expected to get errack'd if the driver doesn't support
15957 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15958 		 * if these error conditions are encountered.
15959 		 */
15960 		if (mp1 != NULL) {
15961 			if (ill->ill_ifname_pending_err != 0)  {
15962 				err = ill->ill_ifname_pending_err;
15963 				ill->ill_ifname_pending_err = 0;
15964 			} else {
15965 				err = dlea->dl_unix_errno ?
15966 				    dlea->dl_unix_errno : ENXIO;
15967 			}
15968 		/*
15969 		 * If we're plumbing an interface and an error hasn't already
15970 		 * been saved, set ill_ifname_pending_err to the error passed
15971 		 * up. Ignore the error if log is B_FALSE (see comment above).
15972 		 */
15973 		} else if (log && ill->ill_ifname_pending &&
15974 		    ill->ill_ifname_pending_err == 0) {
15975 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15976 			    dlea->dl_unix_errno : ENXIO;
15977 		}
15978 
15979 		if (log)
15980 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15981 			    dlea->dl_errno, dlea->dl_unix_errno);
15982 		break;
15983 	case DL_CAPABILITY_ACK:
15984 		ill_capability_ack(ill, mp);
15985 		/*
15986 		 * The message has been handed off to ill_capability_ack
15987 		 * and must not be freed below
15988 		 */
15989 		mp = NULL;
15990 		break;
15991 
15992 	case DL_CONTROL_ACK:
15993 		/* We treat all of these as "fire and forget" */
15994 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15995 		break;
15996 	case DL_INFO_ACK:
15997 		/* Call a routine to handle this one. */
15998 		ill_dlpi_done(ill, DL_INFO_REQ);
15999 		ip_ll_subnet_defaults(ill, mp);
16000 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16001 		return;
16002 	case DL_BIND_ACK:
16003 		/*
16004 		 * We should have an IOCTL waiting on this unless
16005 		 * sent by ill_dl_phys, in which case just return
16006 		 */
16007 		ill_dlpi_done(ill, DL_BIND_REQ);
16008 		if (ill->ill_ifname_pending)
16009 			break;
16010 
16011 		if (!ioctl_aborted)
16012 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16013 		if (mp1 == NULL)
16014 			break;
16015 		/*
16016 		 * mp1 was added by ill_dl_up(). if that is a result of
16017 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16018 		 */
16019 		if (connp != NULL)
16020 			q = CONNP_TO_WQ(connp);
16021 
16022 		/*
16023 		 * We are exclusive. So nothing can change even after
16024 		 * we get the pending mp. If need be we can put it back
16025 		 * and restart, as in calling ipif_arp_up()  below.
16026 		 */
16027 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16028 
16029 		mutex_enter(&ill->ill_lock);
16030 		ill->ill_dl_up = 1;
16031 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16032 		mutex_exit(&ill->ill_lock);
16033 
16034 		/*
16035 		 * Now bring up the resolver; when that is complete, we'll
16036 		 * create IREs.  Note that we intentionally mirror what
16037 		 * ipif_up() would have done, because we got here by way of
16038 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16039 		 */
16040 		if (ill->ill_isv6) {
16041 			if (ill->ill_flags & ILLF_XRESOLV) {
16042 				if (connp != NULL)
16043 					mutex_enter(&connp->conn_lock);
16044 				mutex_enter(&ill->ill_lock);
16045 				success = ipsq_pending_mp_add(connp, ipif, q,
16046 				    mp1, 0);
16047 				mutex_exit(&ill->ill_lock);
16048 				if (connp != NULL)
16049 					mutex_exit(&connp->conn_lock);
16050 				if (success) {
16051 					err = ipif_resolver_up(ipif,
16052 					    Res_act_initial);
16053 					if (err == EINPROGRESS) {
16054 						freemsg(mp);
16055 						return;
16056 					}
16057 					ASSERT(err != 0);
16058 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16059 					ASSERT(mp1 != NULL);
16060 				} else {
16061 					/* conn has started closing */
16062 					err = EINTR;
16063 				}
16064 			} else { /* Non XRESOLV interface */
16065 				(void) ipif_resolver_up(ipif, Res_act_initial);
16066 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16067 					err = ipif_up_done_v6(ipif);
16068 			}
16069 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16070 			/*
16071 			 * ARP and other v4 external resolvers.
16072 			 * Leave the pending mblk intact so that
16073 			 * the ioctl completes in ip_rput().
16074 			 */
16075 			if (connp != NULL)
16076 				mutex_enter(&connp->conn_lock);
16077 			mutex_enter(&ill->ill_lock);
16078 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16079 			mutex_exit(&ill->ill_lock);
16080 			if (connp != NULL)
16081 				mutex_exit(&connp->conn_lock);
16082 			if (success) {
16083 				err = ipif_resolver_up(ipif, Res_act_initial);
16084 				if (err == EINPROGRESS) {
16085 					freemsg(mp);
16086 					return;
16087 				}
16088 				ASSERT(err != 0);
16089 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16090 			} else {
16091 				/* The conn has started closing */
16092 				err = EINTR;
16093 			}
16094 		} else {
16095 			/*
16096 			 * This one is complete. Reply to pending ioctl.
16097 			 */
16098 			(void) ipif_resolver_up(ipif, Res_act_initial);
16099 			err = ipif_up_done(ipif);
16100 		}
16101 
16102 		if ((err == 0) && (ill->ill_up_ipifs)) {
16103 			err = ill_up_ipifs(ill, q, mp1);
16104 			if (err == EINPROGRESS) {
16105 				freemsg(mp);
16106 				return;
16107 			}
16108 		}
16109 
16110 		/*
16111 		 * If we have a moved ipif to bring up, and everything has
16112 		 * succeeded to this point, bring it up on the IPMP ill.
16113 		 * Otherwise, leave it down -- the admin can try to bring it
16114 		 * up by hand if need be.
16115 		 */
16116 		if (ill->ill_move_ipif != NULL) {
16117 			if (err != 0) {
16118 				ill->ill_move_ipif = NULL;
16119 			} else {
16120 				ipif = ill->ill_move_ipif;
16121 				ill->ill_move_ipif = NULL;
16122 				err = ipif_up(ipif, q, mp1);
16123 				if (err == EINPROGRESS) {
16124 					freemsg(mp);
16125 					return;
16126 				}
16127 			}
16128 		}
16129 		break;
16130 
16131 	case DL_NOTIFY_IND: {
16132 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16133 		ire_t *ire;
16134 		uint_t orig_mtu;
16135 		boolean_t need_ire_walk_v4 = B_FALSE;
16136 		boolean_t need_ire_walk_v6 = B_FALSE;
16137 
16138 		switch (notify->dl_notification) {
16139 		case DL_NOTE_PHYS_ADDR:
16140 			err = ill_set_phys_addr(ill, mp);
16141 			break;
16142 
16143 		case DL_NOTE_REPLUMB:
16144 			/*
16145 			 * Directly return after calling ill_replumb().
16146 			 * Note that we should not free mp as it is reused
16147 			 * in the ill_replumb() function.
16148 			 */
16149 			err = ill_replumb(ill, mp);
16150 			return;
16151 
16152 		case DL_NOTE_FASTPATH_FLUSH:
16153 			ill_fastpath_flush(ill);
16154 			break;
16155 
16156 		case DL_NOTE_SDU_SIZE:
16157 			/*
16158 			 * Change the MTU size of the interface, of all
16159 			 * attached ipif's, and of all relevant ire's.  The
16160 			 * new value's a uint32_t at notify->dl_data.
16161 			 * Mtu change Vs. new ire creation - protocol below.
16162 			 *
16163 			 * a Mark the ipif as IPIF_CHANGING.
16164 			 * b Set the new mtu in the ipif.
16165 			 * c Change the ire_max_frag on all affected ires
16166 			 * d Unmark the IPIF_CHANGING
16167 			 *
16168 			 * To see how the protocol works, assume an interface
16169 			 * route is also being added simultaneously by
16170 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16171 			 * the ire. If the ire is created before step a,
16172 			 * it will be cleaned up by step c. If the ire is
16173 			 * created after step d, it will see the new value of
16174 			 * ipif_mtu. Any attempt to create the ire between
16175 			 * steps a to d will fail because of the IPIF_CHANGING
16176 			 * flag. Note that ire_create() is passed a pointer to
16177 			 * the ipif_mtu, and not the value. During ire_add
16178 			 * under the bucket lock, the ire_max_frag of the
16179 			 * new ire being created is set from the ipif/ire from
16180 			 * which it is being derived.
16181 			 */
16182 			mutex_enter(&ill->ill_lock);
16183 
16184 			orig_mtu = ill->ill_max_mtu;
16185 			ill->ill_max_frag = (uint_t)notify->dl_data;
16186 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16187 
16188 			/*
16189 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16190 			 * clamp ill_max_mtu at it.
16191 			 */
16192 			if (ill->ill_user_mtu != 0 &&
16193 			    ill->ill_user_mtu < ill->ill_max_mtu)
16194 				ill->ill_max_mtu = ill->ill_user_mtu;
16195 
16196 			/*
16197 			 * If the MTU is unchanged, we're done.
16198 			 */
16199 			if (orig_mtu == ill->ill_max_mtu) {
16200 				mutex_exit(&ill->ill_lock);
16201 				break;
16202 			}
16203 
16204 			if (ill->ill_isv6) {
16205 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16206 					ill->ill_max_mtu = IPV6_MIN_MTU;
16207 			} else {
16208 				if (ill->ill_max_mtu < IP_MIN_MTU)
16209 					ill->ill_max_mtu = IP_MIN_MTU;
16210 			}
16211 			for (ipif = ill->ill_ipif; ipif != NULL;
16212 			    ipif = ipif->ipif_next) {
16213 				/*
16214 				 * Don't override the mtu if the user
16215 				 * has explicitly set it.
16216 				 */
16217 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16218 					continue;
16219 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16220 				if (ipif->ipif_isv6)
16221 					ire = ipif_to_ire_v6(ipif);
16222 				else
16223 					ire = ipif_to_ire(ipif);
16224 				if (ire != NULL) {
16225 					ire->ire_max_frag = ipif->ipif_mtu;
16226 					ire_refrele(ire);
16227 				}
16228 				if (ipif->ipif_flags & IPIF_UP) {
16229 					if (ill->ill_isv6)
16230 						need_ire_walk_v6 = B_TRUE;
16231 					else
16232 						need_ire_walk_v4 = B_TRUE;
16233 				}
16234 			}
16235 			mutex_exit(&ill->ill_lock);
16236 			if (need_ire_walk_v4)
16237 				ire_walk_v4(ill_mtu_change, (char *)ill,
16238 				    ALL_ZONES, ipst);
16239 			if (need_ire_walk_v6)
16240 				ire_walk_v6(ill_mtu_change, (char *)ill,
16241 				    ALL_ZONES, ipst);
16242 
16243 			/*
16244 			 * Refresh IPMP meta-interface MTU if necessary.
16245 			 */
16246 			if (IS_UNDER_IPMP(ill))
16247 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16248 			break;
16249 
16250 		case DL_NOTE_LINK_UP:
16251 		case DL_NOTE_LINK_DOWN: {
16252 			/*
16253 			 * We are writer. ill / phyint / ipsq assocs stable.
16254 			 * The RUNNING flag reflects the state of the link.
16255 			 */
16256 			phyint_t *phyint = ill->ill_phyint;
16257 			uint64_t new_phyint_flags;
16258 			boolean_t changed = B_FALSE;
16259 			boolean_t went_up;
16260 
16261 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16262 			mutex_enter(&phyint->phyint_lock);
16263 
16264 			new_phyint_flags = went_up ?
16265 			    phyint->phyint_flags | PHYI_RUNNING :
16266 			    phyint->phyint_flags & ~PHYI_RUNNING;
16267 
16268 			if (IS_IPMP(ill)) {
16269 				new_phyint_flags = went_up ?
16270 				    new_phyint_flags & ~PHYI_FAILED :
16271 				    new_phyint_flags | PHYI_FAILED;
16272 			}
16273 
16274 			if (new_phyint_flags != phyint->phyint_flags) {
16275 				phyint->phyint_flags = new_phyint_flags;
16276 				changed = B_TRUE;
16277 			}
16278 			mutex_exit(&phyint->phyint_lock);
16279 			/*
16280 			 * ill_restart_dad handles the DAD restart and routing
16281 			 * socket notification logic.
16282 			 */
16283 			if (changed) {
16284 				ill_restart_dad(phyint->phyint_illv4, went_up);
16285 				ill_restart_dad(phyint->phyint_illv6, went_up);
16286 			}
16287 			break;
16288 		}
16289 		case DL_NOTE_PROMISC_ON_PHYS:
16290 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16291 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16292 			mutex_enter(&ill->ill_lock);
16293 			ill->ill_promisc_on_phys = B_TRUE;
16294 			mutex_exit(&ill->ill_lock);
16295 			break;
16296 		case DL_NOTE_PROMISC_OFF_PHYS:
16297 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16298 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16299 			mutex_enter(&ill->ill_lock);
16300 			ill->ill_promisc_on_phys = B_FALSE;
16301 			mutex_exit(&ill->ill_lock);
16302 			break;
16303 		case DL_NOTE_CAPAB_RENEG:
16304 			/*
16305 			 * Something changed on the driver side.
16306 			 * It wants us to renegotiate the capabilities
16307 			 * on this ill. One possible cause is the aggregation
16308 			 * interface under us where a port got added or
16309 			 * went away.
16310 			 *
16311 			 * If the capability negotiation is already done
16312 			 * or is in progress, reset the capabilities and
16313 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16314 			 * so that when the ack comes back, we can start
16315 			 * the renegotiation process.
16316 			 *
16317 			 * Note that if ill_capab_reneg is already B_TRUE
16318 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16319 			 * the capability resetting request has been sent
16320 			 * and the renegotiation has not been started yet;
16321 			 * nothing needs to be done in this case.
16322 			 */
16323 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16324 			ill_capability_reset(ill, B_TRUE);
16325 			ipsq_current_finish(ipsq);
16326 			break;
16327 		default:
16328 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16329 			    "type 0x%x for DL_NOTIFY_IND\n",
16330 			    notify->dl_notification));
16331 			break;
16332 		}
16333 
16334 		/*
16335 		 * As this is an asynchronous operation, we
16336 		 * should not call ill_dlpi_done
16337 		 */
16338 		break;
16339 	}
16340 	case DL_NOTIFY_ACK: {
16341 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16342 
16343 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16344 			ill->ill_note_link = 1;
16345 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16346 		break;
16347 	}
16348 	case DL_PHYS_ADDR_ACK: {
16349 		/*
16350 		 * As part of plumbing the interface via SIOCSLIFNAME,
16351 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16352 		 * whose answers we receive here.  As each answer is received,
16353 		 * we call ill_dlpi_done() to dispatch the next request as
16354 		 * we're processing the current one.  Once all answers have
16355 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16356 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16357 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16358 		 * available, but we know the ioctl is pending on ill_wq.)
16359 		 */
16360 		uint_t	paddrlen, paddroff;
16361 
16362 		paddrreq = ill->ill_phys_addr_pend;
16363 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16364 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16365 
16366 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16367 		if (paddrreq == DL_IPV6_TOKEN) {
16368 			/*
16369 			 * bcopy to low-order bits of ill_token
16370 			 *
16371 			 * XXX Temporary hack - currently, all known tokens
16372 			 * are 64 bits, so I'll cheat for the moment.
16373 			 */
16374 			bcopy(mp->b_rptr + paddroff,
16375 			    &ill->ill_token.s6_addr32[2], paddrlen);
16376 			ill->ill_token_length = paddrlen;
16377 			break;
16378 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16379 			ASSERT(ill->ill_nd_lla_mp == NULL);
16380 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16381 			mp = NULL;
16382 			break;
16383 		}
16384 
16385 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16386 		ASSERT(ill->ill_phys_addr_mp == NULL);
16387 		if (!ill->ill_ifname_pending)
16388 			break;
16389 		ill->ill_ifname_pending = 0;
16390 		if (!ioctl_aborted)
16391 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16392 		if (mp1 != NULL) {
16393 			ASSERT(connp == NULL);
16394 			q = ill->ill_wq;
16395 		}
16396 		/*
16397 		 * If any error acks received during the plumbing sequence,
16398 		 * ill_ifname_pending_err will be set. Break out and send up
16399 		 * the error to the pending ioctl.
16400 		 */
16401 		if (ill->ill_ifname_pending_err != 0) {
16402 			err = ill->ill_ifname_pending_err;
16403 			ill->ill_ifname_pending_err = 0;
16404 			break;
16405 		}
16406 
16407 		ill->ill_phys_addr_mp = mp;
16408 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16409 		mp = NULL;
16410 
16411 		/*
16412 		 * If paddrlen is zero, the DLPI provider doesn't support
16413 		 * physical addresses.  The other two tests were historical
16414 		 * workarounds for bugs in our former PPP implementation, but
16415 		 * now other things have grown dependencies on them -- e.g.,
16416 		 * the tun module specifies a dl_addr_length of zero in its
16417 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16418 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16419 		 * but only after careful testing ensures that all dependent
16420 		 * broken DLPI providers have been fixed.
16421 		 */
16422 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16423 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16424 			ill->ill_phys_addr = NULL;
16425 		} else if (paddrlen != ill->ill_phys_addr_length) {
16426 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16427 			    paddrlen, ill->ill_phys_addr_length));
16428 			err = EINVAL;
16429 			break;
16430 		}
16431 
16432 		if (ill->ill_nd_lla_mp == NULL) {
16433 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16434 				err = ENOMEM;
16435 				break;
16436 			}
16437 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16438 		}
16439 
16440 		/*
16441 		 * Set the interface token.  If the zeroth interface address
16442 		 * is unspecified, then set it to the link local address.
16443 		 */
16444 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16445 			(void) ill_setdefaulttoken(ill);
16446 
16447 		ASSERT(ill->ill_ipif->ipif_id == 0);
16448 		if (ipif != NULL &&
16449 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16450 			(void) ipif_setlinklocal(ipif);
16451 		}
16452 		break;
16453 	}
16454 	case DL_OK_ACK:
16455 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16456 		    dl_primstr((int)dloa->dl_correct_primitive),
16457 		    dloa->dl_correct_primitive));
16458 		switch (dloa->dl_correct_primitive) {
16459 		case DL_ENABMULTI_REQ:
16460 		case DL_DISABMULTI_REQ:
16461 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16462 			break;
16463 		case DL_PROMISCON_REQ:
16464 		case DL_PROMISCOFF_REQ:
16465 		case DL_UNBIND_REQ:
16466 		case DL_ATTACH_REQ:
16467 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16468 			break;
16469 		}
16470 		break;
16471 	default:
16472 		break;
16473 	}
16474 
16475 	freemsg(mp);
16476 	if (mp1 == NULL)
16477 		return;
16478 
16479 	/*
16480 	 * The operation must complete without EINPROGRESS since
16481 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16482 	 * the operation will be stuck forever inside the IPSQ.
16483 	 */
16484 	ASSERT(err != EINPROGRESS);
16485 
16486 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16487 	case 0:
16488 		ipsq_current_finish(ipsq);
16489 		break;
16490 
16491 	case SIOCSLIFNAME:
16492 	case IF_UNITSEL: {
16493 		ill_t *ill_other = ILL_OTHER(ill);
16494 
16495 		/*
16496 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16497 		 * ill has a peer which is in an IPMP group, then place ill
16498 		 * into the same group.  One catch: although ifconfig plumbs
16499 		 * the appropriate IPMP meta-interface prior to plumbing this
16500 		 * ill, it is possible for multiple ifconfig applications to
16501 		 * race (or for another application to adjust plumbing), in
16502 		 * which case the IPMP meta-interface we need will be missing.
16503 		 * If so, kick the phyint out of the group.
16504 		 */
16505 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16506 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16507 			ipmp_illgrp_t	*illg;
16508 
16509 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16510 			if (illg == NULL)
16511 				ipmp_phyint_leave_grp(ill->ill_phyint);
16512 			else
16513 				ipmp_ill_join_illgrp(ill, illg);
16514 		}
16515 
16516 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16517 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16518 		else
16519 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16520 		break;
16521 	}
16522 	case SIOCLIFADDIF:
16523 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16524 		break;
16525 
16526 	default:
16527 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16528 		break;
16529 	}
16530 }
16531 
16532 /*
16533  * ip_rput_other is called by ip_rput to handle messages modifying the global
16534  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16535  */
16536 /* ARGSUSED */
16537 void
16538 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16539 {
16540 	ill_t		*ill = q->q_ptr;
16541 	struct iocblk	*iocp;
16542 	mblk_t		*mp1;
16543 	conn_t		*connp = NULL;
16544 
16545 	ip1dbg(("ip_rput_other "));
16546 	if (ipsq != NULL) {
16547 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16548 		ASSERT(ipsq->ipsq_xop ==
16549 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16550 	}
16551 
16552 	switch (mp->b_datap->db_type) {
16553 	case M_ERROR:
16554 	case M_HANGUP:
16555 		/*
16556 		 * The device has a problem.  We force the ILL down.  It can
16557 		 * be brought up again manually using SIOCSIFFLAGS (via
16558 		 * ifconfig or equivalent).
16559 		 */
16560 		ASSERT(ipsq != NULL);
16561 		if (mp->b_rptr < mp->b_wptr)
16562 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16563 		if (ill->ill_error == 0)
16564 			ill->ill_error = ENXIO;
16565 		if (!ill_down_start(q, mp))
16566 			return;
16567 		ipif_all_down_tail(ipsq, q, mp, NULL);
16568 		break;
16569 	case M_IOCACK:
16570 		iocp = (struct iocblk *)mp->b_rptr;
16571 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16572 		switch (iocp->ioc_cmd) {
16573 		case SIOCSTUNPARAM:
16574 		case OSIOCSTUNPARAM:
16575 			ASSERT(ipsq != NULL);
16576 			/*
16577 			 * Finish socket ioctl passed through to tun.
16578 			 * We should have an IOCTL waiting on this.
16579 			 */
16580 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16581 			if (ill->ill_isv6) {
16582 				struct iftun_req *ta;
16583 
16584 				/*
16585 				 * if a source or destination is
16586 				 * being set, try and set the link
16587 				 * local address for the tunnel
16588 				 */
16589 				ta = (struct iftun_req *)mp->b_cont->
16590 				    b_cont->b_rptr;
16591 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16592 					ipif_set_tun_llink(ill, ta);
16593 				}
16594 
16595 			}
16596 			if (mp1 != NULL) {
16597 				/*
16598 				 * Now copy back the b_next/b_prev used by
16599 				 * mi code for the mi_copy* functions.
16600 				 * See ip_sioctl_tunparam() for the reason.
16601 				 * Also protect against missing b_cont.
16602 				 */
16603 				if (mp->b_cont != NULL) {
16604 					mp->b_cont->b_next =
16605 					    mp1->b_cont->b_next;
16606 					mp->b_cont->b_prev =
16607 					    mp1->b_cont->b_prev;
16608 				}
16609 				inet_freemsg(mp1);
16610 				ASSERT(connp != NULL);
16611 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16612 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16613 			} else {
16614 				ASSERT(connp == NULL);
16615 				putnext(q, mp);
16616 			}
16617 			break;
16618 		case SIOCGTUNPARAM:
16619 		case OSIOCGTUNPARAM:
16620 			/*
16621 			 * This is really M_IOCDATA from the tunnel driver.
16622 			 * convert back and complete the ioctl.
16623 			 * We should have an IOCTL waiting on this.
16624 			 */
16625 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16626 			if (mp1) {
16627 				/*
16628 				 * Now copy back the b_next/b_prev used by
16629 				 * mi code for the mi_copy* functions.
16630 				 * See ip_sioctl_tunparam() for the reason.
16631 				 * Also protect against missing b_cont.
16632 				 */
16633 				if (mp->b_cont != NULL) {
16634 					mp->b_cont->b_next =
16635 					    mp1->b_cont->b_next;
16636 					mp->b_cont->b_prev =
16637 					    mp1->b_cont->b_prev;
16638 				}
16639 				inet_freemsg(mp1);
16640 				if (iocp->ioc_error == 0)
16641 					mp->b_datap->db_type = M_IOCDATA;
16642 				ASSERT(connp != NULL);
16643 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16644 				    iocp->ioc_error, COPYOUT, NULL);
16645 			} else {
16646 				ASSERT(connp == NULL);
16647 				putnext(q, mp);
16648 			}
16649 			break;
16650 		default:
16651 			break;
16652 		}
16653 		break;
16654 	case M_IOCNAK:
16655 		iocp = (struct iocblk *)mp->b_rptr;
16656 
16657 		switch (iocp->ioc_cmd) {
16658 			int mode;
16659 
16660 		case DL_IOC_HDR_INFO:
16661 			/*
16662 			 * If this was the first attempt, turn off the
16663 			 * fastpath probing.
16664 			 */
16665 			mutex_enter(&ill->ill_lock);
16666 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16667 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16668 				mutex_exit(&ill->ill_lock);
16669 				ill_fastpath_nack(ill);
16670 				ip1dbg(("ip_rput: DLPI fastpath off on "
16671 				    "interface %s\n",
16672 				    ill->ill_name));
16673 			} else {
16674 				mutex_exit(&ill->ill_lock);
16675 			}
16676 			freemsg(mp);
16677 			break;
16678 			case SIOCSTUNPARAM:
16679 		case OSIOCSTUNPARAM:
16680 			ASSERT(ipsq != NULL);
16681 			/*
16682 			 * Finish socket ioctl passed through to tun
16683 			 * We should have an IOCTL waiting on this.
16684 			 */
16685 			/* FALLTHRU */
16686 		case SIOCGTUNPARAM:
16687 		case OSIOCGTUNPARAM:
16688 			/*
16689 			 * This is really M_IOCDATA from the tunnel driver.
16690 			 * convert back and complete the ioctl.
16691 			 * We should have an IOCTL waiting on this.
16692 			 */
16693 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16694 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16695 				mp1 = ill_pending_mp_get(ill, &connp,
16696 				    iocp->ioc_id);
16697 				mode = COPYOUT;
16698 				ipsq = NULL;
16699 			} else {
16700 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16701 				mode = NO_COPYOUT;
16702 			}
16703 			if (mp1 != NULL) {
16704 				/*
16705 				 * Now copy back the b_next/b_prev used by
16706 				 * mi code for the mi_copy* functions.
16707 				 * See ip_sioctl_tunparam() for the reason.
16708 				 * Also protect against missing b_cont.
16709 				 */
16710 				if (mp->b_cont != NULL) {
16711 					mp->b_cont->b_next =
16712 					    mp1->b_cont->b_next;
16713 					mp->b_cont->b_prev =
16714 					    mp1->b_cont->b_prev;
16715 				}
16716 				inet_freemsg(mp1);
16717 				if (iocp->ioc_error == 0)
16718 					iocp->ioc_error = EINVAL;
16719 				ASSERT(connp != NULL);
16720 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16721 				    iocp->ioc_error, mode, ipsq);
16722 			} else {
16723 				ASSERT(connp == NULL);
16724 				putnext(q, mp);
16725 			}
16726 			break;
16727 		default:
16728 			break;
16729 		}
16730 	default:
16731 		break;
16732 	}
16733 }
16734 
16735 /*
16736  * NOTE : This function does not ire_refrele the ire argument passed in.
16737  *
16738  * IPQoS notes
16739  * IP policy is invoked twice for a forwarded packet, once on the read side
16740  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16741  * enabled. An additional parameter, in_ill, has been added for this purpose.
16742  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16743  * because ip_mroute drops this information.
16744  *
16745  */
16746 void
16747 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16748 {
16749 	uint32_t	old_pkt_len;
16750 	uint32_t	pkt_len;
16751 	queue_t	*q;
16752 	uint32_t	sum;
16753 #define	rptr	((uchar_t *)ipha)
16754 	uint32_t	max_frag;
16755 	uint32_t	ill_index;
16756 	ill_t		*out_ill;
16757 	mib2_ipIfStatsEntry_t *mibptr;
16758 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16759 
16760 	/* Get the ill_index of the incoming ILL */
16761 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16762 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16763 
16764 	/* Initiate Read side IPPF processing */
16765 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16766 		ip_process(IPP_FWD_IN, &mp, ill_index);
16767 		if (mp == NULL) {
16768 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16769 			    "during IPPF processing\n"));
16770 			return;
16771 		}
16772 	}
16773 
16774 	/* Adjust the checksum to reflect the ttl decrement. */
16775 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16776 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16777 
16778 	if (ipha->ipha_ttl-- <= 1) {
16779 		if (ip_csum_hdr(ipha)) {
16780 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16781 			goto drop_pkt;
16782 		}
16783 		/*
16784 		 * Note: ire_stq this will be NULL for multicast
16785 		 * datagrams using the long path through arp (the IRE
16786 		 * is not an IRE_CACHE). This should not cause
16787 		 * problems since we don't generate ICMP errors for
16788 		 * multicast packets.
16789 		 */
16790 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16791 		q = ire->ire_stq;
16792 		if (q != NULL) {
16793 			/* Sent by forwarding path, and router is global zone */
16794 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16795 			    GLOBAL_ZONEID, ipst);
16796 		} else
16797 			freemsg(mp);
16798 		return;
16799 	}
16800 
16801 	/*
16802 	 * Don't forward if the interface is down
16803 	 */
16804 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16805 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16806 		ip2dbg(("ip_rput_forward:interface is down\n"));
16807 		goto drop_pkt;
16808 	}
16809 
16810 	/* Get the ill_index of the outgoing ILL */
16811 	out_ill = ire_to_ill(ire);
16812 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16813 
16814 	DTRACE_PROBE4(ip4__forwarding__start,
16815 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16816 
16817 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16818 	    ipst->ips_ipv4firewall_forwarding,
16819 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16820 
16821 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16822 
16823 	if (mp == NULL)
16824 		return;
16825 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16826 
16827 	if (is_system_labeled()) {
16828 		mblk_t *mp1;
16829 
16830 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16831 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16832 			goto drop_pkt;
16833 		}
16834 		/* Size may have changed */
16835 		mp = mp1;
16836 		ipha = (ipha_t *)mp->b_rptr;
16837 		pkt_len = ntohs(ipha->ipha_length);
16838 	}
16839 
16840 	/* Check if there are options to update */
16841 	if (!IS_SIMPLE_IPH(ipha)) {
16842 		if (ip_csum_hdr(ipha)) {
16843 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16844 			goto drop_pkt;
16845 		}
16846 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16847 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16848 			return;
16849 		}
16850 
16851 		ipha->ipha_hdr_checksum = 0;
16852 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16853 	}
16854 	max_frag = ire->ire_max_frag;
16855 	if (pkt_len > max_frag) {
16856 		/*
16857 		 * It needs fragging on its way out.  We haven't
16858 		 * verified the header checksum yet.  Since we
16859 		 * are going to put a surely good checksum in the
16860 		 * outgoing header, we have to make sure that it
16861 		 * was good coming in.
16862 		 */
16863 		if (ip_csum_hdr(ipha)) {
16864 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16865 			goto drop_pkt;
16866 		}
16867 		/* Initiate Write side IPPF processing */
16868 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16869 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16870 			if (mp == NULL) {
16871 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16872 				    " during IPPF processing\n"));
16873 				return;
16874 			}
16875 		}
16876 		/*
16877 		 * Handle labeled packet resizing.
16878 		 *
16879 		 * If we have added a label, inform ip_wput_frag() of its
16880 		 * effect on the MTU for ICMP messages.
16881 		 */
16882 		if (pkt_len > old_pkt_len) {
16883 			uint32_t secopt_size;
16884 
16885 			secopt_size = pkt_len - old_pkt_len;
16886 			if (secopt_size < max_frag)
16887 				max_frag -= secopt_size;
16888 		}
16889 
16890 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16891 		    GLOBAL_ZONEID, ipst, NULL);
16892 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16893 		return;
16894 	}
16895 
16896 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16897 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16898 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16899 	    ipst->ips_ipv4firewall_physical_out,
16900 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16901 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16902 	if (mp == NULL)
16903 		return;
16904 
16905 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16906 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16907 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16908 	/* ip_xmit_v4 always consumes the packet */
16909 	return;
16910 
16911 drop_pkt:;
16912 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16913 	freemsg(mp);
16914 #undef	rptr
16915 }
16916 
16917 void
16918 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16919 {
16920 	ire_t	*ire;
16921 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16922 
16923 	ASSERT(!ipif->ipif_isv6);
16924 	/*
16925 	 * Find an IRE which matches the destination and the outgoing
16926 	 * queue in the cache table. All we need is an IRE_CACHE which
16927 	 * is pointing at ipif->ipif_ill.
16928 	 */
16929 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16930 		dst = ipif->ipif_pp_dst_addr;
16931 
16932 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16933 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16934 	if (ire == NULL) {
16935 		/*
16936 		 * Mark this packet to make it be delivered to
16937 		 * ip_rput_forward after the new ire has been
16938 		 * created.
16939 		 */
16940 		mp->b_prev = NULL;
16941 		mp->b_next = mp;
16942 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16943 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16944 	} else {
16945 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16946 		IRE_REFRELE(ire);
16947 	}
16948 }
16949 
16950 /* Update any source route, record route or timestamp options */
16951 static int
16952 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16953 {
16954 	ipoptp_t	opts;
16955 	uchar_t		*opt;
16956 	uint8_t		optval;
16957 	uint8_t		optlen;
16958 	ipaddr_t	dst;
16959 	uint32_t	ts;
16960 	ire_t		*dst_ire = NULL;
16961 	ire_t		*tmp_ire = NULL;
16962 	timestruc_t	now;
16963 
16964 	ip2dbg(("ip_rput_forward_options\n"));
16965 	dst = ipha->ipha_dst;
16966 	for (optval = ipoptp_first(&opts, ipha);
16967 	    optval != IPOPT_EOL;
16968 	    optval = ipoptp_next(&opts)) {
16969 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16970 		opt = opts.ipoptp_cur;
16971 		optlen = opts.ipoptp_len;
16972 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16973 		    optval, opts.ipoptp_len));
16974 		switch (optval) {
16975 			uint32_t off;
16976 		case IPOPT_SSRR:
16977 		case IPOPT_LSRR:
16978 			/* Check if adminstratively disabled */
16979 			if (!ipst->ips_ip_forward_src_routed) {
16980 				if (ire->ire_stq != NULL) {
16981 					/*
16982 					 * Sent by forwarding path, and router
16983 					 * is global zone
16984 					 */
16985 					icmp_unreachable(ire->ire_stq, mp,
16986 					    ICMP_SOURCE_ROUTE_FAILED,
16987 					    GLOBAL_ZONEID, ipst);
16988 				} else {
16989 					ip0dbg(("ip_rput_forward_options: "
16990 					    "unable to send unreach\n"));
16991 					freemsg(mp);
16992 				}
16993 				return (-1);
16994 			}
16995 
16996 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16997 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16998 			if (dst_ire == NULL) {
16999 				/*
17000 				 * Must be partial since ip_rput_options
17001 				 * checked for strict.
17002 				 */
17003 				break;
17004 			}
17005 			off = opt[IPOPT_OFFSET];
17006 			off--;
17007 		redo_srr:
17008 			if (optlen < IP_ADDR_LEN ||
17009 			    off > optlen - IP_ADDR_LEN) {
17010 				/* End of source route */
17011 				ip1dbg((
17012 				    "ip_rput_forward_options: end of SR\n"));
17013 				ire_refrele(dst_ire);
17014 				break;
17015 			}
17016 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17017 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17018 			    IP_ADDR_LEN);
17019 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17020 			    ntohl(dst)));
17021 
17022 			/*
17023 			 * Check if our address is present more than
17024 			 * once as consecutive hops in source route.
17025 			 */
17026 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17027 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17028 			if (tmp_ire != NULL) {
17029 				ire_refrele(tmp_ire);
17030 				off += IP_ADDR_LEN;
17031 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17032 				goto redo_srr;
17033 			}
17034 			ipha->ipha_dst = dst;
17035 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17036 			ire_refrele(dst_ire);
17037 			break;
17038 		case IPOPT_RR:
17039 			off = opt[IPOPT_OFFSET];
17040 			off--;
17041 			if (optlen < IP_ADDR_LEN ||
17042 			    off > optlen - IP_ADDR_LEN) {
17043 				/* No more room - ignore */
17044 				ip1dbg((
17045 				    "ip_rput_forward_options: end of RR\n"));
17046 				break;
17047 			}
17048 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17049 			    IP_ADDR_LEN);
17050 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17051 			break;
17052 		case IPOPT_TS:
17053 			/* Insert timestamp if there is room */
17054 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17055 			case IPOPT_TS_TSONLY:
17056 				off = IPOPT_TS_TIMELEN;
17057 				break;
17058 			case IPOPT_TS_PRESPEC:
17059 			case IPOPT_TS_PRESPEC_RFC791:
17060 				/* Verify that the address matched */
17061 				off = opt[IPOPT_OFFSET] - 1;
17062 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17063 				dst_ire = ire_ctable_lookup(dst, 0,
17064 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17065 				    MATCH_IRE_TYPE, ipst);
17066 				if (dst_ire == NULL) {
17067 					/* Not for us */
17068 					break;
17069 				}
17070 				ire_refrele(dst_ire);
17071 				/* FALLTHRU */
17072 			case IPOPT_TS_TSANDADDR:
17073 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17074 				break;
17075 			default:
17076 				/*
17077 				 * ip_*put_options should have already
17078 				 * dropped this packet.
17079 				 */
17080 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17081 				    "unknown IT - bug in ip_rput_options?\n");
17082 				return (0);	/* Keep "lint" happy */
17083 			}
17084 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17085 				/* Increase overflow counter */
17086 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17087 				opt[IPOPT_POS_OV_FLG] =
17088 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17089 				    (off << 4));
17090 				break;
17091 			}
17092 			off = opt[IPOPT_OFFSET] - 1;
17093 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17094 			case IPOPT_TS_PRESPEC:
17095 			case IPOPT_TS_PRESPEC_RFC791:
17096 			case IPOPT_TS_TSANDADDR:
17097 				bcopy(&ire->ire_src_addr,
17098 				    (char *)opt + off, IP_ADDR_LEN);
17099 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17100 				/* FALLTHRU */
17101 			case IPOPT_TS_TSONLY:
17102 				off = opt[IPOPT_OFFSET] - 1;
17103 				/* Compute # of milliseconds since midnight */
17104 				gethrestime(&now);
17105 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17106 				    now.tv_nsec / (NANOSEC / MILLISEC);
17107 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17108 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17109 				break;
17110 			}
17111 			break;
17112 		}
17113 	}
17114 	return (0);
17115 }
17116 
17117 /*
17118  * This is called after processing at least one of AH/ESP headers.
17119  *
17120  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17121  * the actual, physical interface on which the packet was received,
17122  * but, when ip_strict_dst_multihoming is set to 1, could be the
17123  * interface which had the ipha_dst configured when the packet went
17124  * through ip_rput. The ill_index corresponding to the recv_ill
17125  * is saved in ipsec_in_rill_index
17126  *
17127  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17128  * cannot assume "ire" points to valid data for any IPv6 cases.
17129  */
17130 void
17131 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17132 {
17133 	mblk_t *mp;
17134 	ipaddr_t dst;
17135 	in6_addr_t *v6dstp;
17136 	ipha_t *ipha;
17137 	ip6_t *ip6h;
17138 	ipsec_in_t *ii;
17139 	boolean_t ill_need_rele = B_FALSE;
17140 	boolean_t rill_need_rele = B_FALSE;
17141 	boolean_t ire_need_rele = B_FALSE;
17142 	netstack_t	*ns;
17143 	ip_stack_t	*ipst;
17144 
17145 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17146 	ASSERT(ii->ipsec_in_ill_index != 0);
17147 	ns = ii->ipsec_in_ns;
17148 	ASSERT(ii->ipsec_in_ns != NULL);
17149 	ipst = ns->netstack_ip;
17150 
17151 	mp = ipsec_mp->b_cont;
17152 	ASSERT(mp != NULL);
17153 
17154 	if (ill == NULL) {
17155 		ASSERT(recv_ill == NULL);
17156 		/*
17157 		 * We need to get the original queue on which ip_rput_local
17158 		 * or ip_rput_data_v6 was called.
17159 		 */
17160 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17161 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17162 		ill_need_rele = B_TRUE;
17163 
17164 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17165 			recv_ill = ill_lookup_on_ifindex(
17166 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17167 			    NULL, NULL, NULL, NULL, ipst);
17168 			rill_need_rele = B_TRUE;
17169 		} else {
17170 			recv_ill = ill;
17171 		}
17172 
17173 		if ((ill == NULL) || (recv_ill == NULL)) {
17174 			ip0dbg(("ip_fanout_proto_again: interface "
17175 			    "disappeared\n"));
17176 			if (ill != NULL)
17177 				ill_refrele(ill);
17178 			if (recv_ill != NULL)
17179 				ill_refrele(recv_ill);
17180 			freemsg(ipsec_mp);
17181 			return;
17182 		}
17183 	}
17184 
17185 	ASSERT(ill != NULL && recv_ill != NULL);
17186 
17187 	if (mp->b_datap->db_type == M_CTL) {
17188 		/*
17189 		 * AH/ESP is returning the ICMP message after
17190 		 * removing their headers. Fanout again till
17191 		 * it gets to the right protocol.
17192 		 */
17193 		if (ii->ipsec_in_v4) {
17194 			icmph_t *icmph;
17195 			int iph_hdr_length;
17196 			int hdr_length;
17197 
17198 			ipha = (ipha_t *)mp->b_rptr;
17199 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17200 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17201 			ipha = (ipha_t *)&icmph[1];
17202 			hdr_length = IPH_HDR_LENGTH(ipha);
17203 			/*
17204 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17205 			 * Reset the type to M_DATA.
17206 			 */
17207 			mp->b_datap->db_type = M_DATA;
17208 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17209 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17210 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17211 		} else {
17212 			icmp6_t *icmp6;
17213 			int hdr_length;
17214 
17215 			ip6h = (ip6_t *)mp->b_rptr;
17216 			/* Don't call hdr_length_v6() unless you have to. */
17217 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17218 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17219 			else
17220 				hdr_length = IPV6_HDR_LEN;
17221 
17222 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17223 			/*
17224 			 * icmp_inbound_error_fanout_v6 may need to do
17225 			 * pullupmsg.  Reset the type to M_DATA.
17226 			 */
17227 			mp->b_datap->db_type = M_DATA;
17228 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17229 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17230 			    ii->ipsec_in_zoneid);
17231 		}
17232 		if (ill_need_rele)
17233 			ill_refrele(ill);
17234 		if (rill_need_rele)
17235 			ill_refrele(recv_ill);
17236 		return;
17237 	}
17238 
17239 	if (ii->ipsec_in_v4) {
17240 		ipha = (ipha_t *)mp->b_rptr;
17241 		dst = ipha->ipha_dst;
17242 		if (CLASSD(dst)) {
17243 			/*
17244 			 * Multicast has to be delivered to all streams.
17245 			 */
17246 			dst = INADDR_BROADCAST;
17247 		}
17248 
17249 		if (ire == NULL) {
17250 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17251 			    msg_getlabel(mp), ipst);
17252 			if (ire == NULL) {
17253 				if (ill_need_rele)
17254 					ill_refrele(ill);
17255 				if (rill_need_rele)
17256 					ill_refrele(recv_ill);
17257 				ip1dbg(("ip_fanout_proto_again: "
17258 				    "IRE not found"));
17259 				freemsg(ipsec_mp);
17260 				return;
17261 			}
17262 			ire_need_rele = B_TRUE;
17263 		}
17264 
17265 		switch (ipha->ipha_protocol) {
17266 		case IPPROTO_UDP:
17267 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17268 			    recv_ill);
17269 			if (ire_need_rele)
17270 				ire_refrele(ire);
17271 			break;
17272 		case IPPROTO_TCP:
17273 			if (!ire_need_rele)
17274 				IRE_REFHOLD(ire);
17275 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17276 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17277 			IRE_REFRELE(ire);
17278 			if (mp != NULL) {
17279 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17280 				    mp, 1, SQ_PROCESS,
17281 				    SQTAG_IP_PROTO_AGAIN);
17282 			}
17283 			break;
17284 		case IPPROTO_SCTP:
17285 			if (!ire_need_rele)
17286 				IRE_REFHOLD(ire);
17287 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17288 			    ipsec_mp, 0, ill->ill_rq, dst);
17289 			break;
17290 		default:
17291 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17292 			    recv_ill, 0);
17293 			if (ire_need_rele)
17294 				ire_refrele(ire);
17295 			break;
17296 		}
17297 	} else {
17298 		uint32_t rput_flags = 0;
17299 
17300 		ip6h = (ip6_t *)mp->b_rptr;
17301 		v6dstp = &ip6h->ip6_dst;
17302 		/*
17303 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17304 		 * address.
17305 		 *
17306 		 * Currently, we don't store that state in the IPSEC_IN
17307 		 * message, and we may need to.
17308 		 */
17309 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17310 		    IP6_IN_LLMCAST : 0);
17311 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17312 		    NULL, NULL);
17313 	}
17314 	if (ill_need_rele)
17315 		ill_refrele(ill);
17316 	if (rill_need_rele)
17317 		ill_refrele(recv_ill);
17318 }
17319 
17320 /*
17321  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17322  * returns 'true' if there are still fragments left on the queue, in
17323  * which case we restart the timer.
17324  */
17325 void
17326 ill_frag_timer(void *arg)
17327 {
17328 	ill_t	*ill = (ill_t *)arg;
17329 	boolean_t frag_pending;
17330 	ip_stack_t	*ipst = ill->ill_ipst;
17331 
17332 	mutex_enter(&ill->ill_lock);
17333 	ASSERT(!ill->ill_fragtimer_executing);
17334 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17335 		ill->ill_frag_timer_id = 0;
17336 		mutex_exit(&ill->ill_lock);
17337 		return;
17338 	}
17339 	ill->ill_fragtimer_executing = 1;
17340 	mutex_exit(&ill->ill_lock);
17341 
17342 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17343 
17344 	/*
17345 	 * Restart the timer, if we have fragments pending or if someone
17346 	 * wanted us to be scheduled again.
17347 	 */
17348 	mutex_enter(&ill->ill_lock);
17349 	ill->ill_fragtimer_executing = 0;
17350 	ill->ill_frag_timer_id = 0;
17351 	if (frag_pending || ill->ill_fragtimer_needrestart)
17352 		ill_frag_timer_start(ill);
17353 	mutex_exit(&ill->ill_lock);
17354 }
17355 
17356 void
17357 ill_frag_timer_start(ill_t *ill)
17358 {
17359 	ip_stack_t	*ipst = ill->ill_ipst;
17360 
17361 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17362 
17363 	/* If the ill is closing or opening don't proceed */
17364 	if (ill->ill_state_flags & ILL_CONDEMNED)
17365 		return;
17366 
17367 	if (ill->ill_fragtimer_executing) {
17368 		/*
17369 		 * ill_frag_timer is currently executing. Just record the
17370 		 * the fact that we want the timer to be restarted.
17371 		 * ill_frag_timer will post a timeout before it returns,
17372 		 * ensuring it will be called again.
17373 		 */
17374 		ill->ill_fragtimer_needrestart = 1;
17375 		return;
17376 	}
17377 
17378 	if (ill->ill_frag_timer_id == 0) {
17379 		/*
17380 		 * The timer is neither running nor is the timeout handler
17381 		 * executing. Post a timeout so that ill_frag_timer will be
17382 		 * called
17383 		 */
17384 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17385 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17386 		ill->ill_fragtimer_needrestart = 0;
17387 	}
17388 }
17389 
17390 /*
17391  * This routine is needed for loopback when forwarding multicasts.
17392  *
17393  * IPQoS Notes:
17394  * IPPF processing is done in fanout routines.
17395  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17396  * processing for IPsec packets is done when it comes back in clear.
17397  * NOTE : The callers of this function need to do the ire_refrele for the
17398  *	  ire that is being passed in.
17399  */
17400 void
17401 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17402     ill_t *recv_ill, uint32_t esp_udp_ports)
17403 {
17404 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17405 	ill_t	*ill = (ill_t *)q->q_ptr;
17406 	uint32_t	sum;
17407 	uint32_t	u1;
17408 	uint32_t	u2;
17409 	int		hdr_length;
17410 	boolean_t	mctl_present;
17411 	mblk_t		*first_mp = mp;
17412 	mblk_t		*hada_mp = NULL;
17413 	ipha_t		*inner_ipha;
17414 	ip_stack_t	*ipst;
17415 
17416 	ASSERT(recv_ill != NULL);
17417 	ipst = recv_ill->ill_ipst;
17418 
17419 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17420 	    "ip_rput_locl_start: q %p", q);
17421 
17422 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17423 	ASSERT(ill != NULL);
17424 
17425 #define	rptr	((uchar_t *)ipha)
17426 #define	iphs	((uint16_t *)ipha)
17427 
17428 	/*
17429 	 * no UDP or TCP packet should come here anymore.
17430 	 */
17431 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17432 	    ipha->ipha_protocol != IPPROTO_UDP);
17433 
17434 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17435 	if (mctl_present &&
17436 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17437 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17438 
17439 		/*
17440 		 * It's an IPsec accelerated packet.
17441 		 * Keep a pointer to the data attributes around until
17442 		 * we allocate the ipsec_info_t.
17443 		 */
17444 		IPSECHW_DEBUG(IPSECHW_PKT,
17445 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17446 		hada_mp = first_mp;
17447 		hada_mp->b_cont = NULL;
17448 		/*
17449 		 * Since it is accelerated, it comes directly from
17450 		 * the ill and the data attributes is followed by
17451 		 * the packet data.
17452 		 */
17453 		ASSERT(mp->b_datap->db_type != M_CTL);
17454 		first_mp = mp;
17455 		mctl_present = B_FALSE;
17456 	}
17457 
17458 	/*
17459 	 * IF M_CTL is not present, then ipsec_in_is_secure
17460 	 * should return B_TRUE. There is a case where loopback
17461 	 * packets has an M_CTL in the front with all the
17462 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17463 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17464 	 * packets never comes here, it is safe to ASSERT the
17465 	 * following.
17466 	 */
17467 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17468 
17469 	/*
17470 	 * Also, we should never have an mctl_present if this is an
17471 	 * ESP-in-UDP packet.
17472 	 */
17473 	ASSERT(!mctl_present || !esp_in_udp_packet);
17474 
17475 	/* u1 is # words of IP options */
17476 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17477 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17478 
17479 	/*
17480 	 * Don't verify header checksum if we just removed UDP header or
17481 	 * packet is coming back from AH/ESP.
17482 	 */
17483 	if (!esp_in_udp_packet && !mctl_present) {
17484 		if (u1) {
17485 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17486 				if (hada_mp != NULL)
17487 					freemsg(hada_mp);
17488 				return;
17489 			}
17490 		} else {
17491 			/* Check the IP header checksum.  */
17492 #define	uph	((uint16_t *)ipha)
17493 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17494 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17495 #undef  uph
17496 			/* finish doing IP checksum */
17497 			sum = (sum & 0xFFFF) + (sum >> 16);
17498 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17499 			if (sum && sum != 0xFFFF) {
17500 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17501 				goto drop_pkt;
17502 			}
17503 		}
17504 	}
17505 
17506 	/*
17507 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17508 	 * might be called more than once for secure packets, count only
17509 	 * the first time.
17510 	 */
17511 	if (!mctl_present) {
17512 		UPDATE_IB_PKT_COUNT(ire);
17513 		ire->ire_last_used_time = lbolt;
17514 	}
17515 
17516 	/* Check for fragmentation offset. */
17517 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17518 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17519 	if (u1) {
17520 		/*
17521 		 * We re-assemble fragments before we do the AH/ESP
17522 		 * processing. Thus, M_CTL should not be present
17523 		 * while we are re-assembling.
17524 		 */
17525 		ASSERT(!mctl_present);
17526 		ASSERT(first_mp == mp);
17527 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17528 			return;
17529 
17530 		/*
17531 		 * Make sure that first_mp points back to mp as
17532 		 * the mp we came in with could have changed in
17533 		 * ip_rput_fragment().
17534 		 */
17535 		ipha = (ipha_t *)mp->b_rptr;
17536 		first_mp = mp;
17537 	}
17538 
17539 	/*
17540 	 * Clear hardware checksumming flag as it is currently only
17541 	 * used by TCP and UDP.
17542 	 */
17543 	DB_CKSUMFLAGS(mp) = 0;
17544 
17545 	/* Now we have a complete datagram, destined for this machine. */
17546 	u1 = IPH_HDR_LENGTH(ipha);
17547 	switch (ipha->ipha_protocol) {
17548 	case IPPROTO_ICMP: {
17549 		ire_t		*ire_zone;
17550 		ilm_t		*ilm;
17551 		mblk_t		*mp1;
17552 		zoneid_t	last_zoneid;
17553 		ilm_walker_t	ilw;
17554 
17555 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17556 			ASSERT(ire->ire_type == IRE_BROADCAST);
17557 
17558 			/*
17559 			 * In the multicast case, applications may have joined
17560 			 * the group from different zones, so we need to deliver
17561 			 * the packet to each of them. Loop through the
17562 			 * multicast memberships structures (ilm) on the receive
17563 			 * ill and send a copy of the packet up each matching
17564 			 * one. However, we don't do this for multicasts sent on
17565 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17566 			 * they must stay in the sender's zone.
17567 			 *
17568 			 * ilm_add_v6() ensures that ilms in the same zone are
17569 			 * contiguous in the ill_ilm list. We use this property
17570 			 * to avoid sending duplicates needed when two
17571 			 * applications in the same zone join the same group on
17572 			 * different logical interfaces: we ignore the ilm if
17573 			 * its zoneid is the same as the last matching one.
17574 			 * In addition, the sending of the packet for
17575 			 * ire_zoneid is delayed until all of the other ilms
17576 			 * have been exhausted.
17577 			 */
17578 			last_zoneid = -1;
17579 			ilm = ilm_walker_start(&ilw, recv_ill);
17580 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17581 				if (ipha->ipha_dst != ilm->ilm_addr ||
17582 				    ilm->ilm_zoneid == last_zoneid ||
17583 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17584 				    ilm->ilm_zoneid == ALL_ZONES ||
17585 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17586 					continue;
17587 				mp1 = ip_copymsg(first_mp);
17588 				if (mp1 == NULL)
17589 					continue;
17590 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17591 				    0, sum, mctl_present, B_TRUE,
17592 				    recv_ill, ilm->ilm_zoneid);
17593 				last_zoneid = ilm->ilm_zoneid;
17594 			}
17595 			ilm_walker_finish(&ilw);
17596 		} else if (ire->ire_type == IRE_BROADCAST) {
17597 			/*
17598 			 * In the broadcast case, there may be many zones
17599 			 * which need a copy of the packet delivered to them.
17600 			 * There is one IRE_BROADCAST per broadcast address
17601 			 * and per zone; we walk those using a helper function.
17602 			 * In addition, the sending of the packet for ire is
17603 			 * delayed until all of the other ires have been
17604 			 * processed.
17605 			 */
17606 			IRB_REFHOLD(ire->ire_bucket);
17607 			ire_zone = NULL;
17608 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17609 			    ire)) != NULL) {
17610 				mp1 = ip_copymsg(first_mp);
17611 				if (mp1 == NULL)
17612 					continue;
17613 
17614 				UPDATE_IB_PKT_COUNT(ire_zone);
17615 				ire_zone->ire_last_used_time = lbolt;
17616 				icmp_inbound(q, mp1, B_TRUE, ill,
17617 				    0, sum, mctl_present, B_TRUE,
17618 				    recv_ill, ire_zone->ire_zoneid);
17619 			}
17620 			IRB_REFRELE(ire->ire_bucket);
17621 		}
17622 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17623 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17624 		    ire->ire_zoneid);
17625 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17626 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17627 		return;
17628 	}
17629 	case IPPROTO_IGMP:
17630 		/*
17631 		 * If we are not willing to accept IGMP packets in clear,
17632 		 * then check with global policy.
17633 		 */
17634 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17635 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17636 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17637 			if (first_mp == NULL)
17638 				return;
17639 		}
17640 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17641 			freemsg(first_mp);
17642 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17643 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17644 			return;
17645 		}
17646 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17647 			/* Bad packet - discarded by igmp_input */
17648 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17649 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17650 			if (mctl_present)
17651 				freeb(first_mp);
17652 			return;
17653 		}
17654 		/*
17655 		 * igmp_input() may have returned the pulled up message.
17656 		 * So first_mp and ipha need to be reinitialized.
17657 		 */
17658 		ipha = (ipha_t *)mp->b_rptr;
17659 		if (mctl_present)
17660 			first_mp->b_cont = mp;
17661 		else
17662 			first_mp = mp;
17663 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17664 		    connf_head != NULL) {
17665 			/* No user-level listener for IGMP packets */
17666 			goto drop_pkt;
17667 		}
17668 		/* deliver to local raw users */
17669 		break;
17670 	case IPPROTO_PIM:
17671 		/*
17672 		 * If we are not willing to accept PIM packets in clear,
17673 		 * then check with global policy.
17674 		 */
17675 		if (ipst->ips_pim_accept_clear_messages == 0) {
17676 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17677 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17678 			if (first_mp == NULL)
17679 				return;
17680 		}
17681 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17682 			freemsg(first_mp);
17683 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17684 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17685 			return;
17686 		}
17687 		if (pim_input(q, mp, ill) != 0) {
17688 			/* Bad packet - discarded by pim_input */
17689 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17690 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17691 			if (mctl_present)
17692 				freeb(first_mp);
17693 			return;
17694 		}
17695 
17696 		/*
17697 		 * pim_input() may have pulled up the message so ipha needs to
17698 		 * be reinitialized.
17699 		 */
17700 		ipha = (ipha_t *)mp->b_rptr;
17701 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17702 		    connf_head != NULL) {
17703 			/* No user-level listener for PIM packets */
17704 			goto drop_pkt;
17705 		}
17706 		/* deliver to local raw users */
17707 		break;
17708 	case IPPROTO_ENCAP:
17709 		/*
17710 		 * Handle self-encapsulated packets (IP-in-IP where
17711 		 * the inner addresses == the outer addresses).
17712 		 */
17713 		hdr_length = IPH_HDR_LENGTH(ipha);
17714 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17715 		    mp->b_wptr) {
17716 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17717 			    sizeof (ipha_t) - mp->b_rptr)) {
17718 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17719 				freemsg(first_mp);
17720 				return;
17721 			}
17722 			ipha = (ipha_t *)mp->b_rptr;
17723 		}
17724 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17725 		/*
17726 		 * Check the sanity of the inner IP header.
17727 		 */
17728 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17729 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17730 			freemsg(first_mp);
17731 			return;
17732 		}
17733 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17734 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17735 			freemsg(first_mp);
17736 			return;
17737 		}
17738 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17739 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17740 			ipsec_in_t *ii;
17741 
17742 			/*
17743 			 * Self-encapsulated tunnel packet. Remove
17744 			 * the outer IP header and fanout again.
17745 			 * We also need to make sure that the inner
17746 			 * header is pulled up until options.
17747 			 */
17748 			mp->b_rptr = (uchar_t *)inner_ipha;
17749 			ipha = inner_ipha;
17750 			hdr_length = IPH_HDR_LENGTH(ipha);
17751 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17752 				if (!pullupmsg(mp, (uchar_t *)ipha +
17753 				    + hdr_length - mp->b_rptr)) {
17754 					freemsg(first_mp);
17755 					return;
17756 				}
17757 				ipha = (ipha_t *)mp->b_rptr;
17758 			}
17759 			if (hdr_length > sizeof (ipha_t)) {
17760 				/* We got options on the inner packet. */
17761 				ipaddr_t dst = ipha->ipha_dst;
17762 
17763 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17764 				    -1) {
17765 					/* Bad options! */
17766 					return;
17767 				}
17768 				if (dst != ipha->ipha_dst) {
17769 					/*
17770 					 * Someone put a source-route in
17771 					 * the inside header of a self-
17772 					 * encapsulated packet.  Drop it
17773 					 * with extreme prejudice and let
17774 					 * the sender know.
17775 					 */
17776 					icmp_unreachable(q, first_mp,
17777 					    ICMP_SOURCE_ROUTE_FAILED,
17778 					    recv_ill->ill_zoneid, ipst);
17779 					return;
17780 				}
17781 			}
17782 			if (!mctl_present) {
17783 				ASSERT(first_mp == mp);
17784 				/*
17785 				 * This means that somebody is sending
17786 				 * Self-encapsualted packets without AH/ESP.
17787 				 * If AH/ESP was present, we would have already
17788 				 * allocated the first_mp.
17789 				 *
17790 				 * Send this packet to find a tunnel endpoint.
17791 				 * if I can't find one, an ICMP
17792 				 * PROTOCOL_UNREACHABLE will get sent.
17793 				 */
17794 				goto fanout;
17795 			}
17796 			/*
17797 			 * We generally store the ill_index if we need to
17798 			 * do IPsec processing as we lose the ill queue when
17799 			 * we come back. But in this case, we never should
17800 			 * have to store the ill_index here as it should have
17801 			 * been stored previously when we processed the
17802 			 * AH/ESP header in this routine or for non-ipsec
17803 			 * cases, we still have the queue. But for some bad
17804 			 * packets from the wire, we can get to IPsec after
17805 			 * this and we better store the index for that case.
17806 			 */
17807 			ill = (ill_t *)q->q_ptr;
17808 			ii = (ipsec_in_t *)first_mp->b_rptr;
17809 			ii->ipsec_in_ill_index =
17810 			    ill->ill_phyint->phyint_ifindex;
17811 			ii->ipsec_in_rill_index =
17812 			    recv_ill->ill_phyint->phyint_ifindex;
17813 			if (ii->ipsec_in_decaps) {
17814 				/*
17815 				 * This packet is self-encapsulated multiple
17816 				 * times. We don't want to recurse infinitely.
17817 				 * To keep it simple, drop the packet.
17818 				 */
17819 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17820 				freemsg(first_mp);
17821 				return;
17822 			}
17823 			ii->ipsec_in_decaps = B_TRUE;
17824 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17825 			    ire);
17826 			return;
17827 		}
17828 		break;
17829 	case IPPROTO_AH:
17830 	case IPPROTO_ESP: {
17831 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17832 
17833 		/*
17834 		 * Fast path for AH/ESP. If this is the first time
17835 		 * we are sending a datagram to AH/ESP, allocate
17836 		 * a IPSEC_IN message and prepend it. Otherwise,
17837 		 * just fanout.
17838 		 */
17839 
17840 		int ipsec_rc;
17841 		ipsec_in_t *ii;
17842 		netstack_t *ns = ipst->ips_netstack;
17843 
17844 		IP_STAT(ipst, ipsec_proto_ahesp);
17845 		if (!mctl_present) {
17846 			ASSERT(first_mp == mp);
17847 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17848 			if (first_mp == NULL) {
17849 				ip1dbg(("ip_proto_input: IPSEC_IN "
17850 				    "allocation failure.\n"));
17851 				freemsg(hada_mp); /* okay ifnull */
17852 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17853 				freemsg(mp);
17854 				return;
17855 			}
17856 			/*
17857 			 * Store the ill_index so that when we come back
17858 			 * from IPsec we ride on the same queue.
17859 			 */
17860 			ill = (ill_t *)q->q_ptr;
17861 			ii = (ipsec_in_t *)first_mp->b_rptr;
17862 			ii->ipsec_in_ill_index =
17863 			    ill->ill_phyint->phyint_ifindex;
17864 			ii->ipsec_in_rill_index =
17865 			    recv_ill->ill_phyint->phyint_ifindex;
17866 			first_mp->b_cont = mp;
17867 			/*
17868 			 * Cache hardware acceleration info.
17869 			 */
17870 			if (hada_mp != NULL) {
17871 				IPSECHW_DEBUG(IPSECHW_PKT,
17872 				    ("ip_rput_local: caching data attr.\n"));
17873 				ii->ipsec_in_accelerated = B_TRUE;
17874 				ii->ipsec_in_da = hada_mp;
17875 				hada_mp = NULL;
17876 			}
17877 		} else {
17878 			ii = (ipsec_in_t *)first_mp->b_rptr;
17879 		}
17880 
17881 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17882 
17883 		if (!ipsec_loaded(ipss)) {
17884 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17885 			    ire->ire_zoneid, ipst);
17886 			return;
17887 		}
17888 
17889 		ns = ipst->ips_netstack;
17890 		/* select inbound SA and have IPsec process the pkt */
17891 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17892 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17893 			boolean_t esp_in_udp_sa;
17894 			if (esph == NULL)
17895 				return;
17896 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17897 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17898 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17899 			    IPSA_F_NATT) != 0);
17900 			/*
17901 			 * The following is a fancy, but quick, way of saying:
17902 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17903 			 *    OR
17904 			 * ESP SA and ESP-in-UDP packet --> drop
17905 			 */
17906 			if (esp_in_udp_sa != esp_in_udp_packet) {
17907 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17908 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17909 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17910 				    &ns->netstack_ipsec->ipsec_dropper);
17911 				return;
17912 			}
17913 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17914 			    first_mp, esph);
17915 		} else {
17916 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17917 			if (ah == NULL)
17918 				return;
17919 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17920 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17921 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17922 			    first_mp, ah);
17923 		}
17924 
17925 		switch (ipsec_rc) {
17926 		case IPSEC_STATUS_SUCCESS:
17927 			break;
17928 		case IPSEC_STATUS_FAILED:
17929 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17930 			/* FALLTHRU */
17931 		case IPSEC_STATUS_PENDING:
17932 			return;
17933 		}
17934 		/* we're done with IPsec processing, send it up */
17935 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17936 		return;
17937 	}
17938 	default:
17939 		break;
17940 	}
17941 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17942 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17943 		    ire->ire_zoneid));
17944 		goto drop_pkt;
17945 	}
17946 	/*
17947 	 * Handle protocols with which IP is less intimate.  There
17948 	 * can be more than one stream bound to a particular
17949 	 * protocol.  When this is the case, each one gets a copy
17950 	 * of any incoming packets.
17951 	 */
17952 fanout:
17953 	ip_fanout_proto(q, first_mp, ill, ipha,
17954 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17955 	    B_TRUE, recv_ill, ire->ire_zoneid);
17956 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17957 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17958 	return;
17959 
17960 drop_pkt:
17961 	freemsg(first_mp);
17962 	if (hada_mp != NULL)
17963 		freeb(hada_mp);
17964 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17965 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17966 #undef	rptr
17967 #undef  iphs
17968 
17969 }
17970 
17971 /*
17972  * Update any source route, record route or timestamp options.
17973  * Check that we are at end of strict source route.
17974  * The options have already been checked for sanity in ip_rput_options().
17975  */
17976 static boolean_t
17977 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17978     ip_stack_t *ipst)
17979 {
17980 	ipoptp_t	opts;
17981 	uchar_t		*opt;
17982 	uint8_t		optval;
17983 	uint8_t		optlen;
17984 	ipaddr_t	dst;
17985 	uint32_t	ts;
17986 	ire_t		*dst_ire;
17987 	timestruc_t	now;
17988 	zoneid_t	zoneid;
17989 	ill_t		*ill;
17990 
17991 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17992 
17993 	ip2dbg(("ip_rput_local_options\n"));
17994 
17995 	for (optval = ipoptp_first(&opts, ipha);
17996 	    optval != IPOPT_EOL;
17997 	    optval = ipoptp_next(&opts)) {
17998 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17999 		opt = opts.ipoptp_cur;
18000 		optlen = opts.ipoptp_len;
18001 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18002 		    optval, optlen));
18003 		switch (optval) {
18004 			uint32_t off;
18005 		case IPOPT_SSRR:
18006 		case IPOPT_LSRR:
18007 			off = opt[IPOPT_OFFSET];
18008 			off--;
18009 			if (optlen < IP_ADDR_LEN ||
18010 			    off > optlen - IP_ADDR_LEN) {
18011 				/* End of source route */
18012 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18013 				break;
18014 			}
18015 			/*
18016 			 * This will only happen if two consecutive entries
18017 			 * in the source route contains our address or if
18018 			 * it is a packet with a loose source route which
18019 			 * reaches us before consuming the whole source route
18020 			 */
18021 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18022 			if (optval == IPOPT_SSRR) {
18023 				goto bad_src_route;
18024 			}
18025 			/*
18026 			 * Hack: instead of dropping the packet truncate the
18027 			 * source route to what has been used by filling the
18028 			 * rest with IPOPT_NOP.
18029 			 */
18030 			opt[IPOPT_OLEN] = (uint8_t)off;
18031 			while (off < optlen) {
18032 				opt[off++] = IPOPT_NOP;
18033 			}
18034 			break;
18035 		case IPOPT_RR:
18036 			off = opt[IPOPT_OFFSET];
18037 			off--;
18038 			if (optlen < IP_ADDR_LEN ||
18039 			    off > optlen - IP_ADDR_LEN) {
18040 				/* No more room - ignore */
18041 				ip1dbg((
18042 				    "ip_rput_local_options: end of RR\n"));
18043 				break;
18044 			}
18045 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18046 			    IP_ADDR_LEN);
18047 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18048 			break;
18049 		case IPOPT_TS:
18050 			/* Insert timestamp if there is romm */
18051 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18052 			case IPOPT_TS_TSONLY:
18053 				off = IPOPT_TS_TIMELEN;
18054 				break;
18055 			case IPOPT_TS_PRESPEC:
18056 			case IPOPT_TS_PRESPEC_RFC791:
18057 				/* Verify that the address matched */
18058 				off = opt[IPOPT_OFFSET] - 1;
18059 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18060 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18061 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18062 				    ipst);
18063 				if (dst_ire == NULL) {
18064 					/* Not for us */
18065 					break;
18066 				}
18067 				ire_refrele(dst_ire);
18068 				/* FALLTHRU */
18069 			case IPOPT_TS_TSANDADDR:
18070 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18071 				break;
18072 			default:
18073 				/*
18074 				 * ip_*put_options should have already
18075 				 * dropped this packet.
18076 				 */
18077 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18078 				    "unknown IT - bug in ip_rput_options?\n");
18079 				return (B_TRUE);	/* Keep "lint" happy */
18080 			}
18081 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18082 				/* Increase overflow counter */
18083 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18084 				opt[IPOPT_POS_OV_FLG] =
18085 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18086 				    (off << 4));
18087 				break;
18088 			}
18089 			off = opt[IPOPT_OFFSET] - 1;
18090 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18091 			case IPOPT_TS_PRESPEC:
18092 			case IPOPT_TS_PRESPEC_RFC791:
18093 			case IPOPT_TS_TSANDADDR:
18094 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18095 				    IP_ADDR_LEN);
18096 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18097 				/* FALLTHRU */
18098 			case IPOPT_TS_TSONLY:
18099 				off = opt[IPOPT_OFFSET] - 1;
18100 				/* Compute # of milliseconds since midnight */
18101 				gethrestime(&now);
18102 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18103 				    now.tv_nsec / (NANOSEC / MILLISEC);
18104 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18105 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18106 				break;
18107 			}
18108 			break;
18109 		}
18110 	}
18111 	return (B_TRUE);
18112 
18113 bad_src_route:
18114 	q = WR(q);
18115 	if (q->q_next != NULL)
18116 		ill = q->q_ptr;
18117 	else
18118 		ill = NULL;
18119 
18120 	/* make sure we clear any indication of a hardware checksum */
18121 	DB_CKSUMFLAGS(mp) = 0;
18122 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18123 	if (zoneid == ALL_ZONES)
18124 		freemsg(mp);
18125 	else
18126 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18127 	return (B_FALSE);
18128 
18129 }
18130 
18131 /*
18132  * Process IP options in an inbound packet.  If an option affects the
18133  * effective destination address, return the next hop address via dstp.
18134  * Returns -1 if something fails in which case an ICMP error has been sent
18135  * and mp freed.
18136  */
18137 static int
18138 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18139     ip_stack_t *ipst)
18140 {
18141 	ipoptp_t	opts;
18142 	uchar_t		*opt;
18143 	uint8_t		optval;
18144 	uint8_t		optlen;
18145 	ipaddr_t	dst;
18146 	intptr_t	code = 0;
18147 	ire_t		*ire = NULL;
18148 	zoneid_t	zoneid;
18149 	ill_t		*ill;
18150 
18151 	ip2dbg(("ip_rput_options\n"));
18152 	dst = ipha->ipha_dst;
18153 	for (optval = ipoptp_first(&opts, ipha);
18154 	    optval != IPOPT_EOL;
18155 	    optval = ipoptp_next(&opts)) {
18156 		opt = opts.ipoptp_cur;
18157 		optlen = opts.ipoptp_len;
18158 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18159 		    optval, optlen));
18160 		/*
18161 		 * Note: we need to verify the checksum before we
18162 		 * modify anything thus this routine only extracts the next
18163 		 * hop dst from any source route.
18164 		 */
18165 		switch (optval) {
18166 			uint32_t off;
18167 		case IPOPT_SSRR:
18168 		case IPOPT_LSRR:
18169 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18170 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18171 			if (ire == NULL) {
18172 				if (optval == IPOPT_SSRR) {
18173 					ip1dbg(("ip_rput_options: not next"
18174 					    " strict source route 0x%x\n",
18175 					    ntohl(dst)));
18176 					code = (char *)&ipha->ipha_dst -
18177 					    (char *)ipha;
18178 					goto param_prob; /* RouterReq's */
18179 				}
18180 				ip2dbg(("ip_rput_options: "
18181 				    "not next source route 0x%x\n",
18182 				    ntohl(dst)));
18183 				break;
18184 			}
18185 			ire_refrele(ire);
18186 
18187 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18188 				ip1dbg((
18189 				    "ip_rput_options: bad option offset\n"));
18190 				code = (char *)&opt[IPOPT_OLEN] -
18191 				    (char *)ipha;
18192 				goto param_prob;
18193 			}
18194 			off = opt[IPOPT_OFFSET];
18195 			off--;
18196 		redo_srr:
18197 			if (optlen < IP_ADDR_LEN ||
18198 			    off > optlen - IP_ADDR_LEN) {
18199 				/* End of source route */
18200 				ip1dbg(("ip_rput_options: end of SR\n"));
18201 				break;
18202 			}
18203 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18204 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18205 			    ntohl(dst)));
18206 
18207 			/*
18208 			 * Check if our address is present more than
18209 			 * once as consecutive hops in source route.
18210 			 * XXX verify per-interface ip_forwarding
18211 			 * for source route?
18212 			 */
18213 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18214 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18215 
18216 			if (ire != NULL) {
18217 				ire_refrele(ire);
18218 				off += IP_ADDR_LEN;
18219 				goto redo_srr;
18220 			}
18221 
18222 			if (dst == htonl(INADDR_LOOPBACK)) {
18223 				ip1dbg(("ip_rput_options: loopback addr in "
18224 				    "source route!\n"));
18225 				goto bad_src_route;
18226 			}
18227 			/*
18228 			 * For strict: verify that dst is directly
18229 			 * reachable.
18230 			 */
18231 			if (optval == IPOPT_SSRR) {
18232 				ire = ire_ftable_lookup(dst, 0, 0,
18233 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18234 				    msg_getlabel(mp),
18235 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18236 				if (ire == NULL) {
18237 					ip1dbg(("ip_rput_options: SSRR not "
18238 					    "directly reachable: 0x%x\n",
18239 					    ntohl(dst)));
18240 					goto bad_src_route;
18241 				}
18242 				ire_refrele(ire);
18243 			}
18244 			/*
18245 			 * Defer update of the offset and the record route
18246 			 * until the packet is forwarded.
18247 			 */
18248 			break;
18249 		case IPOPT_RR:
18250 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18251 				ip1dbg((
18252 				    "ip_rput_options: bad option offset\n"));
18253 				code = (char *)&opt[IPOPT_OLEN] -
18254 				    (char *)ipha;
18255 				goto param_prob;
18256 			}
18257 			break;
18258 		case IPOPT_TS:
18259 			/*
18260 			 * Verify that length >= 5 and that there is either
18261 			 * room for another timestamp or that the overflow
18262 			 * counter is not maxed out.
18263 			 */
18264 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18265 			if (optlen < IPOPT_MINLEN_IT) {
18266 				goto param_prob;
18267 			}
18268 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18269 				ip1dbg((
18270 				    "ip_rput_options: bad option offset\n"));
18271 				code = (char *)&opt[IPOPT_OFFSET] -
18272 				    (char *)ipha;
18273 				goto param_prob;
18274 			}
18275 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18276 			case IPOPT_TS_TSONLY:
18277 				off = IPOPT_TS_TIMELEN;
18278 				break;
18279 			case IPOPT_TS_TSANDADDR:
18280 			case IPOPT_TS_PRESPEC:
18281 			case IPOPT_TS_PRESPEC_RFC791:
18282 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18283 				break;
18284 			default:
18285 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18286 				    (char *)ipha;
18287 				goto param_prob;
18288 			}
18289 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18290 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18291 				/*
18292 				 * No room and the overflow counter is 15
18293 				 * already.
18294 				 */
18295 				goto param_prob;
18296 			}
18297 			break;
18298 		}
18299 	}
18300 
18301 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18302 		*dstp = dst;
18303 		return (0);
18304 	}
18305 
18306 	ip1dbg(("ip_rput_options: error processing IP options."));
18307 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18308 
18309 param_prob:
18310 	q = WR(q);
18311 	if (q->q_next != NULL)
18312 		ill = q->q_ptr;
18313 	else
18314 		ill = NULL;
18315 
18316 	/* make sure we clear any indication of a hardware checksum */
18317 	DB_CKSUMFLAGS(mp) = 0;
18318 	/* Don't know whether this is for non-global or global/forwarding */
18319 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18320 	if (zoneid == ALL_ZONES)
18321 		freemsg(mp);
18322 	else
18323 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18324 	return (-1);
18325 
18326 bad_src_route:
18327 	q = WR(q);
18328 	if (q->q_next != NULL)
18329 		ill = q->q_ptr;
18330 	else
18331 		ill = NULL;
18332 
18333 	/* make sure we clear any indication of a hardware checksum */
18334 	DB_CKSUMFLAGS(mp) = 0;
18335 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18336 	if (zoneid == ALL_ZONES)
18337 		freemsg(mp);
18338 	else
18339 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18340 	return (-1);
18341 }
18342 
18343 /*
18344  * IP & ICMP info in >=14 msg's ...
18345  *  - ip fixed part (mib2_ip_t)
18346  *  - icmp fixed part (mib2_icmp_t)
18347  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18348  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18349  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18350  *  - ipRouteAttributeTable (ip 102)	labeled routes
18351  *  - ip multicast membership (ip_member_t)
18352  *  - ip multicast source filtering (ip_grpsrc_t)
18353  *  - igmp fixed part (struct igmpstat)
18354  *  - multicast routing stats (struct mrtstat)
18355  *  - multicast routing vifs (array of struct vifctl)
18356  *  - multicast routing routes (array of struct mfcctl)
18357  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18358  *					One per ill plus one generic
18359  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18360  *					One per ill plus one generic
18361  *  - ipv6RouteEntry			all IPv6 IREs
18362  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18363  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18364  *  - ipv6AddrEntry			all IPv6 ipifs
18365  *  - ipv6 multicast membership (ipv6_member_t)
18366  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18367  *
18368  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18369  *
18370  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18371  * already filled in by the caller.
18372  * Return value of 0 indicates that no messages were sent and caller
18373  * should free mpctl.
18374  */
18375 int
18376 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18377 {
18378 	ip_stack_t *ipst;
18379 	sctp_stack_t *sctps;
18380 
18381 	if (q->q_next != NULL) {
18382 		ipst = ILLQ_TO_IPST(q);
18383 	} else {
18384 		ipst = CONNQ_TO_IPST(q);
18385 	}
18386 	ASSERT(ipst != NULL);
18387 	sctps = ipst->ips_netstack->netstack_sctp;
18388 
18389 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18390 		return (0);
18391 	}
18392 
18393 	/*
18394 	 * For the purposes of the (broken) packet shell use
18395 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18396 	 * to make TCP and UDP appear first in the list of mib items.
18397 	 * TBD: We could expand this and use it in netstat so that
18398 	 * the kernel doesn't have to produce large tables (connections,
18399 	 * routes, etc) when netstat only wants the statistics or a particular
18400 	 * table.
18401 	 */
18402 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18403 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18404 			return (1);
18405 		}
18406 	}
18407 
18408 	if (level != MIB2_TCP) {
18409 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18410 			return (1);
18411 		}
18412 	}
18413 
18414 	if (level != MIB2_UDP) {
18415 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18416 			return (1);
18417 		}
18418 	}
18419 
18420 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18421 	    ipst)) == NULL) {
18422 		return (1);
18423 	}
18424 
18425 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18426 		return (1);
18427 	}
18428 
18429 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18430 		return (1);
18431 	}
18432 
18433 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18434 		return (1);
18435 	}
18436 
18437 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18438 		return (1);
18439 	}
18440 
18441 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18442 		return (1);
18443 	}
18444 
18445 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18446 		return (1);
18447 	}
18448 
18449 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18450 		return (1);
18451 	}
18452 
18453 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18454 		return (1);
18455 	}
18456 
18457 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18458 		return (1);
18459 	}
18460 
18461 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18462 		return (1);
18463 	}
18464 
18465 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18466 		return (1);
18467 	}
18468 
18469 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18470 		return (1);
18471 	}
18472 
18473 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18474 		return (1);
18475 	}
18476 
18477 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18478 	if (mpctl == NULL)
18479 		return (1);
18480 
18481 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18482 	if (mpctl == NULL)
18483 		return (1);
18484 
18485 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18486 		return (1);
18487 	}
18488 	freemsg(mpctl);
18489 	return (1);
18490 }
18491 
18492 /* Get global (legacy) IPv4 statistics */
18493 static mblk_t *
18494 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18495     ip_stack_t *ipst)
18496 {
18497 	mib2_ip_t		old_ip_mib;
18498 	struct opthdr		*optp;
18499 	mblk_t			*mp2ctl;
18500 
18501 	/*
18502 	 * make a copy of the original message
18503 	 */
18504 	mp2ctl = copymsg(mpctl);
18505 
18506 	/* fixed length IP structure... */
18507 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18508 	optp->level = MIB2_IP;
18509 	optp->name = 0;
18510 	SET_MIB(old_ip_mib.ipForwarding,
18511 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18512 	SET_MIB(old_ip_mib.ipDefaultTTL,
18513 	    (uint32_t)ipst->ips_ip_def_ttl);
18514 	SET_MIB(old_ip_mib.ipReasmTimeout,
18515 	    ipst->ips_ip_g_frag_timeout);
18516 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18517 	    sizeof (mib2_ipAddrEntry_t));
18518 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18519 	    sizeof (mib2_ipRouteEntry_t));
18520 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18521 	    sizeof (mib2_ipNetToMediaEntry_t));
18522 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18523 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18524 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18525 	    sizeof (mib2_ipAttributeEntry_t));
18526 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18527 
18528 	/*
18529 	 * Grab the statistics from the new IP MIB
18530 	 */
18531 	SET_MIB(old_ip_mib.ipInReceives,
18532 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18533 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18534 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18535 	SET_MIB(old_ip_mib.ipForwDatagrams,
18536 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18537 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18538 	    ipmib->ipIfStatsInUnknownProtos);
18539 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18540 	SET_MIB(old_ip_mib.ipInDelivers,
18541 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18542 	SET_MIB(old_ip_mib.ipOutRequests,
18543 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18544 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18545 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18546 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18547 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18548 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18549 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18550 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18551 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18552 
18553 	/* ipRoutingDiscards is not being used */
18554 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18555 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18556 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18557 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18558 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18559 	    ipmib->ipIfStatsReasmDuplicates);
18560 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18561 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18562 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18563 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18564 	SET_MIB(old_ip_mib.rawipInOverflows,
18565 	    ipmib->rawipIfStatsInOverflows);
18566 
18567 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18568 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18569 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18570 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18571 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18572 	    ipmib->ipIfStatsOutSwitchIPVersion);
18573 
18574 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18575 	    (int)sizeof (old_ip_mib))) {
18576 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18577 		    (uint_t)sizeof (old_ip_mib)));
18578 	}
18579 
18580 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18581 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18582 	    (int)optp->level, (int)optp->name, (int)optp->len));
18583 	qreply(q, mpctl);
18584 	return (mp2ctl);
18585 }
18586 
18587 /* Per interface IPv4 statistics */
18588 static mblk_t *
18589 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18590 {
18591 	struct opthdr		*optp;
18592 	mblk_t			*mp2ctl;
18593 	ill_t			*ill;
18594 	ill_walk_context_t	ctx;
18595 	mblk_t			*mp_tail = NULL;
18596 	mib2_ipIfStatsEntry_t	global_ip_mib;
18597 
18598 	/*
18599 	 * Make a copy of the original message
18600 	 */
18601 	mp2ctl = copymsg(mpctl);
18602 
18603 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18604 	optp->level = MIB2_IP;
18605 	optp->name = MIB2_IP_TRAFFIC_STATS;
18606 	/* Include "unknown interface" ip_mib */
18607 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18608 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18609 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18610 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18611 	    (ipst->ips_ip_g_forward ? 1 : 2));
18612 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18613 	    (uint32_t)ipst->ips_ip_def_ttl);
18614 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18615 	    sizeof (mib2_ipIfStatsEntry_t));
18616 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18617 	    sizeof (mib2_ipAddrEntry_t));
18618 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18619 	    sizeof (mib2_ipRouteEntry_t));
18620 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18621 	    sizeof (mib2_ipNetToMediaEntry_t));
18622 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18623 	    sizeof (ip_member_t));
18624 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18625 	    sizeof (ip_grpsrc_t));
18626 
18627 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18628 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18629 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18630 		    "failed to allocate %u bytes\n",
18631 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18632 	}
18633 
18634 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18635 
18636 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18637 	ill = ILL_START_WALK_V4(&ctx, ipst);
18638 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18639 		ill->ill_ip_mib->ipIfStatsIfIndex =
18640 		    ill->ill_phyint->phyint_ifindex;
18641 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18642 		    (ipst->ips_ip_g_forward ? 1 : 2));
18643 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18644 		    (uint32_t)ipst->ips_ip_def_ttl);
18645 
18646 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18647 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18648 		    (char *)ill->ill_ip_mib,
18649 		    (int)sizeof (*ill->ill_ip_mib))) {
18650 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18651 			    "failed to allocate %u bytes\n",
18652 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18653 		}
18654 	}
18655 	rw_exit(&ipst->ips_ill_g_lock);
18656 
18657 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18658 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18659 	    "level %d, name %d, len %d\n",
18660 	    (int)optp->level, (int)optp->name, (int)optp->len));
18661 	qreply(q, mpctl);
18662 
18663 	if (mp2ctl == NULL)
18664 		return (NULL);
18665 
18666 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18667 }
18668 
18669 /* Global IPv4 ICMP statistics */
18670 static mblk_t *
18671 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18672 {
18673 	struct opthdr		*optp;
18674 	mblk_t			*mp2ctl;
18675 
18676 	/*
18677 	 * Make a copy of the original message
18678 	 */
18679 	mp2ctl = copymsg(mpctl);
18680 
18681 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18682 	optp->level = MIB2_ICMP;
18683 	optp->name = 0;
18684 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18685 	    (int)sizeof (ipst->ips_icmp_mib))) {
18686 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18687 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18688 	}
18689 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18690 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18691 	    (int)optp->level, (int)optp->name, (int)optp->len));
18692 	qreply(q, mpctl);
18693 	return (mp2ctl);
18694 }
18695 
18696 /* Global IPv4 IGMP statistics */
18697 static mblk_t *
18698 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18699 {
18700 	struct opthdr		*optp;
18701 	mblk_t			*mp2ctl;
18702 
18703 	/*
18704 	 * make a copy of the original message
18705 	 */
18706 	mp2ctl = copymsg(mpctl);
18707 
18708 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18709 	optp->level = EXPER_IGMP;
18710 	optp->name = 0;
18711 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18712 	    (int)sizeof (ipst->ips_igmpstat))) {
18713 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18714 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18715 	}
18716 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18717 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18718 	    (int)optp->level, (int)optp->name, (int)optp->len));
18719 	qreply(q, mpctl);
18720 	return (mp2ctl);
18721 }
18722 
18723 /* Global IPv4 Multicast Routing statistics */
18724 static mblk_t *
18725 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18726 {
18727 	struct opthdr		*optp;
18728 	mblk_t			*mp2ctl;
18729 
18730 	/*
18731 	 * make a copy of the original message
18732 	 */
18733 	mp2ctl = copymsg(mpctl);
18734 
18735 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18736 	optp->level = EXPER_DVMRP;
18737 	optp->name = 0;
18738 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18739 		ip0dbg(("ip_mroute_stats: failed\n"));
18740 	}
18741 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18742 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18743 	    (int)optp->level, (int)optp->name, (int)optp->len));
18744 	qreply(q, mpctl);
18745 	return (mp2ctl);
18746 }
18747 
18748 /* IPv4 address information */
18749 static mblk_t *
18750 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18751 {
18752 	struct opthdr		*optp;
18753 	mblk_t			*mp2ctl;
18754 	mblk_t			*mp_tail = NULL;
18755 	ill_t			*ill;
18756 	ipif_t			*ipif;
18757 	uint_t			bitval;
18758 	mib2_ipAddrEntry_t	mae;
18759 	zoneid_t		zoneid;
18760 	ill_walk_context_t ctx;
18761 
18762 	/*
18763 	 * make a copy of the original message
18764 	 */
18765 	mp2ctl = copymsg(mpctl);
18766 
18767 	/* ipAddrEntryTable */
18768 
18769 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18770 	optp->level = MIB2_IP;
18771 	optp->name = MIB2_IP_ADDR;
18772 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18773 
18774 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18775 	ill = ILL_START_WALK_V4(&ctx, ipst);
18776 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18777 		for (ipif = ill->ill_ipif; ipif != NULL;
18778 		    ipif = ipif->ipif_next) {
18779 			if (ipif->ipif_zoneid != zoneid &&
18780 			    ipif->ipif_zoneid != ALL_ZONES)
18781 				continue;
18782 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18783 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18784 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18785 
18786 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18787 			    OCTET_LENGTH);
18788 			mae.ipAdEntIfIndex.o_length =
18789 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18790 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18791 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18792 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18793 			mae.ipAdEntInfo.ae_subnet_len =
18794 			    ip_mask_to_plen(ipif->ipif_net_mask);
18795 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18796 			for (bitval = 1;
18797 			    bitval &&
18798 			    !(bitval & ipif->ipif_brd_addr);
18799 			    bitval <<= 1)
18800 				noop;
18801 			mae.ipAdEntBcastAddr = bitval;
18802 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18803 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18804 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18805 			mae.ipAdEntInfo.ae_broadcast_addr =
18806 			    ipif->ipif_brd_addr;
18807 			mae.ipAdEntInfo.ae_pp_dst_addr =
18808 			    ipif->ipif_pp_dst_addr;
18809 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18810 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18811 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18812 
18813 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18814 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18815 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18816 				    "allocate %u bytes\n",
18817 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18818 			}
18819 		}
18820 	}
18821 	rw_exit(&ipst->ips_ill_g_lock);
18822 
18823 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18824 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18825 	    (int)optp->level, (int)optp->name, (int)optp->len));
18826 	qreply(q, mpctl);
18827 	return (mp2ctl);
18828 }
18829 
18830 /* IPv6 address information */
18831 static mblk_t *
18832 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18833 {
18834 	struct opthdr		*optp;
18835 	mblk_t			*mp2ctl;
18836 	mblk_t			*mp_tail = NULL;
18837 	ill_t			*ill;
18838 	ipif_t			*ipif;
18839 	mib2_ipv6AddrEntry_t	mae6;
18840 	zoneid_t		zoneid;
18841 	ill_walk_context_t	ctx;
18842 
18843 	/*
18844 	 * make a copy of the original message
18845 	 */
18846 	mp2ctl = copymsg(mpctl);
18847 
18848 	/* ipv6AddrEntryTable */
18849 
18850 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18851 	optp->level = MIB2_IP6;
18852 	optp->name = MIB2_IP6_ADDR;
18853 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18854 
18855 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18856 	ill = ILL_START_WALK_V6(&ctx, ipst);
18857 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18858 		for (ipif = ill->ill_ipif; ipif != NULL;
18859 		    ipif = ipif->ipif_next) {
18860 			if (ipif->ipif_zoneid != zoneid &&
18861 			    ipif->ipif_zoneid != ALL_ZONES)
18862 				continue;
18863 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18864 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18865 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18866 
18867 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18868 			    OCTET_LENGTH);
18869 			mae6.ipv6AddrIfIndex.o_length =
18870 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18871 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18872 			mae6.ipv6AddrPfxLength =
18873 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18874 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18875 			mae6.ipv6AddrInfo.ae_subnet_len =
18876 			    mae6.ipv6AddrPfxLength;
18877 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18878 
18879 			/* Type: stateless(1), stateful(2), unknown(3) */
18880 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18881 				mae6.ipv6AddrType = 1;
18882 			else
18883 				mae6.ipv6AddrType = 2;
18884 			/* Anycast: true(1), false(2) */
18885 			if (ipif->ipif_flags & IPIF_ANYCAST)
18886 				mae6.ipv6AddrAnycastFlag = 1;
18887 			else
18888 				mae6.ipv6AddrAnycastFlag = 2;
18889 
18890 			/*
18891 			 * Address status: preferred(1), deprecated(2),
18892 			 * invalid(3), inaccessible(4), unknown(5)
18893 			 */
18894 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18895 				mae6.ipv6AddrStatus = 3;
18896 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18897 				mae6.ipv6AddrStatus = 2;
18898 			else
18899 				mae6.ipv6AddrStatus = 1;
18900 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18901 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18902 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18903 			    ipif->ipif_v6pp_dst_addr;
18904 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18905 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18906 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18907 			mae6.ipv6AddrIdentifier = ill->ill_token;
18908 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18909 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18910 			mae6.ipv6AddrRetransmitTime =
18911 			    ill->ill_reachable_retrans_time;
18912 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18913 			    (char *)&mae6,
18914 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18915 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18916 				    "allocate %u bytes\n",
18917 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18918 			}
18919 		}
18920 	}
18921 	rw_exit(&ipst->ips_ill_g_lock);
18922 
18923 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18924 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18925 	    (int)optp->level, (int)optp->name, (int)optp->len));
18926 	qreply(q, mpctl);
18927 	return (mp2ctl);
18928 }
18929 
18930 /* IPv4 multicast group membership. */
18931 static mblk_t *
18932 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18933 {
18934 	struct opthdr		*optp;
18935 	mblk_t			*mp2ctl;
18936 	ill_t			*ill;
18937 	ipif_t			*ipif;
18938 	ilm_t			*ilm;
18939 	ip_member_t		ipm;
18940 	mblk_t			*mp_tail = NULL;
18941 	ill_walk_context_t	ctx;
18942 	zoneid_t		zoneid;
18943 	ilm_walker_t		ilw;
18944 
18945 	/*
18946 	 * make a copy of the original message
18947 	 */
18948 	mp2ctl = copymsg(mpctl);
18949 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18950 
18951 	/* ipGroupMember table */
18952 	optp = (struct opthdr *)&mpctl->b_rptr[
18953 	    sizeof (struct T_optmgmt_ack)];
18954 	optp->level = MIB2_IP;
18955 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18956 
18957 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18958 	ill = ILL_START_WALK_V4(&ctx, ipst);
18959 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18960 		if (IS_UNDER_IPMP(ill))
18961 			continue;
18962 
18963 		ilm = ilm_walker_start(&ilw, ill);
18964 		for (ipif = ill->ill_ipif; ipif != NULL;
18965 		    ipif = ipif->ipif_next) {
18966 			if (ipif->ipif_zoneid != zoneid &&
18967 			    ipif->ipif_zoneid != ALL_ZONES)
18968 				continue;	/* not this zone */
18969 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18970 			    OCTET_LENGTH);
18971 			ipm.ipGroupMemberIfIndex.o_length =
18972 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18973 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18974 				ASSERT(ilm->ilm_ipif != NULL);
18975 				ASSERT(ilm->ilm_ill == NULL);
18976 				if (ilm->ilm_ipif != ipif)
18977 					continue;
18978 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18979 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18980 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18981 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18982 				    (char *)&ipm, (int)sizeof (ipm))) {
18983 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18984 					    "failed to allocate %u bytes\n",
18985 					    (uint_t)sizeof (ipm)));
18986 				}
18987 			}
18988 		}
18989 		ilm_walker_finish(&ilw);
18990 	}
18991 	rw_exit(&ipst->ips_ill_g_lock);
18992 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18993 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18994 	    (int)optp->level, (int)optp->name, (int)optp->len));
18995 	qreply(q, mpctl);
18996 	return (mp2ctl);
18997 }
18998 
18999 /* IPv6 multicast group membership. */
19000 static mblk_t *
19001 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19002 {
19003 	struct opthdr		*optp;
19004 	mblk_t			*mp2ctl;
19005 	ill_t			*ill;
19006 	ilm_t			*ilm;
19007 	ipv6_member_t		ipm6;
19008 	mblk_t			*mp_tail = NULL;
19009 	ill_walk_context_t	ctx;
19010 	zoneid_t		zoneid;
19011 	ilm_walker_t		ilw;
19012 
19013 	/*
19014 	 * make a copy of the original message
19015 	 */
19016 	mp2ctl = copymsg(mpctl);
19017 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19018 
19019 	/* ip6GroupMember table */
19020 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19021 	optp->level = MIB2_IP6;
19022 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19023 
19024 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19025 	ill = ILL_START_WALK_V6(&ctx, ipst);
19026 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19027 		if (IS_UNDER_IPMP(ill))
19028 			continue;
19029 
19030 		ilm = ilm_walker_start(&ilw, ill);
19031 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19032 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19033 			ASSERT(ilm->ilm_ipif == NULL);
19034 			ASSERT(ilm->ilm_ill != NULL);
19035 			if (ilm->ilm_zoneid != zoneid)
19036 				continue;	/* not this zone */
19037 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19038 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19039 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19040 			if (!snmp_append_data2(mpctl->b_cont,
19041 			    &mp_tail,
19042 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19043 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19044 				    "failed to allocate %u bytes\n",
19045 				    (uint_t)sizeof (ipm6)));
19046 			}
19047 		}
19048 		ilm_walker_finish(&ilw);
19049 	}
19050 	rw_exit(&ipst->ips_ill_g_lock);
19051 
19052 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19053 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19054 	    (int)optp->level, (int)optp->name, (int)optp->len));
19055 	qreply(q, mpctl);
19056 	return (mp2ctl);
19057 }
19058 
19059 /* IP multicast filtered sources */
19060 static mblk_t *
19061 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19062 {
19063 	struct opthdr		*optp;
19064 	mblk_t			*mp2ctl;
19065 	ill_t			*ill;
19066 	ipif_t			*ipif;
19067 	ilm_t			*ilm;
19068 	ip_grpsrc_t		ips;
19069 	mblk_t			*mp_tail = NULL;
19070 	ill_walk_context_t	ctx;
19071 	zoneid_t		zoneid;
19072 	int			i;
19073 	slist_t			*sl;
19074 	ilm_walker_t		ilw;
19075 
19076 	/*
19077 	 * make a copy of the original message
19078 	 */
19079 	mp2ctl = copymsg(mpctl);
19080 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19081 
19082 	/* ipGroupSource table */
19083 	optp = (struct opthdr *)&mpctl->b_rptr[
19084 	    sizeof (struct T_optmgmt_ack)];
19085 	optp->level = MIB2_IP;
19086 	optp->name = EXPER_IP_GROUP_SOURCES;
19087 
19088 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19089 	ill = ILL_START_WALK_V4(&ctx, ipst);
19090 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19091 		if (IS_UNDER_IPMP(ill))
19092 			continue;
19093 
19094 		ilm = ilm_walker_start(&ilw, ill);
19095 		for (ipif = ill->ill_ipif; ipif != NULL;
19096 		    ipif = ipif->ipif_next) {
19097 			if (ipif->ipif_zoneid != zoneid)
19098 				continue;	/* not this zone */
19099 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19100 			    OCTET_LENGTH);
19101 			ips.ipGroupSourceIfIndex.o_length =
19102 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19103 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19104 				ASSERT(ilm->ilm_ipif != NULL);
19105 				ASSERT(ilm->ilm_ill == NULL);
19106 				sl = ilm->ilm_filter;
19107 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19108 					continue;
19109 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19110 				for (i = 0; i < sl->sl_numsrc; i++) {
19111 					if (!IN6_IS_ADDR_V4MAPPED(
19112 					    &sl->sl_addr[i]))
19113 						continue;
19114 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19115 					    ips.ipGroupSourceAddress);
19116 					if (snmp_append_data2(mpctl->b_cont,
19117 					    &mp_tail, (char *)&ips,
19118 					    (int)sizeof (ips)) == 0) {
19119 						ip1dbg(("ip_snmp_get_mib2_"
19120 						    "ip_group_src: failed to "
19121 						    "allocate %u bytes\n",
19122 						    (uint_t)sizeof (ips)));
19123 					}
19124 				}
19125 			}
19126 		}
19127 		ilm_walker_finish(&ilw);
19128 	}
19129 	rw_exit(&ipst->ips_ill_g_lock);
19130 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19131 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19132 	    (int)optp->level, (int)optp->name, (int)optp->len));
19133 	qreply(q, mpctl);
19134 	return (mp2ctl);
19135 }
19136 
19137 /* IPv6 multicast filtered sources. */
19138 static mblk_t *
19139 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19140 {
19141 	struct opthdr		*optp;
19142 	mblk_t			*mp2ctl;
19143 	ill_t			*ill;
19144 	ilm_t			*ilm;
19145 	ipv6_grpsrc_t		ips6;
19146 	mblk_t			*mp_tail = NULL;
19147 	ill_walk_context_t	ctx;
19148 	zoneid_t		zoneid;
19149 	int			i;
19150 	slist_t			*sl;
19151 	ilm_walker_t		ilw;
19152 
19153 	/*
19154 	 * make a copy of the original message
19155 	 */
19156 	mp2ctl = copymsg(mpctl);
19157 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19158 
19159 	/* ip6GroupMember table */
19160 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19161 	optp->level = MIB2_IP6;
19162 	optp->name = EXPER_IP6_GROUP_SOURCES;
19163 
19164 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19165 	ill = ILL_START_WALK_V6(&ctx, ipst);
19166 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19167 		if (IS_UNDER_IPMP(ill))
19168 			continue;
19169 
19170 		ilm = ilm_walker_start(&ilw, ill);
19171 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19172 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19173 			ASSERT(ilm->ilm_ipif == NULL);
19174 			ASSERT(ilm->ilm_ill != NULL);
19175 			sl = ilm->ilm_filter;
19176 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19177 				continue;
19178 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19179 			for (i = 0; i < sl->sl_numsrc; i++) {
19180 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19181 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19182 				    (char *)&ips6, (int)sizeof (ips6))) {
19183 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19184 					    "group_src: failed to allocate "
19185 					    "%u bytes\n",
19186 					    (uint_t)sizeof (ips6)));
19187 				}
19188 			}
19189 		}
19190 		ilm_walker_finish(&ilw);
19191 	}
19192 	rw_exit(&ipst->ips_ill_g_lock);
19193 
19194 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19195 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19196 	    (int)optp->level, (int)optp->name, (int)optp->len));
19197 	qreply(q, mpctl);
19198 	return (mp2ctl);
19199 }
19200 
19201 /* Multicast routing virtual interface table. */
19202 static mblk_t *
19203 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19204 {
19205 	struct opthdr		*optp;
19206 	mblk_t			*mp2ctl;
19207 
19208 	/*
19209 	 * make a copy of the original message
19210 	 */
19211 	mp2ctl = copymsg(mpctl);
19212 
19213 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19214 	optp->level = EXPER_DVMRP;
19215 	optp->name = EXPER_DVMRP_VIF;
19216 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19217 		ip0dbg(("ip_mroute_vif: failed\n"));
19218 	}
19219 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19220 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19221 	    (int)optp->level, (int)optp->name, (int)optp->len));
19222 	qreply(q, mpctl);
19223 	return (mp2ctl);
19224 }
19225 
19226 /* Multicast routing table. */
19227 static mblk_t *
19228 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19229 {
19230 	struct opthdr		*optp;
19231 	mblk_t			*mp2ctl;
19232 
19233 	/*
19234 	 * make a copy of the original message
19235 	 */
19236 	mp2ctl = copymsg(mpctl);
19237 
19238 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19239 	optp->level = EXPER_DVMRP;
19240 	optp->name = EXPER_DVMRP_MRT;
19241 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19242 		ip0dbg(("ip_mroute_mrt: failed\n"));
19243 	}
19244 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19245 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19246 	    (int)optp->level, (int)optp->name, (int)optp->len));
19247 	qreply(q, mpctl);
19248 	return (mp2ctl);
19249 }
19250 
19251 /*
19252  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19253  * in one IRE walk.
19254  */
19255 static mblk_t *
19256 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19257     ip_stack_t *ipst)
19258 {
19259 	struct opthdr	*optp;
19260 	mblk_t		*mp2ctl;	/* Returned */
19261 	mblk_t		*mp3ctl;	/* nettomedia */
19262 	mblk_t		*mp4ctl;	/* routeattrs */
19263 	iproutedata_t	ird;
19264 	zoneid_t	zoneid;
19265 
19266 	/*
19267 	 * make copies of the original message
19268 	 *	- mp2ctl is returned unchanged to the caller for his use
19269 	 *	- mpctl is sent upstream as ipRouteEntryTable
19270 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19271 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19272 	 */
19273 	mp2ctl = copymsg(mpctl);
19274 	mp3ctl = copymsg(mpctl);
19275 	mp4ctl = copymsg(mpctl);
19276 	if (mp3ctl == NULL || mp4ctl == NULL) {
19277 		freemsg(mp4ctl);
19278 		freemsg(mp3ctl);
19279 		freemsg(mp2ctl);
19280 		freemsg(mpctl);
19281 		return (NULL);
19282 	}
19283 
19284 	bzero(&ird, sizeof (ird));
19285 
19286 	ird.ird_route.lp_head = mpctl->b_cont;
19287 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19288 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19289 	/*
19290 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19291 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19292 	 * intended a temporary solution until a proper MIB API is provided
19293 	 * that provides complete filtering/caller-opt-in.
19294 	 */
19295 	if (level == EXPER_IP_AND_TESTHIDDEN)
19296 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19297 
19298 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19299 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19300 
19301 	/* ipRouteEntryTable in mpctl */
19302 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19303 	optp->level = MIB2_IP;
19304 	optp->name = MIB2_IP_ROUTE;
19305 	optp->len = msgdsize(ird.ird_route.lp_head);
19306 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19307 	    (int)optp->level, (int)optp->name, (int)optp->len));
19308 	qreply(q, mpctl);
19309 
19310 	/* ipNetToMediaEntryTable in mp3ctl */
19311 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19312 	optp->level = MIB2_IP;
19313 	optp->name = MIB2_IP_MEDIA;
19314 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19315 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19316 	    (int)optp->level, (int)optp->name, (int)optp->len));
19317 	qreply(q, mp3ctl);
19318 
19319 	/* ipRouteAttributeTable in mp4ctl */
19320 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19321 	optp->level = MIB2_IP;
19322 	optp->name = EXPER_IP_RTATTR;
19323 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19324 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19325 	    (int)optp->level, (int)optp->name, (int)optp->len));
19326 	if (optp->len == 0)
19327 		freemsg(mp4ctl);
19328 	else
19329 		qreply(q, mp4ctl);
19330 
19331 	return (mp2ctl);
19332 }
19333 
19334 /*
19335  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19336  * ipv6NetToMediaEntryTable in an NDP walk.
19337  */
19338 static mblk_t *
19339 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19340     ip_stack_t *ipst)
19341 {
19342 	struct opthdr	*optp;
19343 	mblk_t		*mp2ctl;	/* Returned */
19344 	mblk_t		*mp3ctl;	/* nettomedia */
19345 	mblk_t		*mp4ctl;	/* routeattrs */
19346 	iproutedata_t	ird;
19347 	zoneid_t	zoneid;
19348 
19349 	/*
19350 	 * make copies of the original message
19351 	 *	- mp2ctl is returned unchanged to the caller for his use
19352 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19353 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19354 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19355 	 */
19356 	mp2ctl = copymsg(mpctl);
19357 	mp3ctl = copymsg(mpctl);
19358 	mp4ctl = copymsg(mpctl);
19359 	if (mp3ctl == NULL || mp4ctl == NULL) {
19360 		freemsg(mp4ctl);
19361 		freemsg(mp3ctl);
19362 		freemsg(mp2ctl);
19363 		freemsg(mpctl);
19364 		return (NULL);
19365 	}
19366 
19367 	bzero(&ird, sizeof (ird));
19368 
19369 	ird.ird_route.lp_head = mpctl->b_cont;
19370 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19371 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19372 	/*
19373 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19374 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19375 	 * intended a temporary solution until a proper MIB API is provided
19376 	 * that provides complete filtering/caller-opt-in.
19377 	 */
19378 	if (level == EXPER_IP_AND_TESTHIDDEN)
19379 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19380 
19381 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19382 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19383 
19384 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19385 	optp->level = MIB2_IP6;
19386 	optp->name = MIB2_IP6_ROUTE;
19387 	optp->len = msgdsize(ird.ird_route.lp_head);
19388 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19389 	    (int)optp->level, (int)optp->name, (int)optp->len));
19390 	qreply(q, mpctl);
19391 
19392 	/* ipv6NetToMediaEntryTable in mp3ctl */
19393 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19394 
19395 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19396 	optp->level = MIB2_IP6;
19397 	optp->name = MIB2_IP6_MEDIA;
19398 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19399 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19400 	    (int)optp->level, (int)optp->name, (int)optp->len));
19401 	qreply(q, mp3ctl);
19402 
19403 	/* ipv6RouteAttributeTable in mp4ctl */
19404 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19405 	optp->level = MIB2_IP6;
19406 	optp->name = EXPER_IP_RTATTR;
19407 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19408 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19409 	    (int)optp->level, (int)optp->name, (int)optp->len));
19410 	if (optp->len == 0)
19411 		freemsg(mp4ctl);
19412 	else
19413 		qreply(q, mp4ctl);
19414 
19415 	return (mp2ctl);
19416 }
19417 
19418 /*
19419  * IPv6 mib: One per ill
19420  */
19421 static mblk_t *
19422 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19423 {
19424 	struct opthdr		*optp;
19425 	mblk_t			*mp2ctl;
19426 	ill_t			*ill;
19427 	ill_walk_context_t	ctx;
19428 	mblk_t			*mp_tail = NULL;
19429 
19430 	/*
19431 	 * Make a copy of the original message
19432 	 */
19433 	mp2ctl = copymsg(mpctl);
19434 
19435 	/* fixed length IPv6 structure ... */
19436 
19437 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19438 	optp->level = MIB2_IP6;
19439 	optp->name = 0;
19440 	/* Include "unknown interface" ip6_mib */
19441 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19442 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19443 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19444 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19445 	    ipst->ips_ipv6_forward ? 1 : 2);
19446 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19447 	    ipst->ips_ipv6_def_hops);
19448 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19449 	    sizeof (mib2_ipIfStatsEntry_t));
19450 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19451 	    sizeof (mib2_ipv6AddrEntry_t));
19452 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19453 	    sizeof (mib2_ipv6RouteEntry_t));
19454 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19455 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19456 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19457 	    sizeof (ipv6_member_t));
19458 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19459 	    sizeof (ipv6_grpsrc_t));
19460 
19461 	/*
19462 	 * Synchronize 64- and 32-bit counters
19463 	 */
19464 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19465 	    ipIfStatsHCInReceives);
19466 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19467 	    ipIfStatsHCInDelivers);
19468 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19469 	    ipIfStatsHCOutRequests);
19470 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19471 	    ipIfStatsHCOutForwDatagrams);
19472 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19473 	    ipIfStatsHCOutMcastPkts);
19474 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19475 	    ipIfStatsHCInMcastPkts);
19476 
19477 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19478 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19479 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19480 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19481 	}
19482 
19483 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19484 	ill = ILL_START_WALK_V6(&ctx, ipst);
19485 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19486 		ill->ill_ip_mib->ipIfStatsIfIndex =
19487 		    ill->ill_phyint->phyint_ifindex;
19488 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19489 		    ipst->ips_ipv6_forward ? 1 : 2);
19490 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19491 		    ill->ill_max_hops);
19492 
19493 		/*
19494 		 * Synchronize 64- and 32-bit counters
19495 		 */
19496 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19497 		    ipIfStatsHCInReceives);
19498 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19499 		    ipIfStatsHCInDelivers);
19500 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19501 		    ipIfStatsHCOutRequests);
19502 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19503 		    ipIfStatsHCOutForwDatagrams);
19504 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19505 		    ipIfStatsHCOutMcastPkts);
19506 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19507 		    ipIfStatsHCInMcastPkts);
19508 
19509 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19510 		    (char *)ill->ill_ip_mib,
19511 		    (int)sizeof (*ill->ill_ip_mib))) {
19512 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19513 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19514 		}
19515 	}
19516 	rw_exit(&ipst->ips_ill_g_lock);
19517 
19518 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19519 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19520 	    (int)optp->level, (int)optp->name, (int)optp->len));
19521 	qreply(q, mpctl);
19522 	return (mp2ctl);
19523 }
19524 
19525 /*
19526  * ICMPv6 mib: One per ill
19527  */
19528 static mblk_t *
19529 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19530 {
19531 	struct opthdr		*optp;
19532 	mblk_t			*mp2ctl;
19533 	ill_t			*ill;
19534 	ill_walk_context_t	ctx;
19535 	mblk_t			*mp_tail = NULL;
19536 	/*
19537 	 * Make a copy of the original message
19538 	 */
19539 	mp2ctl = copymsg(mpctl);
19540 
19541 	/* fixed length ICMPv6 structure ... */
19542 
19543 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19544 	optp->level = MIB2_ICMP6;
19545 	optp->name = 0;
19546 	/* Include "unknown interface" icmp6_mib */
19547 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19548 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19549 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19550 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19551 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19552 	    (char *)&ipst->ips_icmp6_mib,
19553 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19554 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19555 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19556 	}
19557 
19558 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19559 	ill = ILL_START_WALK_V6(&ctx, ipst);
19560 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19561 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19562 		    ill->ill_phyint->phyint_ifindex;
19563 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19564 		    (char *)ill->ill_icmp6_mib,
19565 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19566 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19567 			    "%u bytes\n",
19568 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19569 		}
19570 	}
19571 	rw_exit(&ipst->ips_ill_g_lock);
19572 
19573 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19574 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19575 	    (int)optp->level, (int)optp->name, (int)optp->len));
19576 	qreply(q, mpctl);
19577 	return (mp2ctl);
19578 }
19579 
19580 /*
19581  * ire_walk routine to create both ipRouteEntryTable and
19582  * ipRouteAttributeTable in one IRE walk
19583  */
19584 static void
19585 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19586 {
19587 	ill_t				*ill;
19588 	ipif_t				*ipif;
19589 	mib2_ipRouteEntry_t		*re;
19590 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19591 	ipaddr_t			gw_addr;
19592 	tsol_ire_gw_secattr_t		*attrp;
19593 	tsol_gc_t			*gc = NULL;
19594 	tsol_gcgrp_t			*gcgrp = NULL;
19595 	uint_t				sacnt = 0;
19596 	int				i;
19597 
19598 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19599 
19600 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19601 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19602 		return;
19603 	}
19604 
19605 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19606 		return;
19607 
19608 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19609 		mutex_enter(&attrp->igsa_lock);
19610 		if ((gc = attrp->igsa_gc) != NULL) {
19611 			gcgrp = gc->gc_grp;
19612 			ASSERT(gcgrp != NULL);
19613 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19614 			sacnt = 1;
19615 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19616 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19617 			gc = gcgrp->gcgrp_head;
19618 			sacnt = gcgrp->gcgrp_count;
19619 		}
19620 		mutex_exit(&attrp->igsa_lock);
19621 
19622 		/* do nothing if there's no gc to report */
19623 		if (gc == NULL) {
19624 			ASSERT(sacnt == 0);
19625 			if (gcgrp != NULL) {
19626 				/* we might as well drop the lock now */
19627 				rw_exit(&gcgrp->gcgrp_rwlock);
19628 				gcgrp = NULL;
19629 			}
19630 			attrp = NULL;
19631 		}
19632 
19633 		ASSERT(gc == NULL || (gcgrp != NULL &&
19634 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19635 	}
19636 	ASSERT(sacnt == 0 || gc != NULL);
19637 
19638 	if (sacnt != 0 &&
19639 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19640 		kmem_free(re, sizeof (*re));
19641 		rw_exit(&gcgrp->gcgrp_rwlock);
19642 		return;
19643 	}
19644 
19645 	/*
19646 	 * Return all IRE types for route table... let caller pick and choose
19647 	 */
19648 	re->ipRouteDest = ire->ire_addr;
19649 	ipif = ire->ire_ipif;
19650 	re->ipRouteIfIndex.o_length = 0;
19651 	if (ire->ire_type == IRE_CACHE) {
19652 		ill = (ill_t *)ire->ire_stq->q_ptr;
19653 		re->ipRouteIfIndex.o_length =
19654 		    ill->ill_name_length == 0 ? 0 :
19655 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19656 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19657 		    re->ipRouteIfIndex.o_length);
19658 	} else if (ipif != NULL) {
19659 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19660 		re->ipRouteIfIndex.o_length =
19661 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19662 	}
19663 	re->ipRouteMetric1 = -1;
19664 	re->ipRouteMetric2 = -1;
19665 	re->ipRouteMetric3 = -1;
19666 	re->ipRouteMetric4 = -1;
19667 
19668 	gw_addr = ire->ire_gateway_addr;
19669 
19670 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19671 		re->ipRouteNextHop = ire->ire_src_addr;
19672 	else
19673 		re->ipRouteNextHop = gw_addr;
19674 	/* indirect(4), direct(3), or invalid(2) */
19675 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19676 		re->ipRouteType = 2;
19677 	else
19678 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19679 	re->ipRouteProto = -1;
19680 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19681 	re->ipRouteMask = ire->ire_mask;
19682 	re->ipRouteMetric5 = -1;
19683 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19684 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19685 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19686 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19687 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19688 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19689 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19690 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19691 
19692 	if (ire->ire_flags & RTF_DYNAMIC) {
19693 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19694 	} else {
19695 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19696 	}
19697 
19698 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19699 	    (char *)re, (int)sizeof (*re))) {
19700 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19701 		    (uint_t)sizeof (*re)));
19702 	}
19703 
19704 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19705 		iaeptr->iae_routeidx = ird->ird_idx;
19706 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19707 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19708 	}
19709 
19710 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19711 	    (char *)iae, sacnt * sizeof (*iae))) {
19712 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19713 		    (unsigned)(sacnt * sizeof (*iae))));
19714 	}
19715 
19716 	/* bump route index for next pass */
19717 	ird->ird_idx++;
19718 
19719 	kmem_free(re, sizeof (*re));
19720 	if (sacnt != 0)
19721 		kmem_free(iae, sacnt * sizeof (*iae));
19722 
19723 	if (gcgrp != NULL)
19724 		rw_exit(&gcgrp->gcgrp_rwlock);
19725 }
19726 
19727 /*
19728  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19729  */
19730 static void
19731 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19732 {
19733 	ill_t				*ill;
19734 	ipif_t				*ipif;
19735 	mib2_ipv6RouteEntry_t		*re;
19736 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19737 	in6_addr_t			gw_addr_v6;
19738 	tsol_ire_gw_secattr_t		*attrp;
19739 	tsol_gc_t			*gc = NULL;
19740 	tsol_gcgrp_t			*gcgrp = NULL;
19741 	uint_t				sacnt = 0;
19742 	int				i;
19743 
19744 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19745 
19746 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19747 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19748 		return;
19749 	}
19750 
19751 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19752 		return;
19753 
19754 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19755 		mutex_enter(&attrp->igsa_lock);
19756 		if ((gc = attrp->igsa_gc) != NULL) {
19757 			gcgrp = gc->gc_grp;
19758 			ASSERT(gcgrp != NULL);
19759 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19760 			sacnt = 1;
19761 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19762 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19763 			gc = gcgrp->gcgrp_head;
19764 			sacnt = gcgrp->gcgrp_count;
19765 		}
19766 		mutex_exit(&attrp->igsa_lock);
19767 
19768 		/* do nothing if there's no gc to report */
19769 		if (gc == NULL) {
19770 			ASSERT(sacnt == 0);
19771 			if (gcgrp != NULL) {
19772 				/* we might as well drop the lock now */
19773 				rw_exit(&gcgrp->gcgrp_rwlock);
19774 				gcgrp = NULL;
19775 			}
19776 			attrp = NULL;
19777 		}
19778 
19779 		ASSERT(gc == NULL || (gcgrp != NULL &&
19780 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19781 	}
19782 	ASSERT(sacnt == 0 || gc != NULL);
19783 
19784 	if (sacnt != 0 &&
19785 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19786 		kmem_free(re, sizeof (*re));
19787 		rw_exit(&gcgrp->gcgrp_rwlock);
19788 		return;
19789 	}
19790 
19791 	/*
19792 	 * Return all IRE types for route table... let caller pick and choose
19793 	 */
19794 	re->ipv6RouteDest = ire->ire_addr_v6;
19795 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19796 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19797 	re->ipv6RouteIfIndex.o_length = 0;
19798 	ipif = ire->ire_ipif;
19799 	if (ire->ire_type == IRE_CACHE) {
19800 		ill = (ill_t *)ire->ire_stq->q_ptr;
19801 		re->ipv6RouteIfIndex.o_length =
19802 		    ill->ill_name_length == 0 ? 0 :
19803 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19804 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19805 		    re->ipv6RouteIfIndex.o_length);
19806 	} else if (ipif != NULL) {
19807 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19808 		re->ipv6RouteIfIndex.o_length =
19809 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19810 	}
19811 
19812 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19813 
19814 	mutex_enter(&ire->ire_lock);
19815 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19816 	mutex_exit(&ire->ire_lock);
19817 
19818 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19819 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19820 	else
19821 		re->ipv6RouteNextHop = gw_addr_v6;
19822 
19823 	/* remote(4), local(3), or discard(2) */
19824 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19825 		re->ipv6RouteType = 2;
19826 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19827 		re->ipv6RouteType = 3;
19828 	else
19829 		re->ipv6RouteType = 4;
19830 
19831 	re->ipv6RouteProtocol	= -1;
19832 	re->ipv6RoutePolicy	= 0;
19833 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19834 	re->ipv6RouteNextHopRDI	= 0;
19835 	re->ipv6RouteWeight	= 0;
19836 	re->ipv6RouteMetric	= 0;
19837 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19838 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19839 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19840 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19841 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19842 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19843 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19844 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19845 
19846 	if (ire->ire_flags & RTF_DYNAMIC) {
19847 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19848 	} else {
19849 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19850 	}
19851 
19852 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19853 	    (char *)re, (int)sizeof (*re))) {
19854 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19855 		    (uint_t)sizeof (*re)));
19856 	}
19857 
19858 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19859 		iaeptr->iae_routeidx = ird->ird_idx;
19860 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19861 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19862 	}
19863 
19864 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19865 	    (char *)iae, sacnt * sizeof (*iae))) {
19866 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19867 		    (unsigned)(sacnt * sizeof (*iae))));
19868 	}
19869 
19870 	/* bump route index for next pass */
19871 	ird->ird_idx++;
19872 
19873 	kmem_free(re, sizeof (*re));
19874 	if (sacnt != 0)
19875 		kmem_free(iae, sacnt * sizeof (*iae));
19876 
19877 	if (gcgrp != NULL)
19878 		rw_exit(&gcgrp->gcgrp_rwlock);
19879 }
19880 
19881 /*
19882  * ndp_walk routine to create ipv6NetToMediaEntryTable
19883  */
19884 static int
19885 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19886 {
19887 	ill_t				*ill;
19888 	mib2_ipv6NetToMediaEntry_t	ntme;
19889 	dl_unitdata_req_t		*dl;
19890 
19891 	ill = nce->nce_ill;
19892 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19893 		return (0);
19894 
19895 	/*
19896 	 * Neighbor cache entry attached to IRE with on-link
19897 	 * destination.
19898 	 */
19899 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19900 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19901 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19902 	    (nce->nce_res_mp != NULL)) {
19903 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19904 		ntme.ipv6NetToMediaPhysAddress.o_length =
19905 		    dl->dl_dest_addr_length;
19906 	} else {
19907 		ntme.ipv6NetToMediaPhysAddress.o_length =
19908 		    ill->ill_phys_addr_length;
19909 	}
19910 	if (nce->nce_res_mp != NULL) {
19911 		bcopy((char *)nce->nce_res_mp->b_rptr +
19912 		    NCE_LL_ADDR_OFFSET(ill),
19913 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19914 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19915 	} else {
19916 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19917 		    ill->ill_phys_addr_length);
19918 	}
19919 	/*
19920 	 * Note: Returns ND_* states. Should be:
19921 	 * reachable(1), stale(2), delay(3), probe(4),
19922 	 * invalid(5), unknown(6)
19923 	 */
19924 	ntme.ipv6NetToMediaState = nce->nce_state;
19925 	ntme.ipv6NetToMediaLastUpdated = 0;
19926 
19927 	/* other(1), dynamic(2), static(3), local(4) */
19928 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19929 		ntme.ipv6NetToMediaType = 4;
19930 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19931 		ntme.ipv6NetToMediaType = 1;
19932 	} else {
19933 		ntme.ipv6NetToMediaType = 2;
19934 	}
19935 
19936 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19937 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19938 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19939 		    (uint_t)sizeof (ntme)));
19940 	}
19941 	return (0);
19942 }
19943 
19944 /*
19945  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19946  */
19947 /* ARGSUSED */
19948 int
19949 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19950 {
19951 	switch (level) {
19952 	case MIB2_IP:
19953 	case MIB2_ICMP:
19954 		switch (name) {
19955 		default:
19956 			break;
19957 		}
19958 		return (1);
19959 	default:
19960 		return (1);
19961 	}
19962 }
19963 
19964 /*
19965  * When there exists both a 64- and 32-bit counter of a particular type
19966  * (i.e., InReceives), only the 64-bit counters are added.
19967  */
19968 void
19969 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19970 {
19971 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19972 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19973 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19974 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19975 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19976 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19977 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19978 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19979 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19980 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19981 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19982 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19983 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19984 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19985 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19986 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19987 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19988 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19989 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19990 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19991 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19992 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19993 	    o2->ipIfStatsInWrongIPVersion);
19994 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19995 	    o2->ipIfStatsInWrongIPVersion);
19996 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19997 	    o2->ipIfStatsOutSwitchIPVersion);
19998 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19999 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20000 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20001 	    o2->ipIfStatsHCInForwDatagrams);
20002 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20003 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20004 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20005 	    o2->ipIfStatsHCOutForwDatagrams);
20006 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20007 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20008 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20009 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20010 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20011 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20012 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20013 	    o2->ipIfStatsHCOutMcastOctets);
20014 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20015 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20016 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20017 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20018 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20019 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20020 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20021 }
20022 
20023 void
20024 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20025 {
20026 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20027 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20028 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20029 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20030 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20031 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20032 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20033 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20034 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20035 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20036 	    o2->ipv6IfIcmpInRouterSolicits);
20037 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20038 	    o2->ipv6IfIcmpInRouterAdvertisements);
20039 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20040 	    o2->ipv6IfIcmpInNeighborSolicits);
20041 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20042 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20043 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20044 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20045 	    o2->ipv6IfIcmpInGroupMembQueries);
20046 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20047 	    o2->ipv6IfIcmpInGroupMembResponses);
20048 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20049 	    o2->ipv6IfIcmpInGroupMembReductions);
20050 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20051 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20052 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20053 	    o2->ipv6IfIcmpOutDestUnreachs);
20054 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20055 	    o2->ipv6IfIcmpOutAdminProhibs);
20056 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20057 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20058 	    o2->ipv6IfIcmpOutParmProblems);
20059 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20060 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20061 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20062 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20063 	    o2->ipv6IfIcmpOutRouterSolicits);
20064 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20065 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20066 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20067 	    o2->ipv6IfIcmpOutNeighborSolicits);
20068 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20069 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20070 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20071 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20072 	    o2->ipv6IfIcmpOutGroupMembQueries);
20073 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20074 	    o2->ipv6IfIcmpOutGroupMembResponses);
20075 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20076 	    o2->ipv6IfIcmpOutGroupMembReductions);
20077 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20078 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20079 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20080 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20081 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20082 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20083 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20084 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20085 	    o2->ipv6IfIcmpInGroupMembTotal);
20086 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20087 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20088 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20089 	    o2->ipv6IfIcmpInGroupMembBadReports);
20090 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20091 	    o2->ipv6IfIcmpInGroupMembOurReports);
20092 }
20093 
20094 /*
20095  * Called before the options are updated to check if this packet will
20096  * be source routed from here.
20097  * This routine assumes that the options are well formed i.e. that they
20098  * have already been checked.
20099  */
20100 static boolean_t
20101 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20102 {
20103 	ipoptp_t	opts;
20104 	uchar_t		*opt;
20105 	uint8_t		optval;
20106 	uint8_t		optlen;
20107 	ipaddr_t	dst;
20108 	ire_t		*ire;
20109 
20110 	if (IS_SIMPLE_IPH(ipha)) {
20111 		ip2dbg(("not source routed\n"));
20112 		return (B_FALSE);
20113 	}
20114 	dst = ipha->ipha_dst;
20115 	for (optval = ipoptp_first(&opts, ipha);
20116 	    optval != IPOPT_EOL;
20117 	    optval = ipoptp_next(&opts)) {
20118 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20119 		opt = opts.ipoptp_cur;
20120 		optlen = opts.ipoptp_len;
20121 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20122 		    optval, optlen));
20123 		switch (optval) {
20124 			uint32_t off;
20125 		case IPOPT_SSRR:
20126 		case IPOPT_LSRR:
20127 			/*
20128 			 * If dst is one of our addresses and there are some
20129 			 * entries left in the source route return (true).
20130 			 */
20131 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20132 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20133 			if (ire == NULL) {
20134 				ip2dbg(("ip_source_routed: not next"
20135 				    " source route 0x%x\n",
20136 				    ntohl(dst)));
20137 				return (B_FALSE);
20138 			}
20139 			ire_refrele(ire);
20140 			off = opt[IPOPT_OFFSET];
20141 			off--;
20142 			if (optlen < IP_ADDR_LEN ||
20143 			    off > optlen - IP_ADDR_LEN) {
20144 				/* End of source route */
20145 				ip1dbg(("ip_source_routed: end of SR\n"));
20146 				return (B_FALSE);
20147 			}
20148 			return (B_TRUE);
20149 		}
20150 	}
20151 	ip2dbg(("not source routed\n"));
20152 	return (B_FALSE);
20153 }
20154 
20155 /*
20156  * Check if the packet contains any source route.
20157  */
20158 static boolean_t
20159 ip_source_route_included(ipha_t *ipha)
20160 {
20161 	ipoptp_t	opts;
20162 	uint8_t		optval;
20163 
20164 	if (IS_SIMPLE_IPH(ipha))
20165 		return (B_FALSE);
20166 	for (optval = ipoptp_first(&opts, ipha);
20167 	    optval != IPOPT_EOL;
20168 	    optval = ipoptp_next(&opts)) {
20169 		switch (optval) {
20170 		case IPOPT_SSRR:
20171 		case IPOPT_LSRR:
20172 			return (B_TRUE);
20173 		}
20174 	}
20175 	return (B_FALSE);
20176 }
20177 
20178 /*
20179  * Called when the IRE expiration timer fires.
20180  */
20181 void
20182 ip_trash_timer_expire(void *args)
20183 {
20184 	int			flush_flag = 0;
20185 	ire_expire_arg_t	iea;
20186 	ip_stack_t		*ipst = (ip_stack_t *)args;
20187 
20188 	iea.iea_ipst = ipst;	/* No netstack_hold */
20189 
20190 	/*
20191 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20192 	 * This lock makes sure that a new invocation of this function
20193 	 * that occurs due to an almost immediate timer firing will not
20194 	 * progress beyond this point until the current invocation is done
20195 	 */
20196 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20197 	ipst->ips_ip_ire_expire_id = 0;
20198 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20199 
20200 	/* Periodic timer */
20201 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20202 	    ipst->ips_ip_ire_arp_interval) {
20203 		/*
20204 		 * Remove all IRE_CACHE entries since they might
20205 		 * contain arp information.
20206 		 */
20207 		flush_flag |= FLUSH_ARP_TIME;
20208 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20209 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20210 	}
20211 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20212 	    ipst->ips_ip_ire_redir_interval) {
20213 		/* Remove all redirects */
20214 		flush_flag |= FLUSH_REDIRECT_TIME;
20215 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20216 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20217 	}
20218 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20219 	    ipst->ips_ip_ire_pathmtu_interval) {
20220 		/* Increase path mtu */
20221 		flush_flag |= FLUSH_MTU_TIME;
20222 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20223 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20224 	}
20225 
20226 	/*
20227 	 * Optimize for the case when there are no redirects in the
20228 	 * ftable, that is, no need to walk the ftable in that case.
20229 	 */
20230 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20231 		iea.iea_flush_flag = flush_flag;
20232 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20233 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20234 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20235 		    NULL, ALL_ZONES, ipst);
20236 	}
20237 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20238 	    ipst->ips_ip_redirect_cnt > 0) {
20239 		iea.iea_flush_flag = flush_flag;
20240 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20241 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20242 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20243 	}
20244 	if (flush_flag & FLUSH_MTU_TIME) {
20245 		/*
20246 		 * Walk all IPv6 IRE's and update them
20247 		 * Note that ARP and redirect timers are not
20248 		 * needed since NUD handles stale entries.
20249 		 */
20250 		flush_flag = FLUSH_MTU_TIME;
20251 		iea.iea_flush_flag = flush_flag;
20252 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20253 		    ALL_ZONES, ipst);
20254 	}
20255 
20256 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20257 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20258 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20259 
20260 	/*
20261 	 * Hold the lock to serialize timeout calls and prevent
20262 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20263 	 * for the timer to fire and a new invocation of this function
20264 	 * to start before the return value of timeout has been stored
20265 	 * in ip_ire_expire_id by the current invocation.
20266 	 */
20267 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20268 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20269 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20270 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20271 }
20272 
20273 /*
20274  * Called by the memory allocator subsystem directly, when the system
20275  * is running low on memory.
20276  */
20277 /* ARGSUSED */
20278 void
20279 ip_trash_ire_reclaim(void *args)
20280 {
20281 	netstack_handle_t nh;
20282 	netstack_t *ns;
20283 
20284 	netstack_next_init(&nh);
20285 	while ((ns = netstack_next(&nh)) != NULL) {
20286 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20287 		netstack_rele(ns);
20288 	}
20289 	netstack_next_fini(&nh);
20290 }
20291 
20292 static void
20293 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20294 {
20295 	ire_cache_count_t icc;
20296 	ire_cache_reclaim_t icr;
20297 	ncc_cache_count_t ncc;
20298 	nce_cache_reclaim_t ncr;
20299 	uint_t delete_cnt;
20300 	/*
20301 	 * Memory reclaim call back.
20302 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20303 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20304 	 * entries, determine what fraction to free for
20305 	 * each category of IRE_CACHE entries giving absolute priority
20306 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20307 	 * entry will be freed unless all offlink entries are freed).
20308 	 */
20309 	icc.icc_total = 0;
20310 	icc.icc_unused = 0;
20311 	icc.icc_offlink = 0;
20312 	icc.icc_pmtu = 0;
20313 	icc.icc_onlink = 0;
20314 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20315 
20316 	/*
20317 	 * Free NCEs for IPv6 like the onlink ires.
20318 	 */
20319 	ncc.ncc_total = 0;
20320 	ncc.ncc_host = 0;
20321 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20322 
20323 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20324 	    icc.icc_pmtu + icc.icc_onlink);
20325 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20326 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20327 	if (delete_cnt == 0)
20328 		return;
20329 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20330 	/* Always delete all unused offlink entries */
20331 	icr.icr_ipst = ipst;
20332 	icr.icr_unused = 1;
20333 	if (delete_cnt <= icc.icc_unused) {
20334 		/*
20335 		 * Only need to free unused entries.  In other words,
20336 		 * there are enough unused entries to free to meet our
20337 		 * target number of freed ire cache entries.
20338 		 */
20339 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20340 		ncr.ncr_host = 0;
20341 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20342 		/*
20343 		 * Only need to free unused entries, plus a fraction of offlink
20344 		 * entries.  It follows from the first if statement that
20345 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20346 		 */
20347 		delete_cnt -= icc.icc_unused;
20348 		/* Round up # deleted by truncating fraction */
20349 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20350 		icr.icr_pmtu = icr.icr_onlink = 0;
20351 		ncr.ncr_host = 0;
20352 	} else if (delete_cnt <=
20353 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20354 		/*
20355 		 * Free all unused and offlink entries, plus a fraction of
20356 		 * pmtu entries.  It follows from the previous if statement
20357 		 * that icc_pmtu is non-zero, and that
20358 		 * delete_cnt != icc_unused + icc_offlink.
20359 		 */
20360 		icr.icr_offlink = 1;
20361 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20362 		/* Round up # deleted by truncating fraction */
20363 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20364 		icr.icr_onlink = 0;
20365 		ncr.ncr_host = 0;
20366 	} else {
20367 		/*
20368 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20369 		 * of onlink entries.  If we're here, then we know that
20370 		 * icc_onlink is non-zero, and that
20371 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20372 		 */
20373 		icr.icr_offlink = icr.icr_pmtu = 1;
20374 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20375 		    icc.icc_pmtu;
20376 		/* Round up # deleted by truncating fraction */
20377 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20378 		/* Using the same delete fraction as for onlink IREs */
20379 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20380 	}
20381 #ifdef DEBUG
20382 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20383 	    "fractions %d/%d/%d/%d\n",
20384 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20385 	    icc.icc_unused, icc.icc_offlink,
20386 	    icc.icc_pmtu, icc.icc_onlink,
20387 	    icr.icr_unused, icr.icr_offlink,
20388 	    icr.icr_pmtu, icr.icr_onlink));
20389 #endif
20390 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20391 	if (ncr.ncr_host != 0)
20392 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20393 		    (uchar_t *)&ncr, ipst);
20394 #ifdef DEBUG
20395 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20396 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20397 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20398 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20399 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20400 	    icc.icc_pmtu, icc.icc_onlink));
20401 #endif
20402 }
20403 
20404 /*
20405  * ip_unbind is called when a copy of an unbind request is received from the
20406  * upper level protocol.  We remove this conn from any fanout hash list it is
20407  * on, and zero out the bind information.  No reply is expected up above.
20408  */
20409 void
20410 ip_unbind(conn_t *connp)
20411 {
20412 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20413 
20414 	if (is_system_labeled() && connp->conn_anon_port) {
20415 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20416 		    connp->conn_mlp_type, connp->conn_ulp,
20417 		    ntohs(connp->conn_lport), B_FALSE);
20418 		connp->conn_anon_port = 0;
20419 	}
20420 	connp->conn_mlp_type = mlptSingle;
20421 
20422 	ipcl_hash_remove(connp);
20423 
20424 }
20425 
20426 /*
20427  * Write side put procedure.  Outbound data, IOCTLs, responses from
20428  * resolvers, etc, come down through here.
20429  *
20430  * arg2 is always a queue_t *.
20431  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20432  * the zoneid.
20433  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20434  */
20435 void
20436 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20437 {
20438 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20439 }
20440 
20441 void
20442 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20443     ip_opt_info_t *infop)
20444 {
20445 	conn_t		*connp = NULL;
20446 	queue_t		*q = (queue_t *)arg2;
20447 	ipha_t		*ipha;
20448 #define	rptr	((uchar_t *)ipha)
20449 	ire_t		*ire = NULL;
20450 	ire_t		*sctp_ire = NULL;
20451 	uint32_t	v_hlen_tos_len;
20452 	ipaddr_t	dst;
20453 	mblk_t		*first_mp = NULL;
20454 	boolean_t	mctl_present;
20455 	ipsec_out_t	*io;
20456 	int		match_flags;
20457 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20458 	ipif_t		*dst_ipif;
20459 	boolean_t	multirt_need_resolve = B_FALSE;
20460 	mblk_t		*copy_mp = NULL;
20461 	int		err;
20462 	zoneid_t	zoneid;
20463 	boolean_t	need_decref = B_FALSE;
20464 	boolean_t	ignore_dontroute = B_FALSE;
20465 	boolean_t	ignore_nexthop = B_FALSE;
20466 	boolean_t	ip_nexthop = B_FALSE;
20467 	ipaddr_t	nexthop_addr;
20468 	ip_stack_t	*ipst;
20469 
20470 #ifdef	_BIG_ENDIAN
20471 #define	V_HLEN	(v_hlen_tos_len >> 24)
20472 #else
20473 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20474 #endif
20475 
20476 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20477 	    "ip_wput_start: q %p", q);
20478 
20479 	/*
20480 	 * ip_wput fast path
20481 	 */
20482 
20483 	/* is packet from ARP ? */
20484 	if (q->q_next != NULL) {
20485 		zoneid = (zoneid_t)(uintptr_t)arg;
20486 		goto qnext;
20487 	}
20488 
20489 	connp = (conn_t *)arg;
20490 	ASSERT(connp != NULL);
20491 	zoneid = connp->conn_zoneid;
20492 	ipst = connp->conn_netstack->netstack_ip;
20493 	ASSERT(ipst != NULL);
20494 
20495 	/* is queue flow controlled? */
20496 	if ((q->q_first != NULL || connp->conn_draining) &&
20497 	    (caller == IP_WPUT)) {
20498 		ASSERT(!need_decref);
20499 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20500 		(void) putq(q, mp);
20501 		return;
20502 	}
20503 
20504 	/* Multidata transmit? */
20505 	if (DB_TYPE(mp) == M_MULTIDATA) {
20506 		/*
20507 		 * We should never get here, since all Multidata messages
20508 		 * originating from tcp should have been directed over to
20509 		 * tcp_multisend() in the first place.
20510 		 */
20511 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20512 		freemsg(mp);
20513 		return;
20514 	} else if (DB_TYPE(mp) != M_DATA)
20515 		goto notdata;
20516 
20517 	if (mp->b_flag & MSGHASREF) {
20518 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20519 		mp->b_flag &= ~MSGHASREF;
20520 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20521 		need_decref = B_TRUE;
20522 	}
20523 	ipha = (ipha_t *)mp->b_rptr;
20524 
20525 	/* is IP header non-aligned or mblk smaller than basic IP header */
20526 #ifndef SAFETY_BEFORE_SPEED
20527 	if (!OK_32PTR(rptr) ||
20528 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20529 		goto hdrtoosmall;
20530 #endif
20531 
20532 	ASSERT(OK_32PTR(ipha));
20533 
20534 	/*
20535 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20536 	 * wrong version, we'll catch it again in ip_output_v6.
20537 	 *
20538 	 * Note that this is *only* locally-generated output here, and never
20539 	 * forwarded data, and that we need to deal only with transports that
20540 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20541 	 * label.)
20542 	 */
20543 	if (is_system_labeled() &&
20544 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20545 	    !connp->conn_ulp_labeled) {
20546 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20547 		    connp->conn_mac_exempt, ipst);
20548 		ipha = (ipha_t *)mp->b_rptr;
20549 		if (err != 0) {
20550 			first_mp = mp;
20551 			if (err == EINVAL)
20552 				goto icmp_parameter_problem;
20553 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20554 			goto discard_pkt;
20555 		}
20556 	}
20557 
20558 	ASSERT(infop != NULL);
20559 
20560 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20561 		/*
20562 		 * IP_PKTINFO ancillary option is present.
20563 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20564 		 * allows using address of any zone as the source address.
20565 		 */
20566 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20567 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20568 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20569 		if (ire == NULL)
20570 			goto drop_pkt;
20571 		ire_refrele(ire);
20572 		ire = NULL;
20573 	}
20574 
20575 	/*
20576 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20577 	 */
20578 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20579 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20580 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20581 
20582 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20583 			goto drop_pkt;
20584 		/*
20585 		 * check that there is an ipif belonging
20586 		 * to our zone. IPCL_ZONEID is not used because
20587 		 * IP_ALLZONES option is valid only when the ill is
20588 		 * accessible from all zones i.e has a valid ipif in
20589 		 * all zones.
20590 		 */
20591 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20592 			goto drop_pkt;
20593 		}
20594 	}
20595 
20596 	/*
20597 	 * If there is a policy, try to attach an ipsec_out in
20598 	 * the front. At the end, first_mp either points to a
20599 	 * M_DATA message or IPSEC_OUT message linked to a
20600 	 * M_DATA message. We have to do it now as we might
20601 	 * lose the "conn" if we go through ip_newroute.
20602 	 */
20603 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20604 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20605 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20606 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20607 			if (need_decref)
20608 				CONN_DEC_REF(connp);
20609 			return;
20610 		} else {
20611 			ASSERT(mp->b_datap->db_type == M_CTL);
20612 			first_mp = mp;
20613 			mp = mp->b_cont;
20614 			mctl_present = B_TRUE;
20615 		}
20616 	} else {
20617 		first_mp = mp;
20618 		mctl_present = B_FALSE;
20619 	}
20620 
20621 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20622 
20623 	/* is wrong version or IP options present */
20624 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20625 		goto version_hdrlen_check;
20626 	dst = ipha->ipha_dst;
20627 
20628 	/* If IP_BOUND_IF has been set, use that ill. */
20629 	if (connp->conn_outgoing_ill != NULL) {
20630 		xmit_ill = conn_get_held_ill(connp,
20631 		    &connp->conn_outgoing_ill, &err);
20632 		if (err == ILL_LOOKUP_FAILED)
20633 			goto drop_pkt;
20634 
20635 		goto send_from_ill;
20636 	}
20637 
20638 	/* is packet multicast? */
20639 	if (CLASSD(dst))
20640 		goto multicast;
20641 
20642 	/*
20643 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20644 	 * takes precedence over conn_dontroute and conn_nexthop_set
20645 	 */
20646 	if (xmit_ill != NULL)
20647 		goto send_from_ill;
20648 
20649 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20650 		/*
20651 		 * If the destination is a broadcast, local, or loopback
20652 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20653 		 * standard path.
20654 		 */
20655 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20656 		if ((ire == NULL) || (ire->ire_type &
20657 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20658 			if (ire != NULL) {
20659 				ire_refrele(ire);
20660 				/* No more access to ire */
20661 				ire = NULL;
20662 			}
20663 			/*
20664 			 * bypass routing checks and go directly to interface.
20665 			 */
20666 			if (connp->conn_dontroute)
20667 				goto dontroute;
20668 
20669 			ASSERT(connp->conn_nexthop_set);
20670 			ip_nexthop = B_TRUE;
20671 			nexthop_addr = connp->conn_nexthop_v4;
20672 			goto send_from_ill;
20673 		}
20674 
20675 		/* Must be a broadcast, a loopback or a local ire */
20676 		ire_refrele(ire);
20677 		/* No more access to ire */
20678 		ire = NULL;
20679 	}
20680 
20681 	/*
20682 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20683 	 * this for the tcp global queue and listen end point
20684 	 * as it does not really have a real destination to
20685 	 * talk to.  This is also true for SCTP.
20686 	 */
20687 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20688 	    !connp->conn_fully_bound) {
20689 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20690 		if (ire == NULL)
20691 			goto noirefound;
20692 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20693 		    "ip_wput_end: q %p (%S)", q, "end");
20694 
20695 		/*
20696 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20697 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20698 		 */
20699 		if (ire->ire_flags & RTF_MULTIRT) {
20700 
20701 			/*
20702 			 * Force the TTL of multirouted packets if required.
20703 			 * The TTL of such packets is bounded by the
20704 			 * ip_multirt_ttl ndd variable.
20705 			 */
20706 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20707 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20708 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20709 				    "(was %d), dst 0x%08x\n",
20710 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20711 				    ntohl(ire->ire_addr)));
20712 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20713 			}
20714 			/*
20715 			 * We look at this point if there are pending
20716 			 * unresolved routes. ire_multirt_resolvable()
20717 			 * checks in O(n) that all IRE_OFFSUBNET ire
20718 			 * entries for the packet's destination and
20719 			 * flagged RTF_MULTIRT are currently resolved.
20720 			 * If some remain unresolved, we make a copy
20721 			 * of the current message. It will be used
20722 			 * to initiate additional route resolutions.
20723 			 */
20724 			multirt_need_resolve =
20725 			    ire_multirt_need_resolve(ire->ire_addr,
20726 			    msg_getlabel(first_mp), ipst);
20727 			ip2dbg(("ip_wput[TCP]: ire %p, "
20728 			    "multirt_need_resolve %d, first_mp %p\n",
20729 			    (void *)ire, multirt_need_resolve,
20730 			    (void *)first_mp));
20731 			if (multirt_need_resolve) {
20732 				copy_mp = copymsg(first_mp);
20733 				if (copy_mp != NULL) {
20734 					MULTIRT_DEBUG_TAG(copy_mp);
20735 				}
20736 			}
20737 		}
20738 
20739 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20740 
20741 		/*
20742 		 * Try to resolve another multiroute if
20743 		 * ire_multirt_need_resolve() deemed it necessary.
20744 		 */
20745 		if (copy_mp != NULL)
20746 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20747 		if (need_decref)
20748 			CONN_DEC_REF(connp);
20749 		return;
20750 	}
20751 
20752 	/*
20753 	 * Access to conn_ire_cache. (protected by conn_lock)
20754 	 *
20755 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20756 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20757 	 * send a packet or two with the IRE_CACHE that is going away.
20758 	 * Access to the ire requires an ire refhold on the ire prior to
20759 	 * its use since an interface unplumb thread may delete the cached
20760 	 * ire and release the refhold at any time.
20761 	 *
20762 	 * Caching an ire in the conn_ire_cache
20763 	 *
20764 	 * o Caching an ire pointer in the conn requires a strict check for
20765 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20766 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20767 	 * in the conn is done after making sure under the bucket lock that the
20768 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20769 	 * caching an ire after the unplumb thread has cleaned up the conn.
20770 	 * If the conn does not send a packet subsequently the unplumb thread
20771 	 * will be hanging waiting for the ire count to drop to zero.
20772 	 *
20773 	 * o We also need to atomically test for a null conn_ire_cache and
20774 	 * set the conn_ire_cache under the the protection of the conn_lock
20775 	 * to avoid races among concurrent threads trying to simultaneously
20776 	 * cache an ire in the conn_ire_cache.
20777 	 */
20778 	mutex_enter(&connp->conn_lock);
20779 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20780 
20781 	if (ire != NULL && ire->ire_addr == dst &&
20782 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20783 
20784 		IRE_REFHOLD(ire);
20785 		mutex_exit(&connp->conn_lock);
20786 
20787 	} else {
20788 		boolean_t cached = B_FALSE;
20789 		connp->conn_ire_cache = NULL;
20790 		mutex_exit(&connp->conn_lock);
20791 		/* Release the old ire */
20792 		if (ire != NULL && sctp_ire == NULL)
20793 			IRE_REFRELE_NOTR(ire);
20794 
20795 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20796 		if (ire == NULL)
20797 			goto noirefound;
20798 		IRE_REFHOLD_NOTR(ire);
20799 
20800 		mutex_enter(&connp->conn_lock);
20801 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20802 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20803 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20804 				if (connp->conn_ulp == IPPROTO_TCP)
20805 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20806 				connp->conn_ire_cache = ire;
20807 				cached = B_TRUE;
20808 			}
20809 			rw_exit(&ire->ire_bucket->irb_lock);
20810 		}
20811 		mutex_exit(&connp->conn_lock);
20812 
20813 		/*
20814 		 * We can continue to use the ire but since it was
20815 		 * not cached, we should drop the extra reference.
20816 		 */
20817 		if (!cached)
20818 			IRE_REFRELE_NOTR(ire);
20819 	}
20820 
20821 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20822 	    "ip_wput_end: q %p (%S)", q, "end");
20823 
20824 	/*
20825 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20826 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20827 	 */
20828 	if (ire->ire_flags & RTF_MULTIRT) {
20829 		/*
20830 		 * Force the TTL of multirouted packets if required.
20831 		 * The TTL of such packets is bounded by the
20832 		 * ip_multirt_ttl ndd variable.
20833 		 */
20834 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20835 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20836 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20837 			    "(was %d), dst 0x%08x\n",
20838 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20839 			    ntohl(ire->ire_addr)));
20840 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20841 		}
20842 
20843 		/*
20844 		 * At this point, we check to see if there are any pending
20845 		 * unresolved routes. ire_multirt_resolvable()
20846 		 * checks in O(n) that all IRE_OFFSUBNET ire
20847 		 * entries for the packet's destination and
20848 		 * flagged RTF_MULTIRT are currently resolved.
20849 		 * If some remain unresolved, we make a copy
20850 		 * of the current message. It will be used
20851 		 * to initiate additional route resolutions.
20852 		 */
20853 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20854 		    msg_getlabel(first_mp), ipst);
20855 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20856 		    "multirt_need_resolve %d, first_mp %p\n",
20857 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20858 		if (multirt_need_resolve) {
20859 			copy_mp = copymsg(first_mp);
20860 			if (copy_mp != NULL) {
20861 				MULTIRT_DEBUG_TAG(copy_mp);
20862 			}
20863 		}
20864 	}
20865 
20866 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20867 
20868 	/*
20869 	 * Try to resolve another multiroute if
20870 	 * ire_multirt_resolvable() deemed it necessary
20871 	 */
20872 	if (copy_mp != NULL)
20873 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20874 	if (need_decref)
20875 		CONN_DEC_REF(connp);
20876 	return;
20877 
20878 qnext:
20879 	/*
20880 	 * Upper Level Protocols pass down complete IP datagrams
20881 	 * as M_DATA messages.	Everything else is a sideshow.
20882 	 *
20883 	 * 1) We could be re-entering ip_wput because of ip_neworute
20884 	 *    in which case we could have a IPSEC_OUT message. We
20885 	 *    need to pass through ip_wput like other datagrams and
20886 	 *    hence cannot branch to ip_wput_nondata.
20887 	 *
20888 	 * 2) ARP, AH, ESP, and other clients who are on the module
20889 	 *    instance of IP stream, give us something to deal with.
20890 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20891 	 *
20892 	 * 3) ICMP replies also could come here.
20893 	 */
20894 	ipst = ILLQ_TO_IPST(q);
20895 
20896 	if (DB_TYPE(mp) != M_DATA) {
20897 notdata:
20898 		if (DB_TYPE(mp) == M_CTL) {
20899 			/*
20900 			 * M_CTL messages are used by ARP, AH and ESP to
20901 			 * communicate with IP. We deal with IPSEC_IN and
20902 			 * IPSEC_OUT here. ip_wput_nondata handles other
20903 			 * cases.
20904 			 */
20905 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20906 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20907 				first_mp = mp->b_cont;
20908 				first_mp->b_flag &= ~MSGHASREF;
20909 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20910 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20911 				CONN_DEC_REF(connp);
20912 				connp = NULL;
20913 			}
20914 			if (ii->ipsec_info_type == IPSEC_IN) {
20915 				/*
20916 				 * Either this message goes back to
20917 				 * IPsec for further processing or to
20918 				 * ULP after policy checks.
20919 				 */
20920 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20921 				return;
20922 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20923 				io = (ipsec_out_t *)ii;
20924 				if (io->ipsec_out_proc_begin) {
20925 					/*
20926 					 * IPsec processing has already started.
20927 					 * Complete it.
20928 					 * IPQoS notes: We don't care what is
20929 					 * in ipsec_out_ill_index since this
20930 					 * won't be processed for IPQoS policies
20931 					 * in ipsec_out_process.
20932 					 */
20933 					ipsec_out_process(q, mp, NULL,
20934 					    io->ipsec_out_ill_index);
20935 					return;
20936 				} else {
20937 					connp = (q->q_next != NULL) ?
20938 					    NULL : Q_TO_CONN(q);
20939 					first_mp = mp;
20940 					mp = mp->b_cont;
20941 					mctl_present = B_TRUE;
20942 				}
20943 				zoneid = io->ipsec_out_zoneid;
20944 				ASSERT(zoneid != ALL_ZONES);
20945 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20946 				/*
20947 				 * It's an IPsec control message requesting
20948 				 * an SADB update to be sent to the IPsec
20949 				 * hardware acceleration capable ills.
20950 				 */
20951 				ipsec_ctl_t *ipsec_ctl =
20952 				    (ipsec_ctl_t *)mp->b_rptr;
20953 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20954 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20955 				mblk_t *cmp = mp->b_cont;
20956 
20957 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20958 				ASSERT(cmp != NULL);
20959 
20960 				freeb(mp);
20961 				ill_ipsec_capab_send_all(satype, cmp, sa,
20962 				    ipst->ips_netstack);
20963 				return;
20964 			} else {
20965 				/*
20966 				 * This must be ARP or special TSOL signaling.
20967 				 */
20968 				ip_wput_nondata(NULL, q, mp, NULL);
20969 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20970 				    "ip_wput_end: q %p (%S)", q, "nondata");
20971 				return;
20972 			}
20973 		} else {
20974 			/*
20975 			 * This must be non-(ARP/AH/ESP) messages.
20976 			 */
20977 			ASSERT(!need_decref);
20978 			ip_wput_nondata(NULL, q, mp, NULL);
20979 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20980 			    "ip_wput_end: q %p (%S)", q, "nondata");
20981 			return;
20982 		}
20983 	} else {
20984 		first_mp = mp;
20985 		mctl_present = B_FALSE;
20986 	}
20987 
20988 	ASSERT(first_mp != NULL);
20989 
20990 	if (mctl_present) {
20991 		io = (ipsec_out_t *)first_mp->b_rptr;
20992 		if (io->ipsec_out_ip_nexthop) {
20993 			/*
20994 			 * We may have lost the conn context if we are
20995 			 * coming here from ip_newroute(). Copy the
20996 			 * nexthop information.
20997 			 */
20998 			ip_nexthop = B_TRUE;
20999 			nexthop_addr = io->ipsec_out_nexthop_addr;
21000 
21001 			ipha = (ipha_t *)mp->b_rptr;
21002 			dst = ipha->ipha_dst;
21003 			goto send_from_ill;
21004 		}
21005 	}
21006 
21007 	ASSERT(xmit_ill == NULL);
21008 
21009 	/* We have a complete IP datagram heading outbound. */
21010 	ipha = (ipha_t *)mp->b_rptr;
21011 
21012 #ifndef SPEED_BEFORE_SAFETY
21013 	/*
21014 	 * Make sure we have a full-word aligned message and that at least
21015 	 * a simple IP header is accessible in the first message.  If not,
21016 	 * try a pullup.  For labeled systems we need to always take this
21017 	 * path as M_CTLs are "notdata" but have trailing data to process.
21018 	 */
21019 	if (!OK_32PTR(rptr) ||
21020 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21021 hdrtoosmall:
21022 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21023 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21024 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21025 			if (first_mp == NULL)
21026 				first_mp = mp;
21027 			goto discard_pkt;
21028 		}
21029 
21030 		/* This function assumes that mp points to an IPv4 packet. */
21031 		if (is_system_labeled() && q->q_next == NULL &&
21032 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21033 		    !connp->conn_ulp_labeled) {
21034 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21035 			    connp->conn_mac_exempt, ipst);
21036 			ipha = (ipha_t *)mp->b_rptr;
21037 			if (first_mp != NULL)
21038 				first_mp->b_cont = mp;
21039 			if (err != 0) {
21040 				if (first_mp == NULL)
21041 					first_mp = mp;
21042 				if (err == EINVAL)
21043 					goto icmp_parameter_problem;
21044 				ip2dbg(("ip_wput: label check failed (%d)\n",
21045 				    err));
21046 				goto discard_pkt;
21047 			}
21048 		}
21049 
21050 		ipha = (ipha_t *)mp->b_rptr;
21051 		if (first_mp == NULL) {
21052 			ASSERT(xmit_ill == NULL);
21053 			/*
21054 			 * If we got here because of "goto hdrtoosmall"
21055 			 * We need to attach a IPSEC_OUT.
21056 			 */
21057 			if (connp->conn_out_enforce_policy) {
21058 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21059 				    NULL, ipha->ipha_protocol,
21060 				    ipst->ips_netstack)) == NULL)) {
21061 					BUMP_MIB(&ipst->ips_ip_mib,
21062 					    ipIfStatsOutDiscards);
21063 					if (need_decref)
21064 						CONN_DEC_REF(connp);
21065 					return;
21066 				} else {
21067 					ASSERT(mp->b_datap->db_type == M_CTL);
21068 					first_mp = mp;
21069 					mp = mp->b_cont;
21070 					mctl_present = B_TRUE;
21071 				}
21072 			} else {
21073 				first_mp = mp;
21074 				mctl_present = B_FALSE;
21075 			}
21076 		}
21077 	}
21078 #endif
21079 
21080 	/* Most of the code below is written for speed, not readability */
21081 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21082 
21083 	/*
21084 	 * If ip_newroute() fails, we're going to need a full
21085 	 * header for the icmp wraparound.
21086 	 */
21087 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21088 		uint_t	v_hlen;
21089 version_hdrlen_check:
21090 		ASSERT(first_mp != NULL);
21091 		v_hlen = V_HLEN;
21092 		/*
21093 		 * siphon off IPv6 packets coming down from transport
21094 		 * layer modules here.
21095 		 * Note: high-order bit carries NUD reachability confirmation
21096 		 */
21097 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21098 			/*
21099 			 * FIXME: assume that callers of ip_output* call
21100 			 * the right version?
21101 			 */
21102 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21103 			ASSERT(xmit_ill == NULL);
21104 			if (need_decref)
21105 				mp->b_flag |= MSGHASREF;
21106 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21107 			return;
21108 		}
21109 
21110 		if ((v_hlen >> 4) != IP_VERSION) {
21111 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21112 			    "ip_wput_end: q %p (%S)", q, "badvers");
21113 			goto discard_pkt;
21114 		}
21115 		/*
21116 		 * Is the header length at least 20 bytes?
21117 		 *
21118 		 * Are there enough bytes accessible in the header?  If
21119 		 * not, try a pullup.
21120 		 */
21121 		v_hlen &= 0xF;
21122 		v_hlen <<= 2;
21123 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21124 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21125 			    "ip_wput_end: q %p (%S)", q, "badlen");
21126 			goto discard_pkt;
21127 		}
21128 		if (v_hlen > (mp->b_wptr - rptr)) {
21129 			if (!pullupmsg(mp, v_hlen)) {
21130 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21131 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21132 				goto discard_pkt;
21133 			}
21134 			ipha = (ipha_t *)mp->b_rptr;
21135 		}
21136 		/*
21137 		 * Move first entry from any source route into ipha_dst and
21138 		 * verify the options
21139 		 */
21140 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21141 		    zoneid, ipst)) {
21142 			ASSERT(xmit_ill == NULL);
21143 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21144 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21145 			    "ip_wput_end: q %p (%S)", q, "badopts");
21146 			if (need_decref)
21147 				CONN_DEC_REF(connp);
21148 			return;
21149 		}
21150 	}
21151 	dst = ipha->ipha_dst;
21152 
21153 	/*
21154 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21155 	 * we have to run the packet through ip_newroute which will take
21156 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21157 	 * a resolver, or assigning a default gateway, etc.
21158 	 */
21159 	if (CLASSD(dst)) {
21160 		ipif_t	*ipif;
21161 		uint32_t setsrc = 0;
21162 
21163 multicast:
21164 		ASSERT(first_mp != NULL);
21165 		ip2dbg(("ip_wput: CLASSD\n"));
21166 		if (connp == NULL) {
21167 			/*
21168 			 * Use the first good ipif on the ill.
21169 			 * XXX Should this ever happen? (Appears
21170 			 * to show up with just ppp and no ethernet due
21171 			 * to in.rdisc.)
21172 			 * However, ire_send should be able to
21173 			 * call ip_wput_ire directly.
21174 			 *
21175 			 * XXX Also, this can happen for ICMP and other packets
21176 			 * with multicast source addresses.  Perhaps we should
21177 			 * fix things so that we drop the packet in question,
21178 			 * but for now, just run with it.
21179 			 */
21180 			ill_t *ill = (ill_t *)q->q_ptr;
21181 
21182 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21183 			if (ipif == NULL) {
21184 				if (need_decref)
21185 					CONN_DEC_REF(connp);
21186 				freemsg(first_mp);
21187 				return;
21188 			}
21189 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21190 			    ntohl(dst), ill->ill_name));
21191 		} else {
21192 			/*
21193 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21194 			 * and IP_MULTICAST_IF.  The block comment above this
21195 			 * function explains the locking mechanism used here.
21196 			 */
21197 			if (xmit_ill == NULL) {
21198 				xmit_ill = conn_get_held_ill(connp,
21199 				    &connp->conn_outgoing_ill, &err);
21200 				if (err == ILL_LOOKUP_FAILED) {
21201 					ip1dbg(("ip_wput: No ill for "
21202 					    "IP_BOUND_IF\n"));
21203 					BUMP_MIB(&ipst->ips_ip_mib,
21204 					    ipIfStatsOutNoRoutes);
21205 					goto drop_pkt;
21206 				}
21207 			}
21208 
21209 			if (xmit_ill == NULL) {
21210 				ipif = conn_get_held_ipif(connp,
21211 				    &connp->conn_multicast_ipif, &err);
21212 				if (err == IPIF_LOOKUP_FAILED) {
21213 					ip1dbg(("ip_wput: No ipif for "
21214 					    "multicast\n"));
21215 					BUMP_MIB(&ipst->ips_ip_mib,
21216 					    ipIfStatsOutNoRoutes);
21217 					goto drop_pkt;
21218 				}
21219 			}
21220 			if (xmit_ill != NULL) {
21221 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21222 				if (ipif == NULL) {
21223 					ip1dbg(("ip_wput: No ipif for "
21224 					    "xmit_ill\n"));
21225 					BUMP_MIB(&ipst->ips_ip_mib,
21226 					    ipIfStatsOutNoRoutes);
21227 					goto drop_pkt;
21228 				}
21229 			} else if (ipif == NULL || ipif->ipif_isv6) {
21230 				/*
21231 				 * We must do this ipif determination here
21232 				 * else we could pass through ip_newroute
21233 				 * and come back here without the conn context.
21234 				 *
21235 				 * Note: we do late binding i.e. we bind to
21236 				 * the interface when the first packet is sent.
21237 				 * For performance reasons we do not rebind on
21238 				 * each packet but keep the binding until the
21239 				 * next IP_MULTICAST_IF option.
21240 				 *
21241 				 * conn_multicast_{ipif,ill} are shared between
21242 				 * IPv4 and IPv6 and AF_INET6 sockets can
21243 				 * send both IPv4 and IPv6 packets. Hence
21244 				 * we have to check that "isv6" matches above.
21245 				 */
21246 				if (ipif != NULL)
21247 					ipif_refrele(ipif);
21248 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21249 				if (ipif == NULL) {
21250 					ip1dbg(("ip_wput: No ipif for "
21251 					    "multicast\n"));
21252 					BUMP_MIB(&ipst->ips_ip_mib,
21253 					    ipIfStatsOutNoRoutes);
21254 					goto drop_pkt;
21255 				}
21256 				err = conn_set_held_ipif(connp,
21257 				    &connp->conn_multicast_ipif, ipif);
21258 				if (err == IPIF_LOOKUP_FAILED) {
21259 					ipif_refrele(ipif);
21260 					ip1dbg(("ip_wput: No ipif for "
21261 					    "multicast\n"));
21262 					BUMP_MIB(&ipst->ips_ip_mib,
21263 					    ipIfStatsOutNoRoutes);
21264 					goto drop_pkt;
21265 				}
21266 			}
21267 		}
21268 		ASSERT(!ipif->ipif_isv6);
21269 		/*
21270 		 * As we may lose the conn by the time we reach ip_wput_ire,
21271 		 * we copy conn_multicast_loop and conn_dontroute on to an
21272 		 * ipsec_out. In case if this datagram goes out secure,
21273 		 * we need the ill_index also. Copy that also into the
21274 		 * ipsec_out.
21275 		 */
21276 		if (mctl_present) {
21277 			io = (ipsec_out_t *)first_mp->b_rptr;
21278 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21279 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21280 		} else {
21281 			ASSERT(mp == first_mp);
21282 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21283 			    BPRI_HI)) == NULL) {
21284 				ipif_refrele(ipif);
21285 				first_mp = mp;
21286 				goto discard_pkt;
21287 			}
21288 			first_mp->b_datap->db_type = M_CTL;
21289 			first_mp->b_wptr += sizeof (ipsec_info_t);
21290 			/* ipsec_out_secure is B_FALSE now */
21291 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21292 			io = (ipsec_out_t *)first_mp->b_rptr;
21293 			io->ipsec_out_type = IPSEC_OUT;
21294 			io->ipsec_out_len = sizeof (ipsec_out_t);
21295 			io->ipsec_out_use_global_policy = B_TRUE;
21296 			io->ipsec_out_ns = ipst->ips_netstack;
21297 			first_mp->b_cont = mp;
21298 			mctl_present = B_TRUE;
21299 		}
21300 
21301 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21302 		io->ipsec_out_ill_index =
21303 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21304 
21305 		if (connp != NULL) {
21306 			io->ipsec_out_multicast_loop =
21307 			    connp->conn_multicast_loop;
21308 			io->ipsec_out_dontroute = connp->conn_dontroute;
21309 			io->ipsec_out_zoneid = connp->conn_zoneid;
21310 		}
21311 		/*
21312 		 * If the application uses IP_MULTICAST_IF with
21313 		 * different logical addresses of the same ILL, we
21314 		 * need to make sure that the soruce address of
21315 		 * the packet matches the logical IP address used
21316 		 * in the option. We do it by initializing ipha_src
21317 		 * here. This should keep IPsec also happy as
21318 		 * when we return from IPsec processing, we don't
21319 		 * have to worry about getting the right address on
21320 		 * the packet. Thus it is sufficient to look for
21321 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21322 		 * MATCH_IRE_IPIF.
21323 		 *
21324 		 * NOTE : We need to do it for non-secure case also as
21325 		 * this might go out secure if there is a global policy
21326 		 * match in ip_wput_ire.
21327 		 *
21328 		 * As we do not have the ire yet, it is possible that
21329 		 * we set the source address here and then later discover
21330 		 * that the ire implies the source address to be assigned
21331 		 * through the RTF_SETSRC flag.
21332 		 * In that case, the setsrc variable will remind us
21333 		 * that overwritting the source address by the one
21334 		 * of the RTF_SETSRC-flagged ire is allowed.
21335 		 */
21336 		if (ipha->ipha_src == INADDR_ANY &&
21337 		    (connp == NULL || !connp->conn_unspec_src)) {
21338 			ipha->ipha_src = ipif->ipif_src_addr;
21339 			setsrc = RTF_SETSRC;
21340 		}
21341 		/*
21342 		 * Find an IRE which matches the destination and the outgoing
21343 		 * queue (i.e. the outgoing interface.)
21344 		 * For loopback use a unicast IP address for
21345 		 * the ire lookup.
21346 		 */
21347 		if (IS_LOOPBACK(ipif->ipif_ill))
21348 			dst = ipif->ipif_lcl_addr;
21349 
21350 		/*
21351 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21352 		 * We don't need to lookup ire in ctable as the packet
21353 		 * needs to be sent to the destination through the specified
21354 		 * ill irrespective of ires in the cache table.
21355 		 */
21356 		ire = NULL;
21357 		if (xmit_ill == NULL) {
21358 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21359 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21360 		}
21361 
21362 		if (ire == NULL) {
21363 			/*
21364 			 * Multicast loopback and multicast forwarding is
21365 			 * done in ip_wput_ire.
21366 			 *
21367 			 * Mark this packet to make it be delivered to
21368 			 * ip_wput_ire after the new ire has been
21369 			 * created.
21370 			 *
21371 			 * The call to ip_newroute_ipif takes into account
21372 			 * the setsrc reminder. In any case, we take care
21373 			 * of the RTF_MULTIRT flag.
21374 			 */
21375 			mp->b_prev = mp->b_next = NULL;
21376 			if (xmit_ill == NULL ||
21377 			    xmit_ill->ill_ipif_up_count > 0) {
21378 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21379 				    setsrc | RTF_MULTIRT, zoneid, infop);
21380 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21381 				    "ip_wput_end: q %p (%S)", q, "noire");
21382 			} else {
21383 				freemsg(first_mp);
21384 			}
21385 			ipif_refrele(ipif);
21386 			if (xmit_ill != NULL)
21387 				ill_refrele(xmit_ill);
21388 			if (need_decref)
21389 				CONN_DEC_REF(connp);
21390 			return;
21391 		}
21392 
21393 		ipif_refrele(ipif);
21394 		ipif = NULL;
21395 		ASSERT(xmit_ill == NULL);
21396 
21397 		/*
21398 		 * Honor the RTF_SETSRC flag for multicast packets,
21399 		 * if allowed by the setsrc reminder.
21400 		 */
21401 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21402 			ipha->ipha_src = ire->ire_src_addr;
21403 		}
21404 
21405 		/*
21406 		 * Unconditionally force the TTL to 1 for
21407 		 * multirouted multicast packets:
21408 		 * multirouted multicast should not cross
21409 		 * multicast routers.
21410 		 */
21411 		if (ire->ire_flags & RTF_MULTIRT) {
21412 			if (ipha->ipha_ttl > 1) {
21413 				ip2dbg(("ip_wput: forcing multicast "
21414 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21415 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21416 				ipha->ipha_ttl = 1;
21417 			}
21418 		}
21419 	} else {
21420 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21421 		if ((ire != NULL) && (ire->ire_type &
21422 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21423 			ignore_dontroute = B_TRUE;
21424 			ignore_nexthop = B_TRUE;
21425 		}
21426 		if (ire != NULL) {
21427 			ire_refrele(ire);
21428 			ire = NULL;
21429 		}
21430 		/*
21431 		 * Guard against coming in from arp in which case conn is NULL.
21432 		 * Also guard against non M_DATA with dontroute set but
21433 		 * destined to local, loopback or broadcast addresses.
21434 		 */
21435 		if (connp != NULL && connp->conn_dontroute &&
21436 		    !ignore_dontroute) {
21437 dontroute:
21438 			/*
21439 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21440 			 * routing protocols from seeing false direct
21441 			 * connectivity.
21442 			 */
21443 			ipha->ipha_ttl = 1;
21444 			/* If suitable ipif not found, drop packet */
21445 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21446 			if (dst_ipif == NULL) {
21447 noroute:
21448 				ip1dbg(("ip_wput: no route for dst using"
21449 				    " SO_DONTROUTE\n"));
21450 				BUMP_MIB(&ipst->ips_ip_mib,
21451 				    ipIfStatsOutNoRoutes);
21452 				mp->b_prev = mp->b_next = NULL;
21453 				if (first_mp == NULL)
21454 					first_mp = mp;
21455 				goto drop_pkt;
21456 			} else {
21457 				/*
21458 				 * If suitable ipif has been found, set
21459 				 * xmit_ill to the corresponding
21460 				 * ipif_ill because we'll be using the
21461 				 * send_from_ill logic below.
21462 				 */
21463 				ASSERT(xmit_ill == NULL);
21464 				xmit_ill = dst_ipif->ipif_ill;
21465 				mutex_enter(&xmit_ill->ill_lock);
21466 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21467 					mutex_exit(&xmit_ill->ill_lock);
21468 					xmit_ill = NULL;
21469 					ipif_refrele(dst_ipif);
21470 					goto noroute;
21471 				}
21472 				ill_refhold_locked(xmit_ill);
21473 				mutex_exit(&xmit_ill->ill_lock);
21474 				ipif_refrele(dst_ipif);
21475 			}
21476 		}
21477 
21478 send_from_ill:
21479 		if (xmit_ill != NULL) {
21480 			ipif_t *ipif;
21481 
21482 			/*
21483 			 * Mark this packet as originated locally
21484 			 */
21485 			mp->b_prev = mp->b_next = NULL;
21486 
21487 			/*
21488 			 * Could be SO_DONTROUTE case also.
21489 			 * Verify that at least one ipif is up on the ill.
21490 			 */
21491 			if (xmit_ill->ill_ipif_up_count == 0) {
21492 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21493 				    xmit_ill->ill_name));
21494 				goto drop_pkt;
21495 			}
21496 
21497 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21498 			if (ipif == NULL) {
21499 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21500 				    xmit_ill->ill_name));
21501 				goto drop_pkt;
21502 			}
21503 
21504 			match_flags = 0;
21505 			if (IS_UNDER_IPMP(xmit_ill))
21506 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21507 
21508 			/*
21509 			 * Look for a ire that is part of the group,
21510 			 * if found use it else call ip_newroute_ipif.
21511 			 * IPCL_ZONEID is not used for matching because
21512 			 * IP_ALLZONES option is valid only when the
21513 			 * ill is accessible from all zones i.e has a
21514 			 * valid ipif in all zones.
21515 			 */
21516 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21517 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21518 			    msg_getlabel(mp), match_flags, ipst);
21519 			/*
21520 			 * If an ire exists use it or else create
21521 			 * an ire but don't add it to the cache.
21522 			 * Adding an ire may cause issues with
21523 			 * asymmetric routing.
21524 			 * In case of multiroute always act as if
21525 			 * ire does not exist.
21526 			 */
21527 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21528 				if (ire != NULL)
21529 					ire_refrele(ire);
21530 				ip_newroute_ipif(q, first_mp, ipif,
21531 				    dst, connp, 0, zoneid, infop);
21532 				ipif_refrele(ipif);
21533 				ip1dbg(("ip_output: xmit_ill via %s\n",
21534 				    xmit_ill->ill_name));
21535 				ill_refrele(xmit_ill);
21536 				if (need_decref)
21537 					CONN_DEC_REF(connp);
21538 				return;
21539 			}
21540 			ipif_refrele(ipif);
21541 		} else if (ip_nexthop || (connp != NULL &&
21542 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21543 			if (!ip_nexthop) {
21544 				ip_nexthop = B_TRUE;
21545 				nexthop_addr = connp->conn_nexthop_v4;
21546 			}
21547 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21548 			    MATCH_IRE_GW;
21549 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21550 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21551 		} else {
21552 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21553 			    ipst);
21554 		}
21555 		if (!ire) {
21556 			if (ip_nexthop && !ignore_nexthop) {
21557 				if (mctl_present) {
21558 					io = (ipsec_out_t *)first_mp->b_rptr;
21559 					ASSERT(first_mp->b_datap->db_type ==
21560 					    M_CTL);
21561 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21562 				} else {
21563 					ASSERT(mp == first_mp);
21564 					first_mp = allocb(
21565 					    sizeof (ipsec_info_t), BPRI_HI);
21566 					if (first_mp == NULL) {
21567 						first_mp = mp;
21568 						goto discard_pkt;
21569 					}
21570 					first_mp->b_datap->db_type = M_CTL;
21571 					first_mp->b_wptr +=
21572 					    sizeof (ipsec_info_t);
21573 					/* ipsec_out_secure is B_FALSE now */
21574 					bzero(first_mp->b_rptr,
21575 					    sizeof (ipsec_info_t));
21576 					io = (ipsec_out_t *)first_mp->b_rptr;
21577 					io->ipsec_out_type = IPSEC_OUT;
21578 					io->ipsec_out_len =
21579 					    sizeof (ipsec_out_t);
21580 					io->ipsec_out_use_global_policy =
21581 					    B_TRUE;
21582 					io->ipsec_out_ns = ipst->ips_netstack;
21583 					first_mp->b_cont = mp;
21584 					mctl_present = B_TRUE;
21585 				}
21586 				io->ipsec_out_ip_nexthop = ip_nexthop;
21587 				io->ipsec_out_nexthop_addr = nexthop_addr;
21588 			}
21589 noirefound:
21590 			/*
21591 			 * Mark this packet as having originated on
21592 			 * this machine.  This will be noted in
21593 			 * ire_add_then_send, which needs to know
21594 			 * whether to run it back through ip_wput or
21595 			 * ip_rput following successful resolution.
21596 			 */
21597 			mp->b_prev = NULL;
21598 			mp->b_next = NULL;
21599 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21600 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21601 			    "ip_wput_end: q %p (%S)", q, "newroute");
21602 			if (xmit_ill != NULL)
21603 				ill_refrele(xmit_ill);
21604 			if (need_decref)
21605 				CONN_DEC_REF(connp);
21606 			return;
21607 		}
21608 	}
21609 
21610 	/* We now know where we are going with it. */
21611 
21612 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21613 	    "ip_wput_end: q %p (%S)", q, "end");
21614 
21615 	/*
21616 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21617 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21618 	 */
21619 	if (ire->ire_flags & RTF_MULTIRT) {
21620 		/*
21621 		 * Force the TTL of multirouted packets if required.
21622 		 * The TTL of such packets is bounded by the
21623 		 * ip_multirt_ttl ndd variable.
21624 		 */
21625 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21626 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21627 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21628 			    "(was %d), dst 0x%08x\n",
21629 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21630 			    ntohl(ire->ire_addr)));
21631 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21632 		}
21633 		/*
21634 		 * At this point, we check to see if there are any pending
21635 		 * unresolved routes. ire_multirt_resolvable()
21636 		 * checks in O(n) that all IRE_OFFSUBNET ire
21637 		 * entries for the packet's destination and
21638 		 * flagged RTF_MULTIRT are currently resolved.
21639 		 * If some remain unresolved, we make a copy
21640 		 * of the current message. It will be used
21641 		 * to initiate additional route resolutions.
21642 		 */
21643 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21644 		    msg_getlabel(first_mp), ipst);
21645 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21646 		    "multirt_need_resolve %d, first_mp %p\n",
21647 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21648 		if (multirt_need_resolve) {
21649 			copy_mp = copymsg(first_mp);
21650 			if (copy_mp != NULL) {
21651 				MULTIRT_DEBUG_TAG(copy_mp);
21652 			}
21653 		}
21654 	}
21655 
21656 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21657 	/*
21658 	 * Try to resolve another multiroute if
21659 	 * ire_multirt_resolvable() deemed it necessary.
21660 	 * At this point, we need to distinguish
21661 	 * multicasts from other packets. For multicasts,
21662 	 * we call ip_newroute_ipif() and request that both
21663 	 * multirouting and setsrc flags are checked.
21664 	 */
21665 	if (copy_mp != NULL) {
21666 		if (CLASSD(dst)) {
21667 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21668 			if (ipif) {
21669 				ASSERT(infop->ip_opt_ill_index == 0);
21670 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21671 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21672 				ipif_refrele(ipif);
21673 			} else {
21674 				MULTIRT_DEBUG_UNTAG(copy_mp);
21675 				freemsg(copy_mp);
21676 				copy_mp = NULL;
21677 			}
21678 		} else {
21679 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21680 		}
21681 	}
21682 	if (xmit_ill != NULL)
21683 		ill_refrele(xmit_ill);
21684 	if (need_decref)
21685 		CONN_DEC_REF(connp);
21686 	return;
21687 
21688 icmp_parameter_problem:
21689 	/* could not have originated externally */
21690 	ASSERT(mp->b_prev == NULL);
21691 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21692 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21693 		/* it's the IP header length that's in trouble */
21694 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21695 		first_mp = NULL;
21696 	}
21697 
21698 discard_pkt:
21699 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21700 drop_pkt:
21701 	ip1dbg(("ip_wput: dropped packet\n"));
21702 	if (ire != NULL)
21703 		ire_refrele(ire);
21704 	if (need_decref)
21705 		CONN_DEC_REF(connp);
21706 	freemsg(first_mp);
21707 	if (xmit_ill != NULL)
21708 		ill_refrele(xmit_ill);
21709 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21710 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21711 }
21712 
21713 /*
21714  * If this is a conn_t queue, then we pass in the conn. This includes the
21715  * zoneid.
21716  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21717  * in which case we use the global zoneid since those are all part of
21718  * the global zone.
21719  */
21720 void
21721 ip_wput(queue_t *q, mblk_t *mp)
21722 {
21723 	if (CONN_Q(q))
21724 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21725 	else
21726 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21727 }
21728 
21729 /*
21730  *
21731  * The following rules must be observed when accessing any ipif or ill
21732  * that has been cached in the conn. Typically conn_outgoing_ill,
21733  * conn_multicast_ipif and conn_multicast_ill.
21734  *
21735  * Access: The ipif or ill pointed to from the conn can be accessed under
21736  * the protection of the conn_lock or after it has been refheld under the
21737  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21738  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21739  * The reason for this is that a concurrent unplumb could actually be
21740  * cleaning up these cached pointers by walking the conns and might have
21741  * finished cleaning up the conn in question. The macros check that an
21742  * unplumb has not yet started on the ipif or ill.
21743  *
21744  * Caching: An ipif or ill pointer may be cached in the conn only after
21745  * making sure that an unplumb has not started. So the caching is done
21746  * while holding both the conn_lock and the ill_lock and after using the
21747  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21748  * flag before starting the cleanup of conns.
21749  *
21750  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21751  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21752  * or a reference to the ipif or a reference to an ire that references the
21753  * ipif. An ipif only changes its ill when migrating from an underlying ill
21754  * to an IPMP ill in ipif_up().
21755  */
21756 ipif_t *
21757 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21758 {
21759 	ipif_t	*ipif;
21760 	ill_t	*ill;
21761 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21762 
21763 	*err = 0;
21764 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21765 	mutex_enter(&connp->conn_lock);
21766 	ipif = *ipifp;
21767 	if (ipif != NULL) {
21768 		ill = ipif->ipif_ill;
21769 		mutex_enter(&ill->ill_lock);
21770 		if (IPIF_CAN_LOOKUP(ipif)) {
21771 			ipif_refhold_locked(ipif);
21772 			mutex_exit(&ill->ill_lock);
21773 			mutex_exit(&connp->conn_lock);
21774 			rw_exit(&ipst->ips_ill_g_lock);
21775 			return (ipif);
21776 		} else {
21777 			*err = IPIF_LOOKUP_FAILED;
21778 		}
21779 		mutex_exit(&ill->ill_lock);
21780 	}
21781 	mutex_exit(&connp->conn_lock);
21782 	rw_exit(&ipst->ips_ill_g_lock);
21783 	return (NULL);
21784 }
21785 
21786 ill_t *
21787 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21788 {
21789 	ill_t	*ill;
21790 
21791 	*err = 0;
21792 	mutex_enter(&connp->conn_lock);
21793 	ill = *illp;
21794 	if (ill != NULL) {
21795 		mutex_enter(&ill->ill_lock);
21796 		if (ILL_CAN_LOOKUP(ill)) {
21797 			ill_refhold_locked(ill);
21798 			mutex_exit(&ill->ill_lock);
21799 			mutex_exit(&connp->conn_lock);
21800 			return (ill);
21801 		} else {
21802 			*err = ILL_LOOKUP_FAILED;
21803 		}
21804 		mutex_exit(&ill->ill_lock);
21805 	}
21806 	mutex_exit(&connp->conn_lock);
21807 	return (NULL);
21808 }
21809 
21810 static int
21811 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21812 {
21813 	ill_t	*ill;
21814 
21815 	ill = ipif->ipif_ill;
21816 	mutex_enter(&connp->conn_lock);
21817 	mutex_enter(&ill->ill_lock);
21818 	if (IPIF_CAN_LOOKUP(ipif)) {
21819 		*ipifp = ipif;
21820 		mutex_exit(&ill->ill_lock);
21821 		mutex_exit(&connp->conn_lock);
21822 		return (0);
21823 	}
21824 	mutex_exit(&ill->ill_lock);
21825 	mutex_exit(&connp->conn_lock);
21826 	return (IPIF_LOOKUP_FAILED);
21827 }
21828 
21829 /*
21830  * This is called if the outbound datagram needs fragmentation.
21831  *
21832  * NOTE : This function does not ire_refrele the ire argument passed in.
21833  */
21834 static void
21835 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21836     ip_stack_t *ipst, conn_t *connp)
21837 {
21838 	ipha_t		*ipha;
21839 	mblk_t		*mp;
21840 	uint32_t	v_hlen_tos_len;
21841 	uint32_t	max_frag;
21842 	uint32_t	frag_flag;
21843 	boolean_t	dont_use;
21844 
21845 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21846 		mp = ipsec_mp->b_cont;
21847 	} else {
21848 		mp = ipsec_mp;
21849 	}
21850 
21851 	ipha = (ipha_t *)mp->b_rptr;
21852 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21853 
21854 #ifdef	_BIG_ENDIAN
21855 #define	V_HLEN	(v_hlen_tos_len >> 24)
21856 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21857 #else
21858 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21859 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21860 #endif
21861 
21862 #ifndef SPEED_BEFORE_SAFETY
21863 	/*
21864 	 * Check that ipha_length is consistent with
21865 	 * the mblk length
21866 	 */
21867 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21868 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21869 		    LENGTH, msgdsize(mp)));
21870 		freemsg(ipsec_mp);
21871 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21872 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21873 		    "packet length mismatch");
21874 		return;
21875 	}
21876 #endif
21877 	/*
21878 	 * Don't use frag_flag if pre-built packet or source
21879 	 * routed or if multicast (since multicast packets do not solicit
21880 	 * ICMP "packet too big" messages). Get the values of
21881 	 * max_frag and frag_flag atomically by acquiring the
21882 	 * ire_lock.
21883 	 */
21884 	mutex_enter(&ire->ire_lock);
21885 	max_frag = ire->ire_max_frag;
21886 	frag_flag = ire->ire_frag_flag;
21887 	mutex_exit(&ire->ire_lock);
21888 
21889 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21890 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21891 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21892 
21893 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21894 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21895 }
21896 
21897 /*
21898  * Used for deciding the MSS size for the upper layer. Thus
21899  * we need to check the outbound policy values in the conn.
21900  */
21901 int
21902 conn_ipsec_length(conn_t *connp)
21903 {
21904 	ipsec_latch_t *ipl;
21905 
21906 	ipl = connp->conn_latch;
21907 	if (ipl == NULL)
21908 		return (0);
21909 
21910 	if (ipl->ipl_out_policy == NULL)
21911 		return (0);
21912 
21913 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21914 }
21915 
21916 /*
21917  * Returns an estimate of the IPsec headers size. This is used if
21918  * we don't want to call into IPsec to get the exact size.
21919  */
21920 int
21921 ipsec_out_extra_length(mblk_t *ipsec_mp)
21922 {
21923 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21924 	ipsec_action_t *a;
21925 
21926 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21927 	if (!io->ipsec_out_secure)
21928 		return (0);
21929 
21930 	a = io->ipsec_out_act;
21931 
21932 	if (a == NULL) {
21933 		ASSERT(io->ipsec_out_policy != NULL);
21934 		a = io->ipsec_out_policy->ipsp_act;
21935 	}
21936 	ASSERT(a != NULL);
21937 
21938 	return (a->ipa_ovhd);
21939 }
21940 
21941 /*
21942  * Returns an estimate of the IPsec headers size. This is used if
21943  * we don't want to call into IPsec to get the exact size.
21944  */
21945 int
21946 ipsec_in_extra_length(mblk_t *ipsec_mp)
21947 {
21948 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21949 	ipsec_action_t *a;
21950 
21951 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21952 
21953 	a = ii->ipsec_in_action;
21954 	return (a == NULL ? 0 : a->ipa_ovhd);
21955 }
21956 
21957 /*
21958  * If there are any source route options, return the true final
21959  * destination. Otherwise, return the destination.
21960  */
21961 ipaddr_t
21962 ip_get_dst(ipha_t *ipha)
21963 {
21964 	ipoptp_t	opts;
21965 	uchar_t		*opt;
21966 	uint8_t		optval;
21967 	uint8_t		optlen;
21968 	ipaddr_t	dst;
21969 	uint32_t off;
21970 
21971 	dst = ipha->ipha_dst;
21972 
21973 	if (IS_SIMPLE_IPH(ipha))
21974 		return (dst);
21975 
21976 	for (optval = ipoptp_first(&opts, ipha);
21977 	    optval != IPOPT_EOL;
21978 	    optval = ipoptp_next(&opts)) {
21979 		opt = opts.ipoptp_cur;
21980 		optlen = opts.ipoptp_len;
21981 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21982 		switch (optval) {
21983 		case IPOPT_SSRR:
21984 		case IPOPT_LSRR:
21985 			off = opt[IPOPT_OFFSET];
21986 			/*
21987 			 * If one of the conditions is true, it means
21988 			 * end of options and dst already has the right
21989 			 * value.
21990 			 */
21991 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21992 				off = optlen - IP_ADDR_LEN;
21993 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21994 			}
21995 			return (dst);
21996 		default:
21997 			break;
21998 		}
21999 	}
22000 
22001 	return (dst);
22002 }
22003 
22004 mblk_t *
22005 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22006     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22007 {
22008 	ipsec_out_t	*io;
22009 	mblk_t		*first_mp;
22010 	boolean_t policy_present;
22011 	ip_stack_t	*ipst;
22012 	ipsec_stack_t	*ipss;
22013 
22014 	ASSERT(ire != NULL);
22015 	ipst = ire->ire_ipst;
22016 	ipss = ipst->ips_netstack->netstack_ipsec;
22017 
22018 	first_mp = mp;
22019 	if (mp->b_datap->db_type == M_CTL) {
22020 		io = (ipsec_out_t *)first_mp->b_rptr;
22021 		/*
22022 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22023 		 *
22024 		 * 1) There is per-socket policy (including cached global
22025 		 *    policy) or a policy on the IP-in-IP tunnel.
22026 		 * 2) There is no per-socket policy, but it is
22027 		 *    a multicast packet that needs to go out
22028 		 *    on a specific interface. This is the case
22029 		 *    where (ip_wput and ip_wput_multicast) attaches
22030 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22031 		 *
22032 		 * In case (2) we check with global policy to
22033 		 * see if there is a match and set the ill_index
22034 		 * appropriately so that we can lookup the ire
22035 		 * properly in ip_wput_ipsec_out.
22036 		 */
22037 
22038 		/*
22039 		 * ipsec_out_use_global_policy is set to B_FALSE
22040 		 * in ipsec_in_to_out(). Refer to that function for
22041 		 * details.
22042 		 */
22043 		if ((io->ipsec_out_latch == NULL) &&
22044 		    (io->ipsec_out_use_global_policy)) {
22045 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22046 			    ire, connp, unspec_src, zoneid));
22047 		}
22048 		if (!io->ipsec_out_secure) {
22049 			/*
22050 			 * If this is not a secure packet, drop
22051 			 * the IPSEC_OUT mp and treat it as a clear
22052 			 * packet. This happens when we are sending
22053 			 * a ICMP reply back to a clear packet. See
22054 			 * ipsec_in_to_out() for details.
22055 			 */
22056 			mp = first_mp->b_cont;
22057 			freeb(first_mp);
22058 		}
22059 		return (mp);
22060 	}
22061 	/*
22062 	 * See whether we need to attach a global policy here. We
22063 	 * don't depend on the conn (as it could be null) for deciding
22064 	 * what policy this datagram should go through because it
22065 	 * should have happened in ip_wput if there was some
22066 	 * policy. This normally happens for connections which are not
22067 	 * fully bound preventing us from caching policies in
22068 	 * ip_bind. Packets coming from the TCP listener/global queue
22069 	 * - which are non-hard_bound - could also be affected by
22070 	 * applying policy here.
22071 	 *
22072 	 * If this packet is coming from tcp global queue or listener,
22073 	 * we will be applying policy here.  This may not be *right*
22074 	 * if these packets are coming from the detached connection as
22075 	 * it could have gone in clear before. This happens only if a
22076 	 * TCP connection started when there is no policy and somebody
22077 	 * added policy before it became detached. Thus packets of the
22078 	 * detached connection could go out secure and the other end
22079 	 * would drop it because it will be expecting in clear. The
22080 	 * converse is not true i.e if somebody starts a TCP
22081 	 * connection and deletes the policy, all the packets will
22082 	 * still go out with the policy that existed before deleting
22083 	 * because ip_unbind sends up policy information which is used
22084 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22085 	 * TCP to attach a dummy IPSEC_OUT and set
22086 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22087 	 * affect performance for normal cases, we are not doing it.
22088 	 * Thus, set policy before starting any TCP connections.
22089 	 *
22090 	 * NOTE - We might apply policy even for a hard bound connection
22091 	 * - for which we cached policy in ip_bind - if somebody added
22092 	 * global policy after we inherited the policy in ip_bind.
22093 	 * This means that the packets that were going out in clear
22094 	 * previously would start going secure and hence get dropped
22095 	 * on the other side. To fix this, TCP attaches a dummy
22096 	 * ipsec_out and make sure that we don't apply global policy.
22097 	 */
22098 	if (ipha != NULL)
22099 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22100 	else
22101 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22102 	if (!policy_present)
22103 		return (mp);
22104 
22105 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22106 	    zoneid));
22107 }
22108 
22109 /*
22110  * This function does the ire_refrele of the ire passed in as the
22111  * argument. As this function looks up more ires i.e broadcast ires,
22112  * it needs to REFRELE them. Currently, for simplicity we don't
22113  * differentiate the one passed in and looked up here. We always
22114  * REFRELE.
22115  * IPQoS Notes:
22116  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22117  * IPsec packets are done in ipsec_out_process.
22118  */
22119 void
22120 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22121     zoneid_t zoneid)
22122 {
22123 	ipha_t		*ipha;
22124 #define	rptr	((uchar_t *)ipha)
22125 	queue_t		*stq;
22126 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22127 	uint32_t	v_hlen_tos_len;
22128 	uint32_t	ttl_protocol;
22129 	ipaddr_t	src;
22130 	ipaddr_t	dst;
22131 	uint32_t	cksum;
22132 	ipaddr_t	orig_src;
22133 	ire_t		*ire1;
22134 	mblk_t		*next_mp;
22135 	uint_t		hlen;
22136 	uint16_t	*up;
22137 	uint32_t	max_frag = ire->ire_max_frag;
22138 	ill_t		*ill = ire_to_ill(ire);
22139 	int		clusterwide;
22140 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22141 	int		ipsec_len;
22142 	mblk_t		*first_mp;
22143 	ipsec_out_t	*io;
22144 	boolean_t	conn_dontroute;		/* conn value for multicast */
22145 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22146 	boolean_t	multicast_forward;	/* Should we forward ? */
22147 	boolean_t	unspec_src;
22148 	ill_t		*conn_outgoing_ill = NULL;
22149 	ill_t		*ire_ill;
22150 	ill_t		*ire1_ill;
22151 	ill_t		*out_ill;
22152 	uint32_t 	ill_index = 0;
22153 	boolean_t	multirt_send = B_FALSE;
22154 	int		err;
22155 	ipxmit_state_t	pktxmit_state;
22156 	ip_stack_t	*ipst = ire->ire_ipst;
22157 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22158 
22159 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22160 	    "ip_wput_ire_start: q %p", q);
22161 
22162 	multicast_forward = B_FALSE;
22163 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22164 
22165 	if (ire->ire_flags & RTF_MULTIRT) {
22166 		/*
22167 		 * Multirouting case. The bucket where ire is stored
22168 		 * probably holds other RTF_MULTIRT flagged ire
22169 		 * to the destination. In this call to ip_wput_ire,
22170 		 * we attempt to send the packet through all
22171 		 * those ires. Thus, we first ensure that ire is the
22172 		 * first RTF_MULTIRT ire in the bucket,
22173 		 * before walking the ire list.
22174 		 */
22175 		ire_t *first_ire;
22176 		irb_t *irb = ire->ire_bucket;
22177 		ASSERT(irb != NULL);
22178 
22179 		/* Make sure we do not omit any multiroute ire. */
22180 		IRB_REFHOLD(irb);
22181 		for (first_ire = irb->irb_ire;
22182 		    first_ire != NULL;
22183 		    first_ire = first_ire->ire_next) {
22184 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22185 			    (first_ire->ire_addr == ire->ire_addr) &&
22186 			    !(first_ire->ire_marks &
22187 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22188 				break;
22189 		}
22190 
22191 		if ((first_ire != NULL) && (first_ire != ire)) {
22192 			IRE_REFHOLD(first_ire);
22193 			ire_refrele(ire);
22194 			ire = first_ire;
22195 			ill = ire_to_ill(ire);
22196 		}
22197 		IRB_REFRELE(irb);
22198 	}
22199 
22200 	/*
22201 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22202 	 * for performance we don't grab the mutexs in the fastpath
22203 	 */
22204 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22205 	    connp->conn_outgoing_ill != NULL) {
22206 		conn_outgoing_ill = conn_get_held_ill(connp,
22207 		    &connp->conn_outgoing_ill, &err);
22208 		if (err == ILL_LOOKUP_FAILED) {
22209 			ire_refrele(ire);
22210 			freemsg(mp);
22211 			return;
22212 		}
22213 	}
22214 
22215 	if (mp->b_datap->db_type != M_CTL) {
22216 		ipha = (ipha_t *)mp->b_rptr;
22217 	} else {
22218 		io = (ipsec_out_t *)mp->b_rptr;
22219 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22220 		ASSERT(zoneid == io->ipsec_out_zoneid);
22221 		ASSERT(zoneid != ALL_ZONES);
22222 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22223 		dst = ipha->ipha_dst;
22224 		/*
22225 		 * For the multicast case, ipsec_out carries conn_dontroute and
22226 		 * conn_multicast_loop as conn may not be available here. We
22227 		 * need this for multicast loopback and forwarding which is done
22228 		 * later in the code.
22229 		 */
22230 		if (CLASSD(dst)) {
22231 			conn_dontroute = io->ipsec_out_dontroute;
22232 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22233 			/*
22234 			 * If conn_dontroute is not set or conn_multicast_loop
22235 			 * is set, we need to do forwarding/loopback. For
22236 			 * datagrams from ip_wput_multicast, conn_dontroute is
22237 			 * set to B_TRUE and conn_multicast_loop is set to
22238 			 * B_FALSE so that we neither do forwarding nor
22239 			 * loopback.
22240 			 */
22241 			if (!conn_dontroute || conn_multicast_loop)
22242 				multicast_forward = B_TRUE;
22243 		}
22244 	}
22245 
22246 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22247 	    ire->ire_zoneid != ALL_ZONES) {
22248 		/*
22249 		 * When a zone sends a packet to another zone, we try to deliver
22250 		 * the packet under the same conditions as if the destination
22251 		 * was a real node on the network. To do so, we look for a
22252 		 * matching route in the forwarding table.
22253 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22254 		 * ip_newroute() does.
22255 		 * Note that IRE_LOCAL are special, since they are used
22256 		 * when the zoneid doesn't match in some cases. This means that
22257 		 * we need to handle ipha_src differently since ire_src_addr
22258 		 * belongs to the receiving zone instead of the sending zone.
22259 		 * When ip_restrict_interzone_loopback is set, then
22260 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22261 		 * for loopback between zones when the logical "Ethernet" would
22262 		 * have looped them back.
22263 		 */
22264 		ire_t *src_ire;
22265 
22266 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22267 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22268 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22269 		if (src_ire != NULL &&
22270 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22271 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22272 		    ire_local_same_lan(ire, src_ire))) {
22273 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22274 				ipha->ipha_src = src_ire->ire_src_addr;
22275 			ire_refrele(src_ire);
22276 		} else {
22277 			ire_refrele(ire);
22278 			if (conn_outgoing_ill != NULL)
22279 				ill_refrele(conn_outgoing_ill);
22280 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22281 			if (src_ire != NULL) {
22282 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22283 					ire_refrele(src_ire);
22284 					freemsg(mp);
22285 					return;
22286 				}
22287 				ire_refrele(src_ire);
22288 			}
22289 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22290 				/* Failed */
22291 				freemsg(mp);
22292 				return;
22293 			}
22294 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22295 			    ipst);
22296 			return;
22297 		}
22298 	}
22299 
22300 	if (mp->b_datap->db_type == M_CTL ||
22301 	    ipss->ipsec_outbound_v4_policy_present) {
22302 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22303 		    unspec_src, zoneid);
22304 		if (mp == NULL) {
22305 			ire_refrele(ire);
22306 			if (conn_outgoing_ill != NULL)
22307 				ill_refrele(conn_outgoing_ill);
22308 			return;
22309 		}
22310 		/*
22311 		 * Trusted Extensions supports all-zones interfaces, so
22312 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22313 		 * the global zone.
22314 		 */
22315 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22316 			io = (ipsec_out_t *)mp->b_rptr;
22317 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22318 			zoneid = io->ipsec_out_zoneid;
22319 		}
22320 	}
22321 
22322 	first_mp = mp;
22323 	ipsec_len = 0;
22324 
22325 	if (first_mp->b_datap->db_type == M_CTL) {
22326 		io = (ipsec_out_t *)first_mp->b_rptr;
22327 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22328 		mp = first_mp->b_cont;
22329 		ipsec_len = ipsec_out_extra_length(first_mp);
22330 		ASSERT(ipsec_len >= 0);
22331 		/* We already picked up the zoneid from the M_CTL above */
22332 		ASSERT(zoneid == io->ipsec_out_zoneid);
22333 		ASSERT(zoneid != ALL_ZONES);
22334 
22335 		/*
22336 		 * Drop M_CTL here if IPsec processing is not needed.
22337 		 * (Non-IPsec use of M_CTL extracted any information it
22338 		 * needed above).
22339 		 */
22340 		if (ipsec_len == 0) {
22341 			freeb(first_mp);
22342 			first_mp = mp;
22343 		}
22344 	}
22345 
22346 	/*
22347 	 * Fast path for ip_wput_ire
22348 	 */
22349 
22350 	ipha = (ipha_t *)mp->b_rptr;
22351 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22352 	dst = ipha->ipha_dst;
22353 
22354 	/*
22355 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22356 	 * if the socket is a SOCK_RAW type. The transport checksum should
22357 	 * be provided in the pre-built packet, so we don't need to compute it.
22358 	 * Also, other application set flags, like DF, should not be altered.
22359 	 * Other transport MUST pass down zero.
22360 	 */
22361 	ip_hdr_included = ipha->ipha_ident;
22362 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22363 
22364 	if (CLASSD(dst)) {
22365 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22366 		    ntohl(dst),
22367 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22368 		    ntohl(ire->ire_addr)));
22369 	}
22370 
22371 /* Macros to extract header fields from data already in registers */
22372 #ifdef	_BIG_ENDIAN
22373 #define	V_HLEN	(v_hlen_tos_len >> 24)
22374 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22375 #define	PROTO	(ttl_protocol & 0xFF)
22376 #else
22377 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22378 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22379 #define	PROTO	(ttl_protocol >> 8)
22380 #endif
22381 
22382 	orig_src = src = ipha->ipha_src;
22383 	/* (The loop back to "another" is explained down below.) */
22384 another:;
22385 	/*
22386 	 * Assign an ident value for this packet.  We assign idents on
22387 	 * a per destination basis out of the IRE.  There could be
22388 	 * other threads targeting the same destination, so we have to
22389 	 * arrange for a atomic increment.  Note that we use a 32-bit
22390 	 * atomic add because it has better performance than its
22391 	 * 16-bit sibling.
22392 	 *
22393 	 * If running in cluster mode and if the source address
22394 	 * belongs to a replicated service then vector through
22395 	 * cl_inet_ipident vector to allocate ip identifier
22396 	 * NOTE: This is a contract private interface with the
22397 	 * clustering group.
22398 	 */
22399 	clusterwide = 0;
22400 	if (cl_inet_ipident) {
22401 		ASSERT(cl_inet_isclusterwide);
22402 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22403 
22404 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22405 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22406 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22407 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22408 			    (uint8_t *)(uintptr_t)dst, NULL);
22409 			clusterwide = 1;
22410 		}
22411 	}
22412 	if (!clusterwide) {
22413 		ipha->ipha_ident =
22414 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22415 	}
22416 
22417 #ifndef _BIG_ENDIAN
22418 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22419 #endif
22420 
22421 	/*
22422 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22423 	 * This is needed to obey conn_unspec_src when packets go through
22424 	 * ip_newroute + arp.
22425 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22426 	 */
22427 	if (src == INADDR_ANY && !unspec_src) {
22428 		/*
22429 		 * Assign the appropriate source address from the IRE if none
22430 		 * was specified.
22431 		 */
22432 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22433 
22434 		src = ire->ire_src_addr;
22435 		if (connp == NULL) {
22436 			ip1dbg(("ip_wput_ire: no connp and no src "
22437 			    "address for dst 0x%x, using src 0x%x\n",
22438 			    ntohl(dst),
22439 			    ntohl(src)));
22440 		}
22441 		ipha->ipha_src = src;
22442 	}
22443 	stq = ire->ire_stq;
22444 
22445 	/*
22446 	 * We only allow ire chains for broadcasts since there will
22447 	 * be multiple IRE_CACHE entries for the same multicast
22448 	 * address (one per ipif).
22449 	 */
22450 	next_mp = NULL;
22451 
22452 	/* broadcast packet */
22453 	if (ire->ire_type == IRE_BROADCAST)
22454 		goto broadcast;
22455 
22456 	/* loopback ? */
22457 	if (stq == NULL)
22458 		goto nullstq;
22459 
22460 	/* The ill_index for outbound ILL */
22461 	ill_index = Q_TO_INDEX(stq);
22462 
22463 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22464 	ttl_protocol = ((uint16_t *)ipha)[4];
22465 
22466 	/* pseudo checksum (do it in parts for IP header checksum) */
22467 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22468 
22469 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22470 		queue_t *dev_q = stq->q_next;
22471 
22472 		/*
22473 		 * For DIRECT_CAPABLE, we do flow control at
22474 		 * the time of sending the packet. See
22475 		 * ILL_SEND_TX().
22476 		 */
22477 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22478 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22479 			goto blocked;
22480 
22481 		if ((PROTO == IPPROTO_UDP) &&
22482 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22483 			hlen = (V_HLEN & 0xF) << 2;
22484 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22485 			if (*up != 0) {
22486 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22487 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22488 				/* Software checksum? */
22489 				if (DB_CKSUMFLAGS(mp) == 0) {
22490 					IP_STAT(ipst, ip_out_sw_cksum);
22491 					IP_STAT_UPDATE(ipst,
22492 					    ip_udp_out_sw_cksum_bytes,
22493 					    LENGTH - hlen);
22494 				}
22495 			}
22496 		}
22497 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22498 		hlen = (V_HLEN & 0xF) << 2;
22499 		if (PROTO == IPPROTO_TCP) {
22500 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22501 			/*
22502 			 * The packet header is processed once and for all, even
22503 			 * in the multirouting case. We disable hardware
22504 			 * checksum if the packet is multirouted, as it will be
22505 			 * replicated via several interfaces, and not all of
22506 			 * them may have this capability.
22507 			 */
22508 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22509 			    LENGTH, max_frag, ipsec_len, cksum);
22510 			/* Software checksum? */
22511 			if (DB_CKSUMFLAGS(mp) == 0) {
22512 				IP_STAT(ipst, ip_out_sw_cksum);
22513 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22514 				    LENGTH - hlen);
22515 			}
22516 		} else {
22517 			sctp_hdr_t	*sctph;
22518 
22519 			ASSERT(PROTO == IPPROTO_SCTP);
22520 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22521 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22522 			/*
22523 			 * Zero out the checksum field to ensure proper
22524 			 * checksum calculation.
22525 			 */
22526 			sctph->sh_chksum = 0;
22527 #ifdef	DEBUG
22528 			if (!skip_sctp_cksum)
22529 #endif
22530 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22531 		}
22532 	}
22533 
22534 	/*
22535 	 * If this is a multicast packet and originated from ip_wput
22536 	 * we need to do loopback and forwarding checks. If it comes
22537 	 * from ip_wput_multicast, we SHOULD not do this.
22538 	 */
22539 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22540 
22541 	/* checksum */
22542 	cksum += ttl_protocol;
22543 
22544 	/* fragment the packet */
22545 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22546 		goto fragmentit;
22547 	/*
22548 	 * Don't use frag_flag if packet is pre-built or source
22549 	 * routed or if multicast (since multicast packets do
22550 	 * not solicit ICMP "packet too big" messages).
22551 	 */
22552 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22553 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22554 	    !ip_source_route_included(ipha)) &&
22555 	    !CLASSD(ipha->ipha_dst))
22556 		ipha->ipha_fragment_offset_and_flags |=
22557 		    htons(ire->ire_frag_flag);
22558 
22559 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22560 		/* calculate IP header checksum */
22561 		cksum += ipha->ipha_ident;
22562 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22563 		cksum += ipha->ipha_fragment_offset_and_flags;
22564 
22565 		/* IP options present */
22566 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22567 		if (hlen)
22568 			goto checksumoptions;
22569 
22570 		/* calculate hdr checksum */
22571 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22572 		cksum = ~(cksum + (cksum >> 16));
22573 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22574 	}
22575 	if (ipsec_len != 0) {
22576 		/*
22577 		 * We will do the rest of the processing after
22578 		 * we come back from IPsec in ip_wput_ipsec_out().
22579 		 */
22580 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22581 
22582 		io = (ipsec_out_t *)first_mp->b_rptr;
22583 		io->ipsec_out_ill_index =
22584 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22585 		ipsec_out_process(q, first_mp, ire, 0);
22586 		ire_refrele(ire);
22587 		if (conn_outgoing_ill != NULL)
22588 			ill_refrele(conn_outgoing_ill);
22589 		return;
22590 	}
22591 
22592 	/*
22593 	 * In most cases, the emission loop below is entered only
22594 	 * once. Only in the case where the ire holds the
22595 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22596 	 * flagged ires in the bucket, and send the packet
22597 	 * through all crossed RTF_MULTIRT routes.
22598 	 */
22599 	if (ire->ire_flags & RTF_MULTIRT) {
22600 		multirt_send = B_TRUE;
22601 	}
22602 	do {
22603 		if (multirt_send) {
22604 			irb_t *irb;
22605 			/*
22606 			 * We are in a multiple send case, need to get
22607 			 * the next ire and make a duplicate of the packet.
22608 			 * ire1 holds here the next ire to process in the
22609 			 * bucket. If multirouting is expected,
22610 			 * any non-RTF_MULTIRT ire that has the
22611 			 * right destination address is ignored.
22612 			 */
22613 			irb = ire->ire_bucket;
22614 			ASSERT(irb != NULL);
22615 
22616 			IRB_REFHOLD(irb);
22617 			for (ire1 = ire->ire_next;
22618 			    ire1 != NULL;
22619 			    ire1 = ire1->ire_next) {
22620 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22621 					continue;
22622 				if (ire1->ire_addr != ire->ire_addr)
22623 					continue;
22624 				if (ire1->ire_marks &
22625 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22626 					continue;
22627 
22628 				/* Got one */
22629 				IRE_REFHOLD(ire1);
22630 				break;
22631 			}
22632 			IRB_REFRELE(irb);
22633 
22634 			if (ire1 != NULL) {
22635 				next_mp = copyb(mp);
22636 				if ((next_mp == NULL) ||
22637 				    ((mp->b_cont != NULL) &&
22638 				    ((next_mp->b_cont =
22639 				    dupmsg(mp->b_cont)) == NULL))) {
22640 					freemsg(next_mp);
22641 					next_mp = NULL;
22642 					ire_refrele(ire1);
22643 					ire1 = NULL;
22644 				}
22645 			}
22646 
22647 			/* Last multiroute ire; don't loop anymore. */
22648 			if (ire1 == NULL) {
22649 				multirt_send = B_FALSE;
22650 			}
22651 		}
22652 
22653 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22654 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22655 		    mblk_t *, mp);
22656 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22657 		    ipst->ips_ipv4firewall_physical_out,
22658 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22659 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22660 
22661 		if (mp == NULL)
22662 			goto release_ire_and_ill;
22663 
22664 		if (ipst->ips_ipobs_enabled) {
22665 			zoneid_t szone;
22666 
22667 			/*
22668 			 * On the outbound path the destination zone will be
22669 			 * unknown as we're sending this packet out on the
22670 			 * wire.
22671 			 */
22672 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22673 			    ALL_ZONES);
22674 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22675 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22676 		}
22677 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22678 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22679 
22680 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22681 
22682 		if ((pktxmit_state == SEND_FAILED) ||
22683 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22684 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22685 			    "- packet dropped\n"));
22686 release_ire_and_ill:
22687 			ire_refrele(ire);
22688 			if (next_mp != NULL) {
22689 				freemsg(next_mp);
22690 				ire_refrele(ire1);
22691 			}
22692 			if (conn_outgoing_ill != NULL)
22693 				ill_refrele(conn_outgoing_ill);
22694 			return;
22695 		}
22696 
22697 		if (CLASSD(dst)) {
22698 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22699 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22700 			    LENGTH);
22701 		}
22702 
22703 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22704 		    "ip_wput_ire_end: q %p (%S)",
22705 		    q, "last copy out");
22706 		IRE_REFRELE(ire);
22707 
22708 		if (multirt_send) {
22709 			ASSERT(ire1);
22710 			/*
22711 			 * Proceed with the next RTF_MULTIRT ire,
22712 			 * Also set up the send-to queue accordingly.
22713 			 */
22714 			ire = ire1;
22715 			ire1 = NULL;
22716 			stq = ire->ire_stq;
22717 			mp = next_mp;
22718 			next_mp = NULL;
22719 			ipha = (ipha_t *)mp->b_rptr;
22720 			ill_index = Q_TO_INDEX(stq);
22721 			ill = (ill_t *)stq->q_ptr;
22722 		}
22723 	} while (multirt_send);
22724 	if (conn_outgoing_ill != NULL)
22725 		ill_refrele(conn_outgoing_ill);
22726 	return;
22727 
22728 	/*
22729 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22730 	 */
22731 broadcast:
22732 	{
22733 		/*
22734 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22735 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22736 		 * can be overridden stack-wide through the ip_broadcast_ttl
22737 		 * ndd tunable, or on a per-connection basis through the
22738 		 * IP_BROADCAST_TTL socket option.
22739 		 *
22740 		 * In the event that we are replying to incoming ICMP packets,
22741 		 * connp could be NULL.
22742 		 */
22743 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22744 		if (connp != NULL) {
22745 			if (connp->conn_dontroute)
22746 				ipha->ipha_ttl = 1;
22747 			else if (connp->conn_broadcast_ttl != 0)
22748 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22749 		}
22750 
22751 		/*
22752 		 * Note that we are not doing a IRB_REFHOLD here.
22753 		 * Actually we don't care if the list changes i.e
22754 		 * if somebody deletes an IRE from the list while
22755 		 * we drop the lock, the next time we come around
22756 		 * ire_next will be NULL and hence we won't send
22757 		 * out multiple copies which is fine.
22758 		 */
22759 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22760 		ire1 = ire->ire_next;
22761 		if (conn_outgoing_ill != NULL) {
22762 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22763 				ASSERT(ire1 == ire->ire_next);
22764 				if (ire1 != NULL && ire1->ire_addr == dst) {
22765 					ire_refrele(ire);
22766 					ire = ire1;
22767 					IRE_REFHOLD(ire);
22768 					ire1 = ire->ire_next;
22769 					continue;
22770 				}
22771 				rw_exit(&ire->ire_bucket->irb_lock);
22772 				/* Did not find a matching ill */
22773 				ip1dbg(("ip_wput_ire: broadcast with no "
22774 				    "matching IP_BOUND_IF ill %s dst %x\n",
22775 				    conn_outgoing_ill->ill_name, dst));
22776 				freemsg(first_mp);
22777 				if (ire != NULL)
22778 					ire_refrele(ire);
22779 				ill_refrele(conn_outgoing_ill);
22780 				return;
22781 			}
22782 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22783 			/*
22784 			 * If the next IRE has the same address and is not one
22785 			 * of the two copies that we need to send, try to see
22786 			 * whether this copy should be sent at all. This
22787 			 * assumes that we insert loopbacks first and then
22788 			 * non-loopbacks. This is acheived by inserting the
22789 			 * loopback always before non-loopback.
22790 			 * This is used to send a single copy of a broadcast
22791 			 * packet out all physical interfaces that have an
22792 			 * matching IRE_BROADCAST while also looping
22793 			 * back one copy (to ip_wput_local) for each
22794 			 * matching physical interface. However, we avoid
22795 			 * sending packets out different logical that match by
22796 			 * having ipif_up/ipif_down supress duplicate
22797 			 * IRE_BROADCASTS.
22798 			 *
22799 			 * This feature is currently used to get broadcasts
22800 			 * sent to multiple interfaces, when the broadcast
22801 			 * address being used applies to multiple interfaces.
22802 			 * For example, a whole net broadcast will be
22803 			 * replicated on every connected subnet of
22804 			 * the target net.
22805 			 *
22806 			 * Each zone has its own set of IRE_BROADCASTs, so that
22807 			 * we're able to distribute inbound packets to multiple
22808 			 * zones who share a broadcast address. We avoid looping
22809 			 * back outbound packets in different zones but on the
22810 			 * same ill, as the application would see duplicates.
22811 			 *
22812 			 * This logic assumes that ire_add_v4() groups the
22813 			 * IRE_BROADCAST entries so that those with the same
22814 			 * ire_addr are kept together.
22815 			 */
22816 			ire_ill = ire->ire_ipif->ipif_ill;
22817 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22818 				while (ire1 != NULL && ire1->ire_addr == dst) {
22819 					ire1_ill = ire1->ire_ipif->ipif_ill;
22820 					if (ire1_ill != ire_ill)
22821 						break;
22822 					ire1 = ire1->ire_next;
22823 				}
22824 			}
22825 		}
22826 		ASSERT(multirt_send == B_FALSE);
22827 		if (ire1 != NULL && ire1->ire_addr == dst) {
22828 			if ((ire->ire_flags & RTF_MULTIRT) &&
22829 			    (ire1->ire_flags & RTF_MULTIRT)) {
22830 				/*
22831 				 * We are in the multirouting case.
22832 				 * The message must be sent at least
22833 				 * on both ires. These ires have been
22834 				 * inserted AFTER the standard ones
22835 				 * in ip_rt_add(). There are thus no
22836 				 * other ire entries for the destination
22837 				 * address in the rest of the bucket
22838 				 * that do not have the RTF_MULTIRT
22839 				 * flag. We don't process a copy
22840 				 * of the message here. This will be
22841 				 * done in the final sending loop.
22842 				 */
22843 				multirt_send = B_TRUE;
22844 			} else {
22845 				next_mp = ip_copymsg(first_mp);
22846 				if (next_mp != NULL)
22847 					IRE_REFHOLD(ire1);
22848 			}
22849 		}
22850 		rw_exit(&ire->ire_bucket->irb_lock);
22851 	}
22852 
22853 	if (stq) {
22854 		/*
22855 		 * A non-NULL send-to queue means this packet is going
22856 		 * out of this machine.
22857 		 */
22858 		out_ill = (ill_t *)stq->q_ptr;
22859 
22860 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22861 		ttl_protocol = ((uint16_t *)ipha)[4];
22862 		/*
22863 		 * We accumulate the pseudo header checksum in cksum.
22864 		 * This is pretty hairy code, so watch close.  One
22865 		 * thing to keep in mind is that UDP and TCP have
22866 		 * stored their respective datagram lengths in their
22867 		 * checksum fields.  This lines things up real nice.
22868 		 */
22869 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22870 		    (src >> 16) + (src & 0xFFFF);
22871 		/*
22872 		 * We assume the udp checksum field contains the
22873 		 * length, so to compute the pseudo header checksum,
22874 		 * all we need is the protocol number and src/dst.
22875 		 */
22876 		/* Provide the checksums for UDP and TCP. */
22877 		if ((PROTO == IPPROTO_TCP) &&
22878 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22879 			/* hlen gets the number of uchar_ts in the IP header */
22880 			hlen = (V_HLEN & 0xF) << 2;
22881 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22882 			IP_STAT(ipst, ip_out_sw_cksum);
22883 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22884 			    LENGTH - hlen);
22885 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22886 		} else if (PROTO == IPPROTO_SCTP &&
22887 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22888 			sctp_hdr_t	*sctph;
22889 
22890 			hlen = (V_HLEN & 0xF) << 2;
22891 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22892 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22893 			sctph->sh_chksum = 0;
22894 #ifdef	DEBUG
22895 			if (!skip_sctp_cksum)
22896 #endif
22897 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22898 		} else {
22899 			queue_t	*dev_q = stq->q_next;
22900 
22901 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22902 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22903 blocked:
22904 				ipha->ipha_ident = ip_hdr_included;
22905 				/*
22906 				 * If we don't have a conn to apply
22907 				 * backpressure, free the message.
22908 				 * In the ire_send path, we don't know
22909 				 * the position to requeue the packet. Rather
22910 				 * than reorder packets, we just drop this
22911 				 * packet.
22912 				 */
22913 				if (ipst->ips_ip_output_queue &&
22914 				    connp != NULL &&
22915 				    caller != IRE_SEND) {
22916 					if (caller == IP_WSRV) {
22917 						idl_tx_list_t *idl_txl;
22918 
22919 						idl_txl =
22920 						    &ipst->ips_idl_tx_list[0];
22921 						connp->conn_did_putbq = 1;
22922 						(void) putbq(connp->conn_wq,
22923 						    first_mp);
22924 						conn_drain_insert(connp,
22925 						    idl_txl);
22926 						/*
22927 						 * This is the service thread,
22928 						 * and the queue is already
22929 						 * noenabled. The check for
22930 						 * canput and the putbq is not
22931 						 * atomic. So we need to check
22932 						 * again.
22933 						 */
22934 						if (canput(stq->q_next))
22935 							connp->conn_did_putbq
22936 							    = 0;
22937 						IP_STAT(ipst, ip_conn_flputbq);
22938 					} else {
22939 						/*
22940 						 * We are not the service proc.
22941 						 * ip_wsrv will be scheduled or
22942 						 * is already running.
22943 						 */
22944 
22945 						(void) putq(connp->conn_wq,
22946 						    first_mp);
22947 					}
22948 				} else {
22949 					out_ill = (ill_t *)stq->q_ptr;
22950 					BUMP_MIB(out_ill->ill_ip_mib,
22951 					    ipIfStatsOutDiscards);
22952 					freemsg(first_mp);
22953 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22954 					    "ip_wput_ire_end: q %p (%S)",
22955 					    q, "discard");
22956 				}
22957 				ire_refrele(ire);
22958 				if (next_mp) {
22959 					ire_refrele(ire1);
22960 					freemsg(next_mp);
22961 				}
22962 				if (conn_outgoing_ill != NULL)
22963 					ill_refrele(conn_outgoing_ill);
22964 				return;
22965 			}
22966 			if ((PROTO == IPPROTO_UDP) &&
22967 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22968 				/*
22969 				 * hlen gets the number of uchar_ts in the
22970 				 * IP header
22971 				 */
22972 				hlen = (V_HLEN & 0xF) << 2;
22973 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22974 				max_frag = ire->ire_max_frag;
22975 				if (*up != 0) {
22976 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22977 					    up, PROTO, hlen, LENGTH, max_frag,
22978 					    ipsec_len, cksum);
22979 					/* Software checksum? */
22980 					if (DB_CKSUMFLAGS(mp) == 0) {
22981 						IP_STAT(ipst, ip_out_sw_cksum);
22982 						IP_STAT_UPDATE(ipst,
22983 						    ip_udp_out_sw_cksum_bytes,
22984 						    LENGTH - hlen);
22985 					}
22986 				}
22987 			}
22988 		}
22989 		/*
22990 		 * Need to do this even when fragmenting. The local
22991 		 * loopback can be done without computing checksums
22992 		 * but forwarding out other interface must be done
22993 		 * after the IP checksum (and ULP checksums) have been
22994 		 * computed.
22995 		 *
22996 		 * NOTE : multicast_forward is set only if this packet
22997 		 * originated from ip_wput. For packets originating from
22998 		 * ip_wput_multicast, it is not set.
22999 		 */
23000 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23001 multi_loopback:
23002 			ip2dbg(("ip_wput: multicast, loop %d\n",
23003 			    conn_multicast_loop));
23004 
23005 			/*  Forget header checksum offload */
23006 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23007 
23008 			/*
23009 			 * Local loopback of multicasts?  Check the
23010 			 * ill.
23011 			 *
23012 			 * Note that the loopback function will not come
23013 			 * in through ip_rput - it will only do the
23014 			 * client fanout thus we need to do an mforward
23015 			 * as well.  The is different from the BSD
23016 			 * logic.
23017 			 */
23018 			if (ill != NULL) {
23019 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23020 				    ALL_ZONES) != NULL) {
23021 					/*
23022 					 * Pass along the virtual output q.
23023 					 * ip_wput_local() will distribute the
23024 					 * packet to all the matching zones,
23025 					 * except the sending zone when
23026 					 * IP_MULTICAST_LOOP is false.
23027 					 */
23028 					ip_multicast_loopback(q, ill, first_mp,
23029 					    conn_multicast_loop ? 0 :
23030 					    IP_FF_NO_MCAST_LOOP, zoneid);
23031 				}
23032 			}
23033 			if (ipha->ipha_ttl == 0) {
23034 				/*
23035 				 * 0 => only to this host i.e. we are
23036 				 * done. We are also done if this was the
23037 				 * loopback interface since it is sufficient
23038 				 * to loopback one copy of a multicast packet.
23039 				 */
23040 				freemsg(first_mp);
23041 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23042 				    "ip_wput_ire_end: q %p (%S)",
23043 				    q, "loopback");
23044 				ire_refrele(ire);
23045 				if (conn_outgoing_ill != NULL)
23046 					ill_refrele(conn_outgoing_ill);
23047 				return;
23048 			}
23049 			/*
23050 			 * ILLF_MULTICAST is checked in ip_newroute
23051 			 * i.e. we don't need to check it here since
23052 			 * all IRE_CACHEs come from ip_newroute.
23053 			 * For multicast traffic, SO_DONTROUTE is interpreted
23054 			 * to mean only send the packet out the interface
23055 			 * (optionally specified with IP_MULTICAST_IF)
23056 			 * and do not forward it out additional interfaces.
23057 			 * RSVP and the rsvp daemon is an example of a
23058 			 * protocol and user level process that
23059 			 * handles it's own routing. Hence, it uses the
23060 			 * SO_DONTROUTE option to accomplish this.
23061 			 */
23062 
23063 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23064 			    ill != NULL) {
23065 				/* Unconditionally redo the checksum */
23066 				ipha->ipha_hdr_checksum = 0;
23067 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23068 
23069 				/*
23070 				 * If this needs to go out secure, we need
23071 				 * to wait till we finish the IPsec
23072 				 * processing.
23073 				 */
23074 				if (ipsec_len == 0 &&
23075 				    ip_mforward(ill, ipha, mp)) {
23076 					freemsg(first_mp);
23077 					ip1dbg(("ip_wput: mforward failed\n"));
23078 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23079 					    "ip_wput_ire_end: q %p (%S)",
23080 					    q, "mforward failed");
23081 					ire_refrele(ire);
23082 					if (conn_outgoing_ill != NULL)
23083 						ill_refrele(conn_outgoing_ill);
23084 					return;
23085 				}
23086 			}
23087 		}
23088 		max_frag = ire->ire_max_frag;
23089 		cksum += ttl_protocol;
23090 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23091 			/* No fragmentation required for this one. */
23092 			/*
23093 			 * Don't use frag_flag if packet is pre-built or source
23094 			 * routed or if multicast (since multicast packets do
23095 			 * not solicit ICMP "packet too big" messages).
23096 			 */
23097 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23098 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23099 			    !ip_source_route_included(ipha)) &&
23100 			    !CLASSD(ipha->ipha_dst))
23101 				ipha->ipha_fragment_offset_and_flags |=
23102 				    htons(ire->ire_frag_flag);
23103 
23104 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23105 				/* Complete the IP header checksum. */
23106 				cksum += ipha->ipha_ident;
23107 				cksum += (v_hlen_tos_len >> 16)+
23108 				    (v_hlen_tos_len & 0xFFFF);
23109 				cksum += ipha->ipha_fragment_offset_and_flags;
23110 				hlen = (V_HLEN & 0xF) -
23111 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23112 				if (hlen) {
23113 checksumoptions:
23114 					/*
23115 					 * Account for the IP Options in the IP
23116 					 * header checksum.
23117 					 */
23118 					up = (uint16_t *)(rptr+
23119 					    IP_SIMPLE_HDR_LENGTH);
23120 					do {
23121 						cksum += up[0];
23122 						cksum += up[1];
23123 						up += 2;
23124 					} while (--hlen);
23125 				}
23126 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23127 				cksum = ~(cksum + (cksum >> 16));
23128 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23129 			}
23130 			if (ipsec_len != 0) {
23131 				ipsec_out_process(q, first_mp, ire, ill_index);
23132 				if (!next_mp) {
23133 					ire_refrele(ire);
23134 					if (conn_outgoing_ill != NULL)
23135 						ill_refrele(conn_outgoing_ill);
23136 					return;
23137 				}
23138 				goto next;
23139 			}
23140 
23141 			/*
23142 			 * multirt_send has already been handled
23143 			 * for broadcast, but not yet for multicast
23144 			 * or IP options.
23145 			 */
23146 			if (next_mp == NULL) {
23147 				if (ire->ire_flags & RTF_MULTIRT) {
23148 					multirt_send = B_TRUE;
23149 				}
23150 			}
23151 
23152 			/*
23153 			 * In most cases, the emission loop below is
23154 			 * entered only once. Only in the case where
23155 			 * the ire holds the RTF_MULTIRT flag, do we loop
23156 			 * to process all RTF_MULTIRT ires in the bucket,
23157 			 * and send the packet through all crossed
23158 			 * RTF_MULTIRT routes.
23159 			 */
23160 			do {
23161 				if (multirt_send) {
23162 					irb_t *irb;
23163 
23164 					irb = ire->ire_bucket;
23165 					ASSERT(irb != NULL);
23166 					/*
23167 					 * We are in a multiple send case,
23168 					 * need to get the next IRE and make
23169 					 * a duplicate of the packet.
23170 					 */
23171 					IRB_REFHOLD(irb);
23172 					for (ire1 = ire->ire_next;
23173 					    ire1 != NULL;
23174 					    ire1 = ire1->ire_next) {
23175 						if (!(ire1->ire_flags &
23176 						    RTF_MULTIRT))
23177 							continue;
23178 
23179 						if (ire1->ire_addr !=
23180 						    ire->ire_addr)
23181 							continue;
23182 
23183 						if (ire1->ire_marks &
23184 						    (IRE_MARK_CONDEMNED |
23185 						    IRE_MARK_TESTHIDDEN))
23186 							continue;
23187 
23188 						/* Got one */
23189 						IRE_REFHOLD(ire1);
23190 						break;
23191 					}
23192 					IRB_REFRELE(irb);
23193 
23194 					if (ire1 != NULL) {
23195 						next_mp = copyb(mp);
23196 						if ((next_mp == NULL) ||
23197 						    ((mp->b_cont != NULL) &&
23198 						    ((next_mp->b_cont =
23199 						    dupmsg(mp->b_cont))
23200 						    == NULL))) {
23201 							freemsg(next_mp);
23202 							next_mp = NULL;
23203 							ire_refrele(ire1);
23204 							ire1 = NULL;
23205 						}
23206 					}
23207 
23208 					/*
23209 					 * Last multiroute ire; don't loop
23210 					 * anymore. The emission is over
23211 					 * and next_mp is NULL.
23212 					 */
23213 					if (ire1 == NULL) {
23214 						multirt_send = B_FALSE;
23215 					}
23216 				}
23217 
23218 				out_ill = ire_to_ill(ire);
23219 				DTRACE_PROBE4(ip4__physical__out__start,
23220 				    ill_t *, NULL,
23221 				    ill_t *, out_ill,
23222 				    ipha_t *, ipha, mblk_t *, mp);
23223 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23224 				    ipst->ips_ipv4firewall_physical_out,
23225 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23226 				DTRACE_PROBE1(ip4__physical__out__end,
23227 				    mblk_t *, mp);
23228 				if (mp == NULL)
23229 					goto release_ire_and_ill_2;
23230 
23231 				ASSERT(ipsec_len == 0);
23232 				mp->b_prev =
23233 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23234 				DTRACE_PROBE2(ip__xmit__2,
23235 				    mblk_t *, mp, ire_t *, ire);
23236 				pktxmit_state = ip_xmit_v4(mp, ire,
23237 				    NULL, B_TRUE, connp);
23238 				if ((pktxmit_state == SEND_FAILED) ||
23239 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23240 release_ire_and_ill_2:
23241 					if (next_mp) {
23242 						freemsg(next_mp);
23243 						ire_refrele(ire1);
23244 					}
23245 					ire_refrele(ire);
23246 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23247 					    "ip_wput_ire_end: q %p (%S)",
23248 					    q, "discard MDATA");
23249 					if (conn_outgoing_ill != NULL)
23250 						ill_refrele(conn_outgoing_ill);
23251 					return;
23252 				}
23253 
23254 				if (CLASSD(dst)) {
23255 					BUMP_MIB(out_ill->ill_ip_mib,
23256 					    ipIfStatsHCOutMcastPkts);
23257 					UPDATE_MIB(out_ill->ill_ip_mib,
23258 					    ipIfStatsHCOutMcastOctets,
23259 					    LENGTH);
23260 				} else if (ire->ire_type == IRE_BROADCAST) {
23261 					BUMP_MIB(out_ill->ill_ip_mib,
23262 					    ipIfStatsHCOutBcastPkts);
23263 				}
23264 
23265 				if (multirt_send) {
23266 					/*
23267 					 * We are in a multiple send case,
23268 					 * need to re-enter the sending loop
23269 					 * using the next ire.
23270 					 */
23271 					ire_refrele(ire);
23272 					ire = ire1;
23273 					stq = ire->ire_stq;
23274 					mp = next_mp;
23275 					next_mp = NULL;
23276 					ipha = (ipha_t *)mp->b_rptr;
23277 					ill_index = Q_TO_INDEX(stq);
23278 				}
23279 			} while (multirt_send);
23280 
23281 			if (!next_mp) {
23282 				/*
23283 				 * Last copy going out (the ultra-common
23284 				 * case).  Note that we intentionally replicate
23285 				 * the putnext rather than calling it before
23286 				 * the next_mp check in hopes of a little
23287 				 * tail-call action out of the compiler.
23288 				 */
23289 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23290 				    "ip_wput_ire_end: q %p (%S)",
23291 				    q, "last copy out(1)");
23292 				ire_refrele(ire);
23293 				if (conn_outgoing_ill != NULL)
23294 					ill_refrele(conn_outgoing_ill);
23295 				return;
23296 			}
23297 			/* More copies going out below. */
23298 		} else {
23299 			int offset;
23300 fragmentit:
23301 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23302 			/*
23303 			 * If this would generate a icmp_frag_needed message,
23304 			 * we need to handle it before we do the IPsec
23305 			 * processing. Otherwise, we need to strip the IPsec
23306 			 * headers before we send up the message to the ULPs
23307 			 * which becomes messy and difficult.
23308 			 */
23309 			if (ipsec_len != 0) {
23310 				if ((max_frag < (unsigned int)(LENGTH +
23311 				    ipsec_len)) && (offset & IPH_DF)) {
23312 					out_ill = (ill_t *)stq->q_ptr;
23313 					BUMP_MIB(out_ill->ill_ip_mib,
23314 					    ipIfStatsOutFragFails);
23315 					BUMP_MIB(out_ill->ill_ip_mib,
23316 					    ipIfStatsOutFragReqds);
23317 					ipha->ipha_hdr_checksum = 0;
23318 					ipha->ipha_hdr_checksum =
23319 					    (uint16_t)ip_csum_hdr(ipha);
23320 					icmp_frag_needed(ire->ire_stq, first_mp,
23321 					    max_frag, zoneid, ipst);
23322 					if (!next_mp) {
23323 						ire_refrele(ire);
23324 						if (conn_outgoing_ill != NULL) {
23325 							ill_refrele(
23326 							    conn_outgoing_ill);
23327 						}
23328 						return;
23329 					}
23330 				} else {
23331 					/*
23332 					 * This won't cause a icmp_frag_needed
23333 					 * message. to be generated. Send it on
23334 					 * the wire. Note that this could still
23335 					 * cause fragmentation and all we
23336 					 * do is the generation of the message
23337 					 * to the ULP if needed before IPsec.
23338 					 */
23339 					if (!next_mp) {
23340 						ipsec_out_process(q, first_mp,
23341 						    ire, ill_index);
23342 						TRACE_2(TR_FAC_IP,
23343 						    TR_IP_WPUT_IRE_END,
23344 						    "ip_wput_ire_end: q %p "
23345 						    "(%S)", q,
23346 						    "last ipsec_out_process");
23347 						ire_refrele(ire);
23348 						if (conn_outgoing_ill != NULL) {
23349 							ill_refrele(
23350 							    conn_outgoing_ill);
23351 						}
23352 						return;
23353 					}
23354 					ipsec_out_process(q, first_mp,
23355 					    ire, ill_index);
23356 				}
23357 			} else {
23358 				/*
23359 				 * Initiate IPPF processing. For
23360 				 * fragmentable packets we finish
23361 				 * all QOS packet processing before
23362 				 * calling:
23363 				 * ip_wput_ire_fragmentit->ip_wput_frag
23364 				 */
23365 
23366 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23367 					ip_process(IPP_LOCAL_OUT, &mp,
23368 					    ill_index);
23369 					if (mp == NULL) {
23370 						out_ill = (ill_t *)stq->q_ptr;
23371 						BUMP_MIB(out_ill->ill_ip_mib,
23372 						    ipIfStatsOutDiscards);
23373 						if (next_mp != NULL) {
23374 							freemsg(next_mp);
23375 							ire_refrele(ire1);
23376 						}
23377 						ire_refrele(ire);
23378 						TRACE_2(TR_FAC_IP,
23379 						    TR_IP_WPUT_IRE_END,
23380 						    "ip_wput_ire: q %p (%S)",
23381 						    q, "discard MDATA");
23382 						if (conn_outgoing_ill != NULL) {
23383 							ill_refrele(
23384 							    conn_outgoing_ill);
23385 						}
23386 						return;
23387 					}
23388 				}
23389 				if (!next_mp) {
23390 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23391 					    "ip_wput_ire_end: q %p (%S)",
23392 					    q, "last fragmentation");
23393 					ip_wput_ire_fragmentit(mp, ire,
23394 					    zoneid, ipst, connp);
23395 					ire_refrele(ire);
23396 					if (conn_outgoing_ill != NULL)
23397 						ill_refrele(conn_outgoing_ill);
23398 					return;
23399 				}
23400 				ip_wput_ire_fragmentit(mp, ire,
23401 				    zoneid, ipst, connp);
23402 			}
23403 		}
23404 	} else {
23405 nullstq:
23406 		/* A NULL stq means the destination address is local. */
23407 		UPDATE_OB_PKT_COUNT(ire);
23408 		ire->ire_last_used_time = lbolt;
23409 		ASSERT(ire->ire_ipif != NULL);
23410 		if (!next_mp) {
23411 			/*
23412 			 * Is there an "in" and "out" for traffic local
23413 			 * to a host (loopback)?  The code in Solaris doesn't
23414 			 * explicitly draw a line in its code for in vs out,
23415 			 * so we've had to draw a line in the sand: ip_wput_ire
23416 			 * is considered to be the "output" side and
23417 			 * ip_wput_local to be the "input" side.
23418 			 */
23419 			out_ill = ire_to_ill(ire);
23420 
23421 			/*
23422 			 * DTrace this as ip:::send.  A blocked packet will
23423 			 * fire the send probe, but not the receive probe.
23424 			 */
23425 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23426 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23427 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23428 
23429 			DTRACE_PROBE4(ip4__loopback__out__start,
23430 			    ill_t *, NULL, ill_t *, out_ill,
23431 			    ipha_t *, ipha, mblk_t *, first_mp);
23432 
23433 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23434 			    ipst->ips_ipv4firewall_loopback_out,
23435 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23436 
23437 			DTRACE_PROBE1(ip4__loopback__out_end,
23438 			    mblk_t *, first_mp);
23439 
23440 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23441 			    "ip_wput_ire_end: q %p (%S)",
23442 			    q, "local address");
23443 
23444 			if (first_mp != NULL)
23445 				ip_wput_local(q, out_ill, ipha,
23446 				    first_mp, ire, 0, ire->ire_zoneid);
23447 			ire_refrele(ire);
23448 			if (conn_outgoing_ill != NULL)
23449 				ill_refrele(conn_outgoing_ill);
23450 			return;
23451 		}
23452 
23453 		out_ill = ire_to_ill(ire);
23454 
23455 		/*
23456 		 * DTrace this as ip:::send.  A blocked packet will fire the
23457 		 * send probe, but not the receive probe.
23458 		 */
23459 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23460 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23461 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23462 
23463 		DTRACE_PROBE4(ip4__loopback__out__start,
23464 		    ill_t *, NULL, ill_t *, out_ill,
23465 		    ipha_t *, ipha, mblk_t *, first_mp);
23466 
23467 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23468 		    ipst->ips_ipv4firewall_loopback_out,
23469 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23470 
23471 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23472 
23473 		if (first_mp != NULL)
23474 			ip_wput_local(q, out_ill, ipha,
23475 			    first_mp, ire, 0, ire->ire_zoneid);
23476 	}
23477 next:
23478 	/*
23479 	 * More copies going out to additional interfaces.
23480 	 * ire1 has already been held. We don't need the
23481 	 * "ire" anymore.
23482 	 */
23483 	ire_refrele(ire);
23484 	ire = ire1;
23485 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23486 	mp = next_mp;
23487 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23488 	ill = ire_to_ill(ire);
23489 	first_mp = mp;
23490 	if (ipsec_len != 0) {
23491 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23492 		mp = mp->b_cont;
23493 	}
23494 	dst = ire->ire_addr;
23495 	ipha = (ipha_t *)mp->b_rptr;
23496 	/*
23497 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23498 	 * Restore ipha_ident "no checksum" flag.
23499 	 */
23500 	src = orig_src;
23501 	ipha->ipha_ident = ip_hdr_included;
23502 	goto another;
23503 
23504 #undef	rptr
23505 #undef	Q_TO_INDEX
23506 }
23507 
23508 /*
23509  * Routine to allocate a message that is used to notify the ULP about MDT.
23510  * The caller may provide a pointer to the link-layer MDT capabilities,
23511  * or NULL if MDT is to be disabled on the stream.
23512  */
23513 mblk_t *
23514 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23515 {
23516 	mblk_t *mp;
23517 	ip_mdt_info_t *mdti;
23518 	ill_mdt_capab_t *idst;
23519 
23520 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23521 		DB_TYPE(mp) = M_CTL;
23522 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23523 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23524 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23525 		idst = &(mdti->mdt_capab);
23526 
23527 		/*
23528 		 * If the caller provides us with the capability, copy
23529 		 * it over into our notification message; otherwise
23530 		 * we zero out the capability portion.
23531 		 */
23532 		if (isrc != NULL)
23533 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23534 		else
23535 			bzero((caddr_t)idst, sizeof (*idst));
23536 	}
23537 	return (mp);
23538 }
23539 
23540 /*
23541  * Routine which determines whether MDT can be enabled on the destination
23542  * IRE and IPC combination, and if so, allocates and returns the MDT
23543  * notification mblk that may be used by ULP.  We also check if we need to
23544  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23545  * MDT usage in the past have been lifted.  This gets called during IP
23546  * and ULP binding.
23547  */
23548 mblk_t *
23549 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23550     ill_mdt_capab_t *mdt_cap)
23551 {
23552 	mblk_t *mp;
23553 	boolean_t rc = B_FALSE;
23554 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23555 
23556 	ASSERT(dst_ire != NULL);
23557 	ASSERT(connp != NULL);
23558 	ASSERT(mdt_cap != NULL);
23559 
23560 	/*
23561 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23562 	 * Multidata, which is handled in tcp_multisend().  This
23563 	 * is the reason why we do all these checks here, to ensure
23564 	 * that we don't enable Multidata for the cases which we
23565 	 * can't handle at the moment.
23566 	 */
23567 	do {
23568 		/* Only do TCP at the moment */
23569 		if (connp->conn_ulp != IPPROTO_TCP)
23570 			break;
23571 
23572 		/*
23573 		 * IPsec outbound policy present?  Note that we get here
23574 		 * after calling ipsec_conn_cache_policy() where the global
23575 		 * policy checking is performed.  conn_latch will be
23576 		 * non-NULL as long as there's a policy defined,
23577 		 * i.e. conn_out_enforce_policy may be NULL in such case
23578 		 * when the connection is non-secure, and hence we check
23579 		 * further if the latch refers to an outbound policy.
23580 		 */
23581 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23582 			break;
23583 
23584 		/* CGTP (multiroute) is enabled? */
23585 		if (dst_ire->ire_flags & RTF_MULTIRT)
23586 			break;
23587 
23588 		/* Outbound IPQoS enabled? */
23589 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23590 			/*
23591 			 * In this case, we disable MDT for this and all
23592 			 * future connections going over the interface.
23593 			 */
23594 			mdt_cap->ill_mdt_on = 0;
23595 			break;
23596 		}
23597 
23598 		/* socket option(s) present? */
23599 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23600 			break;
23601 
23602 		rc = B_TRUE;
23603 	/* CONSTCOND */
23604 	} while (0);
23605 
23606 	/* Remember the result */
23607 	connp->conn_mdt_ok = rc;
23608 
23609 	if (!rc)
23610 		return (NULL);
23611 	else if (!mdt_cap->ill_mdt_on) {
23612 		/*
23613 		 * If MDT has been previously turned off in the past, and we
23614 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23615 		 * then enable it for this interface.
23616 		 */
23617 		mdt_cap->ill_mdt_on = 1;
23618 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23619 		    "interface %s\n", ill_name));
23620 	}
23621 
23622 	/* Allocate the MDT info mblk */
23623 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23624 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23625 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23626 		return (NULL);
23627 	}
23628 	return (mp);
23629 }
23630 
23631 /*
23632  * Routine to allocate a message that is used to notify the ULP about LSO.
23633  * The caller may provide a pointer to the link-layer LSO capabilities,
23634  * or NULL if LSO is to be disabled on the stream.
23635  */
23636 mblk_t *
23637 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23638 {
23639 	mblk_t *mp;
23640 	ip_lso_info_t *lsoi;
23641 	ill_lso_capab_t *idst;
23642 
23643 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23644 		DB_TYPE(mp) = M_CTL;
23645 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23646 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23647 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23648 		idst = &(lsoi->lso_capab);
23649 
23650 		/*
23651 		 * If the caller provides us with the capability, copy
23652 		 * it over into our notification message; otherwise
23653 		 * we zero out the capability portion.
23654 		 */
23655 		if (isrc != NULL)
23656 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23657 		else
23658 			bzero((caddr_t)idst, sizeof (*idst));
23659 	}
23660 	return (mp);
23661 }
23662 
23663 /*
23664  * Routine which determines whether LSO can be enabled on the destination
23665  * IRE and IPC combination, and if so, allocates and returns the LSO
23666  * notification mblk that may be used by ULP.  We also check if we need to
23667  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23668  * LSO usage in the past have been lifted.  This gets called during IP
23669  * and ULP binding.
23670  */
23671 mblk_t *
23672 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23673     ill_lso_capab_t *lso_cap)
23674 {
23675 	mblk_t *mp;
23676 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23677 
23678 	ASSERT(dst_ire != NULL);
23679 	ASSERT(connp != NULL);
23680 	ASSERT(lso_cap != NULL);
23681 
23682 	connp->conn_lso_ok = B_TRUE;
23683 
23684 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23685 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23686 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23687 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23688 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23689 		connp->conn_lso_ok = B_FALSE;
23690 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23691 			/*
23692 			 * Disable LSO for this and all future connections going
23693 			 * over the interface.
23694 			 */
23695 			lso_cap->ill_lso_on = 0;
23696 		}
23697 	}
23698 
23699 	if (!connp->conn_lso_ok)
23700 		return (NULL);
23701 	else if (!lso_cap->ill_lso_on) {
23702 		/*
23703 		 * If LSO has been previously turned off in the past, and we
23704 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23705 		 * then enable it for this interface.
23706 		 */
23707 		lso_cap->ill_lso_on = 1;
23708 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23709 		    ill_name));
23710 	}
23711 
23712 	/* Allocate the LSO info mblk */
23713 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23714 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23715 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23716 
23717 	return (mp);
23718 }
23719 
23720 /*
23721  * Create destination address attribute, and fill it with the physical
23722  * destination address and SAP taken from the template DL_UNITDATA_REQ
23723  * message block.
23724  */
23725 boolean_t
23726 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23727 {
23728 	dl_unitdata_req_t *dlurp;
23729 	pattr_t *pa;
23730 	pattrinfo_t pa_info;
23731 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23732 	uint_t das_len, das_off;
23733 
23734 	ASSERT(dlmp != NULL);
23735 
23736 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23737 	das_len = dlurp->dl_dest_addr_length;
23738 	das_off = dlurp->dl_dest_addr_offset;
23739 
23740 	pa_info.type = PATTR_DSTADDRSAP;
23741 	pa_info.len = sizeof (**das) + das_len - 1;
23742 
23743 	/* create and associate the attribute */
23744 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23745 	if (pa != NULL) {
23746 		ASSERT(*das != NULL);
23747 		(*das)->addr_is_group = 0;
23748 		(*das)->addr_len = (uint8_t)das_len;
23749 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23750 	}
23751 
23752 	return (pa != NULL);
23753 }
23754 
23755 /*
23756  * Create hardware checksum attribute and fill it with the values passed.
23757  */
23758 boolean_t
23759 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23760     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23761 {
23762 	pattr_t *pa;
23763 	pattrinfo_t pa_info;
23764 
23765 	ASSERT(mmd != NULL);
23766 
23767 	pa_info.type = PATTR_HCKSUM;
23768 	pa_info.len = sizeof (pattr_hcksum_t);
23769 
23770 	/* create and associate the attribute */
23771 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23772 	if (pa != NULL) {
23773 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23774 
23775 		hck->hcksum_start_offset = start_offset;
23776 		hck->hcksum_stuff_offset = stuff_offset;
23777 		hck->hcksum_end_offset = end_offset;
23778 		hck->hcksum_flags = flags;
23779 	}
23780 	return (pa != NULL);
23781 }
23782 
23783 /*
23784  * Create zerocopy attribute and fill it with the specified flags
23785  */
23786 boolean_t
23787 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23788 {
23789 	pattr_t *pa;
23790 	pattrinfo_t pa_info;
23791 
23792 	ASSERT(mmd != NULL);
23793 	pa_info.type = PATTR_ZCOPY;
23794 	pa_info.len = sizeof (pattr_zcopy_t);
23795 
23796 	/* create and associate the attribute */
23797 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23798 	if (pa != NULL) {
23799 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23800 
23801 		zcopy->zcopy_flags = flags;
23802 	}
23803 	return (pa != NULL);
23804 }
23805 
23806 /*
23807  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23808  * block chain. We could rewrite to handle arbitrary message block chains but
23809  * that would make the code complicated and slow. Right now there three
23810  * restrictions:
23811  *
23812  *   1. The first message block must contain the complete IP header and
23813  *	at least 1 byte of payload data.
23814  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23815  *	so that we can use a single Multidata message.
23816  *   3. No frag must be distributed over two or more message blocks so
23817  *	that we don't need more than two packet descriptors per frag.
23818  *
23819  * The above restrictions allow us to support userland applications (which
23820  * will send down a single message block) and NFS over UDP (which will
23821  * send down a chain of at most three message blocks).
23822  *
23823  * We also don't use MDT for payloads with less than or equal to
23824  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23825  */
23826 boolean_t
23827 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23828 {
23829 	int	blocks;
23830 	ssize_t	total, missing, size;
23831 
23832 	ASSERT(mp != NULL);
23833 	ASSERT(hdr_len > 0);
23834 
23835 	size = MBLKL(mp) - hdr_len;
23836 	if (size <= 0)
23837 		return (B_FALSE);
23838 
23839 	/* The first mblk contains the header and some payload. */
23840 	blocks = 1;
23841 	total = size;
23842 	size %= len;
23843 	missing = (size == 0) ? 0 : (len - size);
23844 	mp = mp->b_cont;
23845 
23846 	while (mp != NULL) {
23847 		/*
23848 		 * Give up if we encounter a zero length message block.
23849 		 * In practice, this should rarely happen and therefore
23850 		 * not worth the trouble of freeing and re-linking the
23851 		 * mblk from the chain to handle such case.
23852 		 */
23853 		if ((size = MBLKL(mp)) == 0)
23854 			return (B_FALSE);
23855 
23856 		/* Too many payload buffers for a single Multidata message? */
23857 		if (++blocks > MULTIDATA_MAX_PBUFS)
23858 			return (B_FALSE);
23859 
23860 		total += size;
23861 		/* Is a frag distributed over two or more message blocks? */
23862 		if (missing > size)
23863 			return (B_FALSE);
23864 		size -= missing;
23865 
23866 		size %= len;
23867 		missing = (size == 0) ? 0 : (len - size);
23868 
23869 		mp = mp->b_cont;
23870 	}
23871 
23872 	return (total > ip_wput_frag_mdt_min);
23873 }
23874 
23875 /*
23876  * Outbound IPv4 fragmentation routine using MDT.
23877  */
23878 static void
23879 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23880     uint32_t frag_flag, int offset)
23881 {
23882 	ipha_t		*ipha_orig;
23883 	int		i1, ip_data_end;
23884 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23885 	mblk_t		*hdr_mp, *md_mp = NULL;
23886 	unsigned char	*hdr_ptr, *pld_ptr;
23887 	multidata_t	*mmd;
23888 	ip_pdescinfo_t	pdi;
23889 	ill_t		*ill;
23890 	ip_stack_t	*ipst = ire->ire_ipst;
23891 
23892 	ASSERT(DB_TYPE(mp) == M_DATA);
23893 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23894 
23895 	ill = ire_to_ill(ire);
23896 	ASSERT(ill != NULL);
23897 
23898 	ipha_orig = (ipha_t *)mp->b_rptr;
23899 	mp->b_rptr += sizeof (ipha_t);
23900 
23901 	/* Calculate how many packets we will send out */
23902 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23903 	pkts = (i1 + len - 1) / len;
23904 	ASSERT(pkts > 1);
23905 
23906 	/* Allocate a message block which will hold all the IP Headers. */
23907 	wroff = ipst->ips_ip_wroff_extra;
23908 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23909 
23910 	i1 = pkts * hdr_chunk_len;
23911 	/*
23912 	 * Create the header buffer, Multidata and destination address
23913 	 * and SAP attribute that should be associated with it.
23914 	 */
23915 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23916 	    ((hdr_mp->b_wptr += i1),
23917 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23918 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23919 		freemsg(mp);
23920 		if (md_mp == NULL) {
23921 			freemsg(hdr_mp);
23922 		} else {
23923 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23924 			freemsg(md_mp);
23925 		}
23926 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23927 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23928 		return;
23929 	}
23930 	IP_STAT(ipst, ip_frag_mdt_allocd);
23931 
23932 	/*
23933 	 * Add a payload buffer to the Multidata; this operation must not
23934 	 * fail, or otherwise our logic in this routine is broken.  There
23935 	 * is no memory allocation done by the routine, so any returned
23936 	 * failure simply tells us that we've done something wrong.
23937 	 *
23938 	 * A failure tells us that either we're adding the same payload
23939 	 * buffer more than once, or we're trying to add more buffers than
23940 	 * allowed.  None of the above cases should happen, and we panic
23941 	 * because either there's horrible heap corruption, and/or
23942 	 * programming mistake.
23943 	 */
23944 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23945 		goto pbuf_panic;
23946 
23947 	hdr_ptr = hdr_mp->b_rptr;
23948 	pld_ptr = mp->b_rptr;
23949 
23950 	/* Establish the ending byte offset, based on the starting offset. */
23951 	offset <<= 3;
23952 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23953 	    IP_SIMPLE_HDR_LENGTH;
23954 
23955 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23956 
23957 	while (pld_ptr < mp->b_wptr) {
23958 		ipha_t		*ipha;
23959 		uint16_t	offset_and_flags;
23960 		uint16_t	ip_len;
23961 		int		error;
23962 
23963 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23964 		ipha = (ipha_t *)(hdr_ptr + wroff);
23965 		ASSERT(OK_32PTR(ipha));
23966 		*ipha = *ipha_orig;
23967 
23968 		if (ip_data_end - offset > len) {
23969 			offset_and_flags = IPH_MF;
23970 		} else {
23971 			/*
23972 			 * Last frag. Set len to the length of this last piece.
23973 			 */
23974 			len = ip_data_end - offset;
23975 			/* A frag of a frag might have IPH_MF non-zero */
23976 			offset_and_flags =
23977 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23978 			    IPH_MF;
23979 		}
23980 		offset_and_flags |= (uint16_t)(offset >> 3);
23981 		offset_and_flags |= (uint16_t)frag_flag;
23982 		/* Store the offset and flags in the IP header. */
23983 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23984 
23985 		/* Store the length in the IP header. */
23986 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23987 		ipha->ipha_length = htons(ip_len);
23988 
23989 		/*
23990 		 * Set the IP header checksum.  Note that mp is just
23991 		 * the header, so this is easy to pass to ip_csum.
23992 		 */
23993 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23994 
23995 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23996 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23997 		    NULL, int, 0);
23998 
23999 		/*
24000 		 * Record offset and size of header and data of the next packet
24001 		 * in the multidata message.
24002 		 */
24003 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24004 		PDESC_PLD_INIT(&pdi);
24005 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24006 		ASSERT(i1 > 0);
24007 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24008 		if (i1 == len) {
24009 			pld_ptr += len;
24010 		} else {
24011 			i1 = len - i1;
24012 			mp = mp->b_cont;
24013 			ASSERT(mp != NULL);
24014 			ASSERT(MBLKL(mp) >= i1);
24015 			/*
24016 			 * Attach the next payload message block to the
24017 			 * multidata message.
24018 			 */
24019 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24020 				goto pbuf_panic;
24021 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24022 			pld_ptr = mp->b_rptr + i1;
24023 		}
24024 
24025 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24026 		    KM_NOSLEEP)) == NULL) {
24027 			/*
24028 			 * Any failure other than ENOMEM indicates that we
24029 			 * have passed in invalid pdesc info or parameters
24030 			 * to mmd_addpdesc, which must not happen.
24031 			 *
24032 			 * EINVAL is a result of failure on boundary checks
24033 			 * against the pdesc info contents.  It should not
24034 			 * happen, and we panic because either there's
24035 			 * horrible heap corruption, and/or programming
24036 			 * mistake.
24037 			 */
24038 			if (error != ENOMEM) {
24039 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24040 				    "pdesc logic error detected for "
24041 				    "mmd %p pinfo %p (%d)\n",
24042 				    (void *)mmd, (void *)&pdi, error);
24043 				/* NOTREACHED */
24044 			}
24045 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24046 			/* Free unattached payload message blocks as well */
24047 			md_mp->b_cont = mp->b_cont;
24048 			goto free_mmd;
24049 		}
24050 
24051 		/* Advance fragment offset. */
24052 		offset += len;
24053 
24054 		/* Advance to location for next header in the buffer. */
24055 		hdr_ptr += hdr_chunk_len;
24056 
24057 		/* Did we reach the next payload message block? */
24058 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24059 			mp = mp->b_cont;
24060 			/*
24061 			 * Attach the next message block with payload
24062 			 * data to the multidata message.
24063 			 */
24064 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24065 				goto pbuf_panic;
24066 			pld_ptr = mp->b_rptr;
24067 		}
24068 	}
24069 
24070 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24071 	ASSERT(mp->b_wptr == pld_ptr);
24072 
24073 	/* Update IP statistics */
24074 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24075 
24076 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24077 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24078 
24079 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24080 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24081 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24082 
24083 	if (pkt_type == OB_PKT) {
24084 		ire->ire_ob_pkt_count += pkts;
24085 		if (ire->ire_ipif != NULL)
24086 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24087 	} else {
24088 		/* The type is IB_PKT in the forwarding path. */
24089 		ire->ire_ib_pkt_count += pkts;
24090 		ASSERT(!IRE_IS_LOCAL(ire));
24091 		if (ire->ire_type & IRE_BROADCAST) {
24092 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24093 		} else {
24094 			UPDATE_MIB(ill->ill_ip_mib,
24095 			    ipIfStatsHCOutForwDatagrams, pkts);
24096 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24097 		}
24098 	}
24099 	ire->ire_last_used_time = lbolt;
24100 	/* Send it down */
24101 	putnext(ire->ire_stq, md_mp);
24102 	return;
24103 
24104 pbuf_panic:
24105 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24106 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24107 	    pbuf_idx);
24108 	/* NOTREACHED */
24109 }
24110 
24111 /*
24112  * Outbound IP fragmentation routine.
24113  *
24114  * NOTE : This routine does not ire_refrele the ire that is passed in
24115  * as the argument.
24116  */
24117 static void
24118 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24119     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24120 {
24121 	int		i1;
24122 	mblk_t		*ll_hdr_mp;
24123 	int 		ll_hdr_len;
24124 	int		hdr_len;
24125 	mblk_t		*hdr_mp;
24126 	ipha_t		*ipha;
24127 	int		ip_data_end;
24128 	int		len;
24129 	mblk_t		*mp = mp_orig, *mp1;
24130 	int		offset;
24131 	queue_t		*q;
24132 	uint32_t	v_hlen_tos_len;
24133 	mblk_t		*first_mp;
24134 	boolean_t	mctl_present;
24135 	ill_t		*ill;
24136 	ill_t		*out_ill;
24137 	mblk_t		*xmit_mp;
24138 	mblk_t		*carve_mp;
24139 	ire_t		*ire1 = NULL;
24140 	ire_t		*save_ire = NULL;
24141 	mblk_t  	*next_mp = NULL;
24142 	boolean_t	last_frag = B_FALSE;
24143 	boolean_t	multirt_send = B_FALSE;
24144 	ire_t		*first_ire = NULL;
24145 	irb_t		*irb = NULL;
24146 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24147 
24148 	ill = ire_to_ill(ire);
24149 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24150 
24151 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24152 
24153 	if (max_frag == 0) {
24154 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24155 		    " -  dropping packet\n"));
24156 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24157 		freemsg(mp);
24158 		return;
24159 	}
24160 
24161 	/*
24162 	 * IPsec does not allow hw accelerated packets to be fragmented
24163 	 * This check is made in ip_wput_ipsec_out prior to coming here
24164 	 * via ip_wput_ire_fragmentit.
24165 	 *
24166 	 * If at this point we have an ire whose ARP request has not
24167 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24168 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24169 	 * This packet and all fragmentable packets for this ire will
24170 	 * continue to get dropped while ire_nce->nce_state remains in
24171 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24172 	 * ND_REACHABLE, all subsquent large packets for this ire will
24173 	 * get fragemented and sent out by this function.
24174 	 */
24175 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24176 		/* If nce_state is ND_INITIAL, trigger ARP query */
24177 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24178 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24179 		    " -  dropping packet\n"));
24180 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24181 		freemsg(mp);
24182 		return;
24183 	}
24184 
24185 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24186 	    "ip_wput_frag_start:");
24187 
24188 	if (mp->b_datap->db_type == M_CTL) {
24189 		first_mp = mp;
24190 		mp_orig = mp = mp->b_cont;
24191 		mctl_present = B_TRUE;
24192 	} else {
24193 		first_mp = mp;
24194 		mctl_present = B_FALSE;
24195 	}
24196 
24197 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24198 	ipha = (ipha_t *)mp->b_rptr;
24199 
24200 	/*
24201 	 * If the Don't Fragment flag is on, generate an ICMP destination
24202 	 * unreachable, fragmentation needed.
24203 	 */
24204 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24205 	if (offset & IPH_DF) {
24206 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24207 		if (is_system_labeled()) {
24208 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24209 			    ire->ire_max_frag - max_frag, AF_INET);
24210 		}
24211 		/*
24212 		 * Need to compute hdr checksum if called from ip_wput_ire.
24213 		 * Note that ip_rput_forward verifies the checksum before
24214 		 * calling this routine so in that case this is a noop.
24215 		 */
24216 		ipha->ipha_hdr_checksum = 0;
24217 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24218 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24219 		    ipst);
24220 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24221 		    "ip_wput_frag_end:(%S)",
24222 		    "don't fragment");
24223 		return;
24224 	}
24225 	/*
24226 	 * Labeled systems adjust max_frag if they add a label
24227 	 * to send the correct path mtu.  We need the real mtu since we
24228 	 * are fragmenting the packet after label adjustment.
24229 	 */
24230 	if (is_system_labeled())
24231 		max_frag = ire->ire_max_frag;
24232 	if (mctl_present)
24233 		freeb(first_mp);
24234 	/*
24235 	 * Establish the starting offset.  May not be zero if we are fragging
24236 	 * a fragment that is being forwarded.
24237 	 */
24238 	offset = offset & IPH_OFFSET;
24239 
24240 	/* TODO why is this test needed? */
24241 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24242 	if (((max_frag - LENGTH) & ~7) < 8) {
24243 		/* TODO: notify ulp somehow */
24244 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24245 		freemsg(mp);
24246 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24247 		    "ip_wput_frag_end:(%S)",
24248 		    "len < 8");
24249 		return;
24250 	}
24251 
24252 	hdr_len = (V_HLEN & 0xF) << 2;
24253 
24254 	ipha->ipha_hdr_checksum = 0;
24255 
24256 	/*
24257 	 * Establish the number of bytes maximum per frag, after putting
24258 	 * in the header.
24259 	 */
24260 	len = (max_frag - hdr_len) & ~7;
24261 
24262 	/* Check if we can use MDT to send out the frags. */
24263 	ASSERT(!IRE_IS_LOCAL(ire));
24264 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24265 	    ipst->ips_ip_multidata_outbound &&
24266 	    !(ire->ire_flags & RTF_MULTIRT) &&
24267 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24268 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24269 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24270 		ASSERT(ill->ill_mdt_capab != NULL);
24271 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24272 			/*
24273 			 * If MDT has been previously turned off in the past,
24274 			 * and we currently can do MDT (due to IPQoS policy
24275 			 * removal, etc.) then enable it for this interface.
24276 			 */
24277 			ill->ill_mdt_capab->ill_mdt_on = 1;
24278 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24279 			    ill->ill_name));
24280 		}
24281 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24282 		    offset);
24283 		return;
24284 	}
24285 
24286 	/* Get a copy of the header for the trailing frags */
24287 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24288 	    mp);
24289 	if (!hdr_mp) {
24290 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24291 		freemsg(mp);
24292 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24293 		    "ip_wput_frag_end:(%S)",
24294 		    "couldn't copy hdr");
24295 		return;
24296 	}
24297 
24298 	/* Store the starting offset, with the MoreFrags flag. */
24299 	i1 = offset | IPH_MF | frag_flag;
24300 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24301 
24302 	/* Establish the ending byte offset, based on the starting offset. */
24303 	offset <<= 3;
24304 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24305 
24306 	/* Store the length of the first fragment in the IP header. */
24307 	i1 = len + hdr_len;
24308 	ASSERT(i1 <= IP_MAXPACKET);
24309 	ipha->ipha_length = htons((uint16_t)i1);
24310 
24311 	/*
24312 	 * Compute the IP header checksum for the first frag.  We have to
24313 	 * watch out that we stop at the end of the header.
24314 	 */
24315 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24316 
24317 	/*
24318 	 * Now carve off the first frag.  Note that this will include the
24319 	 * original IP header.
24320 	 */
24321 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24322 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24323 		freeb(hdr_mp);
24324 		freemsg(mp_orig);
24325 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24326 		    "ip_wput_frag_end:(%S)",
24327 		    "couldn't carve first");
24328 		return;
24329 	}
24330 
24331 	/*
24332 	 * Multirouting case. Each fragment is replicated
24333 	 * via all non-condemned RTF_MULTIRT routes
24334 	 * currently resolved.
24335 	 * We ensure that first_ire is the first RTF_MULTIRT
24336 	 * ire in the bucket.
24337 	 */
24338 	if (ire->ire_flags & RTF_MULTIRT) {
24339 		irb = ire->ire_bucket;
24340 		ASSERT(irb != NULL);
24341 
24342 		multirt_send = B_TRUE;
24343 
24344 		/* Make sure we do not omit any multiroute ire. */
24345 		IRB_REFHOLD(irb);
24346 		for (first_ire = irb->irb_ire;
24347 		    first_ire != NULL;
24348 		    first_ire = first_ire->ire_next) {
24349 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24350 			    (first_ire->ire_addr == ire->ire_addr) &&
24351 			    !(first_ire->ire_marks &
24352 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24353 				break;
24354 		}
24355 
24356 		if (first_ire != NULL) {
24357 			if (first_ire != ire) {
24358 				IRE_REFHOLD(first_ire);
24359 				/*
24360 				 * Do not release the ire passed in
24361 				 * as the argument.
24362 				 */
24363 				ire = first_ire;
24364 			} else {
24365 				first_ire = NULL;
24366 			}
24367 		}
24368 		IRB_REFRELE(irb);
24369 
24370 		/*
24371 		 * Save the first ire; we will need to restore it
24372 		 * for the trailing frags.
24373 		 * We REFHOLD save_ire, as each iterated ire will be
24374 		 * REFRELEd.
24375 		 */
24376 		save_ire = ire;
24377 		IRE_REFHOLD(save_ire);
24378 	}
24379 
24380 	/*
24381 	 * First fragment emission loop.
24382 	 * In most cases, the emission loop below is entered only
24383 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24384 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24385 	 * bucket, and send the fragment through all crossed
24386 	 * RTF_MULTIRT routes.
24387 	 */
24388 	do {
24389 		if (ire->ire_flags & RTF_MULTIRT) {
24390 			/*
24391 			 * We are in a multiple send case, need to get
24392 			 * the next ire and make a copy of the packet.
24393 			 * ire1 holds here the next ire to process in the
24394 			 * bucket. If multirouting is expected,
24395 			 * any non-RTF_MULTIRT ire that has the
24396 			 * right destination address is ignored.
24397 			 *
24398 			 * We have to take into account the MTU of
24399 			 * each walked ire. max_frag is set by the
24400 			 * the caller and generally refers to
24401 			 * the primary ire entry. Here we ensure that
24402 			 * no route with a lower MTU will be used, as
24403 			 * fragments are carved once for all ires,
24404 			 * then replicated.
24405 			 */
24406 			ASSERT(irb != NULL);
24407 			IRB_REFHOLD(irb);
24408 			for (ire1 = ire->ire_next;
24409 			    ire1 != NULL;
24410 			    ire1 = ire1->ire_next) {
24411 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24412 					continue;
24413 				if (ire1->ire_addr != ire->ire_addr)
24414 					continue;
24415 				if (ire1->ire_marks &
24416 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24417 					continue;
24418 				/*
24419 				 * Ensure we do not exceed the MTU
24420 				 * of the next route.
24421 				 */
24422 				if (ire1->ire_max_frag < max_frag) {
24423 					ip_multirt_bad_mtu(ire1, max_frag);
24424 					continue;
24425 				}
24426 
24427 				/* Got one. */
24428 				IRE_REFHOLD(ire1);
24429 				break;
24430 			}
24431 			IRB_REFRELE(irb);
24432 
24433 			if (ire1 != NULL) {
24434 				next_mp = copyb(mp);
24435 				if ((next_mp == NULL) ||
24436 				    ((mp->b_cont != NULL) &&
24437 				    ((next_mp->b_cont =
24438 				    dupmsg(mp->b_cont)) == NULL))) {
24439 					freemsg(next_mp);
24440 					next_mp = NULL;
24441 					ire_refrele(ire1);
24442 					ire1 = NULL;
24443 				}
24444 			}
24445 
24446 			/* Last multiroute ire; don't loop anymore. */
24447 			if (ire1 == NULL) {
24448 				multirt_send = B_FALSE;
24449 			}
24450 		}
24451 
24452 		ll_hdr_len = 0;
24453 		LOCK_IRE_FP_MP(ire);
24454 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24455 		if (ll_hdr_mp != NULL) {
24456 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24457 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24458 		} else {
24459 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24460 		}
24461 
24462 		/* If there is a transmit header, get a copy for this frag. */
24463 		/*
24464 		 * TODO: should check db_ref before calling ip_carve_mp since
24465 		 * it might give us a dup.
24466 		 */
24467 		if (!ll_hdr_mp) {
24468 			/* No xmit header. */
24469 			xmit_mp = mp;
24470 
24471 		/* We have a link-layer header that can fit in our mblk. */
24472 		} else if (mp->b_datap->db_ref == 1 &&
24473 		    ll_hdr_len != 0 &&
24474 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24475 			/* M_DATA fastpath */
24476 			mp->b_rptr -= ll_hdr_len;
24477 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24478 			xmit_mp = mp;
24479 
24480 		/* Corner case if copyb has failed */
24481 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24482 			UNLOCK_IRE_FP_MP(ire);
24483 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24484 			freeb(hdr_mp);
24485 			freemsg(mp);
24486 			freemsg(mp_orig);
24487 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24488 			    "ip_wput_frag_end:(%S)",
24489 			    "discard");
24490 
24491 			if (multirt_send) {
24492 				ASSERT(ire1);
24493 				ASSERT(next_mp);
24494 
24495 				freemsg(next_mp);
24496 				ire_refrele(ire1);
24497 			}
24498 			if (save_ire != NULL)
24499 				IRE_REFRELE(save_ire);
24500 
24501 			if (first_ire != NULL)
24502 				ire_refrele(first_ire);
24503 			return;
24504 
24505 		/*
24506 		 * Case of res_mp OR the fastpath mp can't fit
24507 		 * in the mblk
24508 		 */
24509 		} else {
24510 			xmit_mp->b_cont = mp;
24511 
24512 			/*
24513 			 * Get priority marking, if any.
24514 			 * We propagate the CoS marking from the
24515 			 * original packet that went to QoS processing
24516 			 * in ip_wput_ire to the newly carved mp.
24517 			 */
24518 			if (DB_TYPE(xmit_mp) == M_DATA)
24519 				xmit_mp->b_band = mp->b_band;
24520 		}
24521 		UNLOCK_IRE_FP_MP(ire);
24522 
24523 		q = ire->ire_stq;
24524 		out_ill = (ill_t *)q->q_ptr;
24525 
24526 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24527 
24528 		DTRACE_PROBE4(ip4__physical__out__start,
24529 		    ill_t *, NULL, ill_t *, out_ill,
24530 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24531 
24532 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24533 		    ipst->ips_ipv4firewall_physical_out,
24534 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24535 
24536 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24537 
24538 		if (xmit_mp != NULL) {
24539 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24540 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24541 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24542 
24543 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24544 
24545 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24546 			UPDATE_MIB(out_ill->ill_ip_mib,
24547 			    ipIfStatsHCOutOctets, i1);
24548 
24549 			if (pkt_type != OB_PKT) {
24550 				/*
24551 				 * Update the packet count and MIB stats
24552 				 * of trailing RTF_MULTIRT ires.
24553 				 */
24554 				UPDATE_OB_PKT_COUNT(ire);
24555 				BUMP_MIB(out_ill->ill_ip_mib,
24556 				    ipIfStatsOutFragReqds);
24557 			}
24558 		}
24559 
24560 		if (multirt_send) {
24561 			/*
24562 			 * We are in a multiple send case; look for
24563 			 * the next ire and re-enter the loop.
24564 			 */
24565 			ASSERT(ire1);
24566 			ASSERT(next_mp);
24567 			/* REFRELE the current ire before looping */
24568 			ire_refrele(ire);
24569 			ire = ire1;
24570 			ire1 = NULL;
24571 			mp = next_mp;
24572 			next_mp = NULL;
24573 		}
24574 	} while (multirt_send);
24575 
24576 	ASSERT(ire1 == NULL);
24577 
24578 	/* Restore the original ire; we need it for the trailing frags */
24579 	if (save_ire != NULL) {
24580 		/* REFRELE the last iterated ire */
24581 		ire_refrele(ire);
24582 		/* save_ire has been REFHOLDed */
24583 		ire = save_ire;
24584 		save_ire = NULL;
24585 		q = ire->ire_stq;
24586 	}
24587 
24588 	if (pkt_type == OB_PKT) {
24589 		UPDATE_OB_PKT_COUNT(ire);
24590 	} else {
24591 		out_ill = (ill_t *)q->q_ptr;
24592 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24593 		UPDATE_IB_PKT_COUNT(ire);
24594 	}
24595 
24596 	/* Advance the offset to the second frag starting point. */
24597 	offset += len;
24598 	/*
24599 	 * Update hdr_len from the copied header - there might be less options
24600 	 * in the later fragments.
24601 	 */
24602 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24603 	/* Loop until done. */
24604 	for (;;) {
24605 		uint16_t	offset_and_flags;
24606 		uint16_t	ip_len;
24607 
24608 		if (ip_data_end - offset > len) {
24609 			/*
24610 			 * Carve off the appropriate amount from the original
24611 			 * datagram.
24612 			 */
24613 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24614 				mp = NULL;
24615 				break;
24616 			}
24617 			/*
24618 			 * More frags after this one.  Get another copy
24619 			 * of the header.
24620 			 */
24621 			if (carve_mp->b_datap->db_ref == 1 &&
24622 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24623 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24624 				/* Inline IP header */
24625 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24626 				    hdr_mp->b_rptr;
24627 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24628 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24629 				mp = carve_mp;
24630 			} else {
24631 				if (!(mp = copyb(hdr_mp))) {
24632 					freemsg(carve_mp);
24633 					break;
24634 				}
24635 				/* Get priority marking, if any. */
24636 				mp->b_band = carve_mp->b_band;
24637 				mp->b_cont = carve_mp;
24638 			}
24639 			ipha = (ipha_t *)mp->b_rptr;
24640 			offset_and_flags = IPH_MF;
24641 		} else {
24642 			/*
24643 			 * Last frag.  Consume the header. Set len to
24644 			 * the length of this last piece.
24645 			 */
24646 			len = ip_data_end - offset;
24647 
24648 			/*
24649 			 * Carve off the appropriate amount from the original
24650 			 * datagram.
24651 			 */
24652 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24653 				mp = NULL;
24654 				break;
24655 			}
24656 			if (carve_mp->b_datap->db_ref == 1 &&
24657 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24658 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24659 				/* Inline IP header */
24660 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24661 				    hdr_mp->b_rptr;
24662 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24663 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24664 				mp = carve_mp;
24665 				freeb(hdr_mp);
24666 				hdr_mp = mp;
24667 			} else {
24668 				mp = hdr_mp;
24669 				/* Get priority marking, if any. */
24670 				mp->b_band = carve_mp->b_band;
24671 				mp->b_cont = carve_mp;
24672 			}
24673 			ipha = (ipha_t *)mp->b_rptr;
24674 			/* A frag of a frag might have IPH_MF non-zero */
24675 			offset_and_flags =
24676 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24677 			    IPH_MF;
24678 		}
24679 		offset_and_flags |= (uint16_t)(offset >> 3);
24680 		offset_and_flags |= (uint16_t)frag_flag;
24681 		/* Store the offset and flags in the IP header. */
24682 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24683 
24684 		/* Store the length in the IP header. */
24685 		ip_len = (uint16_t)(len + hdr_len);
24686 		ipha->ipha_length = htons(ip_len);
24687 
24688 		/*
24689 		 * Set the IP header checksum.	Note that mp is just
24690 		 * the header, so this is easy to pass to ip_csum.
24691 		 */
24692 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24693 
24694 		/* Attach a transmit header, if any, and ship it. */
24695 		if (pkt_type == OB_PKT) {
24696 			UPDATE_OB_PKT_COUNT(ire);
24697 		} else {
24698 			out_ill = (ill_t *)q->q_ptr;
24699 			BUMP_MIB(out_ill->ill_ip_mib,
24700 			    ipIfStatsHCOutForwDatagrams);
24701 			UPDATE_IB_PKT_COUNT(ire);
24702 		}
24703 
24704 		if (ire->ire_flags & RTF_MULTIRT) {
24705 			irb = ire->ire_bucket;
24706 			ASSERT(irb != NULL);
24707 
24708 			multirt_send = B_TRUE;
24709 
24710 			/*
24711 			 * Save the original ire; we will need to restore it
24712 			 * for the tailing frags.
24713 			 */
24714 			save_ire = ire;
24715 			IRE_REFHOLD(save_ire);
24716 		}
24717 		/*
24718 		 * Emission loop for this fragment, similar
24719 		 * to what is done for the first fragment.
24720 		 */
24721 		do {
24722 			if (multirt_send) {
24723 				/*
24724 				 * We are in a multiple send case, need to get
24725 				 * the next ire and make a copy of the packet.
24726 				 */
24727 				ASSERT(irb != NULL);
24728 				IRB_REFHOLD(irb);
24729 				for (ire1 = ire->ire_next;
24730 				    ire1 != NULL;
24731 				    ire1 = ire1->ire_next) {
24732 					if (!(ire1->ire_flags & RTF_MULTIRT))
24733 						continue;
24734 					if (ire1->ire_addr != ire->ire_addr)
24735 						continue;
24736 					if (ire1->ire_marks &
24737 					    (IRE_MARK_CONDEMNED |
24738 					    IRE_MARK_TESTHIDDEN))
24739 						continue;
24740 					/*
24741 					 * Ensure we do not exceed the MTU
24742 					 * of the next route.
24743 					 */
24744 					if (ire1->ire_max_frag < max_frag) {
24745 						ip_multirt_bad_mtu(ire1,
24746 						    max_frag);
24747 						continue;
24748 					}
24749 
24750 					/* Got one. */
24751 					IRE_REFHOLD(ire1);
24752 					break;
24753 				}
24754 				IRB_REFRELE(irb);
24755 
24756 				if (ire1 != NULL) {
24757 					next_mp = copyb(mp);
24758 					if ((next_mp == NULL) ||
24759 					    ((mp->b_cont != NULL) &&
24760 					    ((next_mp->b_cont =
24761 					    dupmsg(mp->b_cont)) == NULL))) {
24762 						freemsg(next_mp);
24763 						next_mp = NULL;
24764 						ire_refrele(ire1);
24765 						ire1 = NULL;
24766 					}
24767 				}
24768 
24769 				/* Last multiroute ire; don't loop anymore. */
24770 				if (ire1 == NULL) {
24771 					multirt_send = B_FALSE;
24772 				}
24773 			}
24774 
24775 			/* Update transmit header */
24776 			ll_hdr_len = 0;
24777 			LOCK_IRE_FP_MP(ire);
24778 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24779 			if (ll_hdr_mp != NULL) {
24780 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24781 				ll_hdr_len = MBLKL(ll_hdr_mp);
24782 			} else {
24783 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24784 			}
24785 
24786 			if (!ll_hdr_mp) {
24787 				xmit_mp = mp;
24788 
24789 			/*
24790 			 * We have link-layer header that can fit in
24791 			 * our mblk.
24792 			 */
24793 			} else if (mp->b_datap->db_ref == 1 &&
24794 			    ll_hdr_len != 0 &&
24795 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24796 				/* M_DATA fastpath */
24797 				mp->b_rptr -= ll_hdr_len;
24798 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24799 				    ll_hdr_len);
24800 				xmit_mp = mp;
24801 
24802 			/*
24803 			 * Case of res_mp OR the fastpath mp can't fit
24804 			 * in the mblk
24805 			 */
24806 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24807 				xmit_mp->b_cont = mp;
24808 				/* Get priority marking, if any. */
24809 				if (DB_TYPE(xmit_mp) == M_DATA)
24810 					xmit_mp->b_band = mp->b_band;
24811 
24812 			/* Corner case if copyb failed */
24813 			} else {
24814 				/*
24815 				 * Exit both the replication and
24816 				 * fragmentation loops.
24817 				 */
24818 				UNLOCK_IRE_FP_MP(ire);
24819 				goto drop_pkt;
24820 			}
24821 			UNLOCK_IRE_FP_MP(ire);
24822 
24823 			mp1 = mp;
24824 			out_ill = (ill_t *)q->q_ptr;
24825 
24826 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24827 
24828 			DTRACE_PROBE4(ip4__physical__out__start,
24829 			    ill_t *, NULL, ill_t *, out_ill,
24830 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24831 
24832 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24833 			    ipst->ips_ipv4firewall_physical_out,
24834 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24835 
24836 			DTRACE_PROBE1(ip4__physical__out__end,
24837 			    mblk_t *, xmit_mp);
24838 
24839 			if (mp != mp1 && hdr_mp == mp1)
24840 				hdr_mp = mp;
24841 			if (mp != mp1 && mp_orig == mp1)
24842 				mp_orig = mp;
24843 
24844 			if (xmit_mp != NULL) {
24845 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24846 				    NULL, void_ip_t *, ipha,
24847 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24848 				    ipha, ip6_t *, NULL, int, 0);
24849 
24850 				ILL_SEND_TX(out_ill, ire, connp,
24851 				    xmit_mp, 0, connp);
24852 
24853 				BUMP_MIB(out_ill->ill_ip_mib,
24854 				    ipIfStatsHCOutTransmits);
24855 				UPDATE_MIB(out_ill->ill_ip_mib,
24856 				    ipIfStatsHCOutOctets, ip_len);
24857 
24858 				if (pkt_type != OB_PKT) {
24859 					/*
24860 					 * Update the packet count of trailing
24861 					 * RTF_MULTIRT ires.
24862 					 */
24863 					UPDATE_OB_PKT_COUNT(ire);
24864 				}
24865 			}
24866 
24867 			/* All done if we just consumed the hdr_mp. */
24868 			if (mp == hdr_mp) {
24869 				last_frag = B_TRUE;
24870 				BUMP_MIB(out_ill->ill_ip_mib,
24871 				    ipIfStatsOutFragOKs);
24872 			}
24873 
24874 			if (multirt_send) {
24875 				/*
24876 				 * We are in a multiple send case; look for
24877 				 * the next ire and re-enter the loop.
24878 				 */
24879 				ASSERT(ire1);
24880 				ASSERT(next_mp);
24881 				/* REFRELE the current ire before looping */
24882 				ire_refrele(ire);
24883 				ire = ire1;
24884 				ire1 = NULL;
24885 				q = ire->ire_stq;
24886 				mp = next_mp;
24887 				next_mp = NULL;
24888 			}
24889 		} while (multirt_send);
24890 		/*
24891 		 * Restore the original ire; we need it for the
24892 		 * trailing frags
24893 		 */
24894 		if (save_ire != NULL) {
24895 			ASSERT(ire1 == NULL);
24896 			/* REFRELE the last iterated ire */
24897 			ire_refrele(ire);
24898 			/* save_ire has been REFHOLDed */
24899 			ire = save_ire;
24900 			q = ire->ire_stq;
24901 			save_ire = NULL;
24902 		}
24903 
24904 		if (last_frag) {
24905 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24906 			    "ip_wput_frag_end:(%S)",
24907 			    "consumed hdr_mp");
24908 
24909 			if (first_ire != NULL)
24910 				ire_refrele(first_ire);
24911 			return;
24912 		}
24913 		/* Otherwise, advance and loop. */
24914 		offset += len;
24915 	}
24916 
24917 drop_pkt:
24918 	/* Clean up following allocation failure. */
24919 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24920 	freemsg(mp);
24921 	if (mp != hdr_mp)
24922 		freeb(hdr_mp);
24923 	if (mp != mp_orig)
24924 		freemsg(mp_orig);
24925 
24926 	if (save_ire != NULL)
24927 		IRE_REFRELE(save_ire);
24928 	if (first_ire != NULL)
24929 		ire_refrele(first_ire);
24930 
24931 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24932 	    "ip_wput_frag_end:(%S)",
24933 	    "end--alloc failure");
24934 }
24935 
24936 /*
24937  * Copy the header plus those options which have the copy bit set
24938  * src is the template to make sure we preserve the cred for TX purposes.
24939  */
24940 static mblk_t *
24941 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24942     mblk_t *src)
24943 {
24944 	mblk_t	*mp;
24945 	uchar_t	*up;
24946 
24947 	/*
24948 	 * Quick check if we need to look for options without the copy bit
24949 	 * set
24950 	 */
24951 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24952 	if (!mp)
24953 		return (mp);
24954 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24955 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24956 		bcopy(rptr, mp->b_rptr, hdr_len);
24957 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24958 		return (mp);
24959 	}
24960 	up  = mp->b_rptr;
24961 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24962 	up += IP_SIMPLE_HDR_LENGTH;
24963 	rptr += IP_SIMPLE_HDR_LENGTH;
24964 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24965 	while (hdr_len > 0) {
24966 		uint32_t optval;
24967 		uint32_t optlen;
24968 
24969 		optval = *rptr;
24970 		if (optval == IPOPT_EOL)
24971 			break;
24972 		if (optval == IPOPT_NOP)
24973 			optlen = 1;
24974 		else
24975 			optlen = rptr[1];
24976 		if (optval & IPOPT_COPY) {
24977 			bcopy(rptr, up, optlen);
24978 			up += optlen;
24979 		}
24980 		rptr += optlen;
24981 		hdr_len -= optlen;
24982 	}
24983 	/*
24984 	 * Make sure that we drop an even number of words by filling
24985 	 * with EOL to the next word boundary.
24986 	 */
24987 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24988 	    hdr_len & 0x3; hdr_len++)
24989 		*up++ = IPOPT_EOL;
24990 	mp->b_wptr = up;
24991 	/* Update header length */
24992 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24993 	return (mp);
24994 }
24995 
24996 /*
24997  * Delivery to local recipients including fanout to multiple recipients.
24998  * Does not do checksumming of UDP/TCP.
24999  * Note: q should be the read side queue for either the ill or conn.
25000  * Note: rq should be the read side q for the lower (ill) stream.
25001  * We don't send packets to IPPF processing, thus the last argument
25002  * to all the fanout calls are B_FALSE.
25003  */
25004 void
25005 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25006     int fanout_flags, zoneid_t zoneid)
25007 {
25008 	uint32_t	protocol;
25009 	mblk_t		*first_mp;
25010 	boolean_t	mctl_present;
25011 	int		ire_type;
25012 #define	rptr	((uchar_t *)ipha)
25013 	ip_stack_t	*ipst = ill->ill_ipst;
25014 
25015 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25016 	    "ip_wput_local_start: q %p", q);
25017 
25018 	if (ire != NULL) {
25019 		ire_type = ire->ire_type;
25020 	} else {
25021 		/*
25022 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25023 		 * packet is not multicast, we can't tell the ire type.
25024 		 */
25025 		ASSERT(CLASSD(ipha->ipha_dst));
25026 		ire_type = IRE_BROADCAST;
25027 	}
25028 
25029 	first_mp = mp;
25030 	if (first_mp->b_datap->db_type == M_CTL) {
25031 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25032 		if (!io->ipsec_out_secure) {
25033 			/*
25034 			 * This ipsec_out_t was allocated in ip_wput
25035 			 * for multicast packets to store the ill_index.
25036 			 * As this is being delivered locally, we don't
25037 			 * need this anymore.
25038 			 */
25039 			mp = first_mp->b_cont;
25040 			freeb(first_mp);
25041 			first_mp = mp;
25042 			mctl_present = B_FALSE;
25043 		} else {
25044 			/*
25045 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25046 			 * security properties for the looped-back packet.
25047 			 */
25048 			mctl_present = B_TRUE;
25049 			mp = first_mp->b_cont;
25050 			ASSERT(mp != NULL);
25051 			ipsec_out_to_in(first_mp);
25052 		}
25053 	} else {
25054 		mctl_present = B_FALSE;
25055 	}
25056 
25057 	DTRACE_PROBE4(ip4__loopback__in__start,
25058 	    ill_t *, ill, ill_t *, NULL,
25059 	    ipha_t *, ipha, mblk_t *, first_mp);
25060 
25061 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25062 	    ipst->ips_ipv4firewall_loopback_in,
25063 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25064 
25065 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25066 
25067 	if (first_mp == NULL)
25068 		return;
25069 
25070 	if (ipst->ips_ipobs_enabled) {
25071 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25072 		zoneid_t stackzoneid = netstackid_to_zoneid(
25073 		    ipst->ips_netstack->netstack_stackid);
25074 
25075 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25076 		/*
25077 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25078 		 * address.  Restrict the lookup below to the destination zone.
25079 		 */
25080 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25081 			lookup_zoneid = zoneid;
25082 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25083 		    lookup_zoneid);
25084 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25085 		    IPV4_VERSION, 0, ipst);
25086 	}
25087 
25088 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25089 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25090 	    int, 1);
25091 
25092 	ipst->ips_loopback_packets++;
25093 
25094 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25095 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25096 	if (!IS_SIMPLE_IPH(ipha)) {
25097 		ip_wput_local_options(ipha, ipst);
25098 	}
25099 
25100 	protocol = ipha->ipha_protocol;
25101 	switch (protocol) {
25102 	case IPPROTO_ICMP: {
25103 		ire_t		*ire_zone;
25104 		ilm_t		*ilm;
25105 		mblk_t		*mp1;
25106 		zoneid_t	last_zoneid;
25107 		ilm_walker_t	ilw;
25108 
25109 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25110 			ASSERT(ire_type == IRE_BROADCAST);
25111 			/*
25112 			 * In the multicast case, applications may have joined
25113 			 * the group from different zones, so we need to deliver
25114 			 * the packet to each of them. Loop through the
25115 			 * multicast memberships structures (ilm) on the receive
25116 			 * ill and send a copy of the packet up each matching
25117 			 * one. However, we don't do this for multicasts sent on
25118 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25119 			 * they must stay in the sender's zone.
25120 			 *
25121 			 * ilm_add_v6() ensures that ilms in the same zone are
25122 			 * contiguous in the ill_ilm list. We use this property
25123 			 * to avoid sending duplicates needed when two
25124 			 * applications in the same zone join the same group on
25125 			 * different logical interfaces: we ignore the ilm if
25126 			 * it's zoneid is the same as the last matching one.
25127 			 * In addition, the sending of the packet for
25128 			 * ire_zoneid is delayed until all of the other ilms
25129 			 * have been exhausted.
25130 			 */
25131 			last_zoneid = -1;
25132 			ilm = ilm_walker_start(&ilw, ill);
25133 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25134 				if (ipha->ipha_dst != ilm->ilm_addr ||
25135 				    ilm->ilm_zoneid == last_zoneid ||
25136 				    ilm->ilm_zoneid == zoneid ||
25137 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25138 					continue;
25139 				mp1 = ip_copymsg(first_mp);
25140 				if (mp1 == NULL)
25141 					continue;
25142 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25143 				    0, 0, mctl_present, B_FALSE, ill,
25144 				    ilm->ilm_zoneid);
25145 				last_zoneid = ilm->ilm_zoneid;
25146 			}
25147 			ilm_walker_finish(&ilw);
25148 			/*
25149 			 * Loopback case: the sending endpoint has
25150 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25151 			 * dispatch the multicast packet to the sending zone.
25152 			 */
25153 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25154 				freemsg(first_mp);
25155 				return;
25156 			}
25157 		} else if (ire_type == IRE_BROADCAST) {
25158 			/*
25159 			 * In the broadcast case, there may be many zones
25160 			 * which need a copy of the packet delivered to them.
25161 			 * There is one IRE_BROADCAST per broadcast address
25162 			 * and per zone; we walk those using a helper function.
25163 			 * In addition, the sending of the packet for zoneid is
25164 			 * delayed until all of the other ires have been
25165 			 * processed.
25166 			 */
25167 			IRB_REFHOLD(ire->ire_bucket);
25168 			ire_zone = NULL;
25169 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25170 			    ire)) != NULL) {
25171 				mp1 = ip_copymsg(first_mp);
25172 				if (mp1 == NULL)
25173 					continue;
25174 
25175 				UPDATE_IB_PKT_COUNT(ire_zone);
25176 				ire_zone->ire_last_used_time = lbolt;
25177 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25178 				    mctl_present, B_FALSE, ill,
25179 				    ire_zone->ire_zoneid);
25180 			}
25181 			IRB_REFRELE(ire->ire_bucket);
25182 		}
25183 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25184 		    0, mctl_present, B_FALSE, ill, zoneid);
25185 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25186 		    "ip_wput_local_end: q %p (%S)",
25187 		    q, "icmp");
25188 		return;
25189 	}
25190 	case IPPROTO_IGMP:
25191 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25192 			/* Bad packet - discarded by igmp_input */
25193 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25194 			    "ip_wput_local_end: q %p (%S)",
25195 			    q, "igmp_input--bad packet");
25196 			if (mctl_present)
25197 				freeb(first_mp);
25198 			return;
25199 		}
25200 		/*
25201 		 * igmp_input() may have returned the pulled up message.
25202 		 * So first_mp and ipha need to be reinitialized.
25203 		 */
25204 		ipha = (ipha_t *)mp->b_rptr;
25205 		if (mctl_present)
25206 			first_mp->b_cont = mp;
25207 		else
25208 			first_mp = mp;
25209 		/* deliver to local raw users */
25210 		break;
25211 	case IPPROTO_ENCAP:
25212 		/*
25213 		 * This case is covered by either ip_fanout_proto, or by
25214 		 * the above security processing for self-tunneled packets.
25215 		 */
25216 		break;
25217 	case IPPROTO_UDP: {
25218 		uint16_t	*up;
25219 		uint32_t	ports;
25220 
25221 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25222 		    UDP_PORTS_OFFSET);
25223 		/* Force a 'valid' checksum. */
25224 		up[3] = 0;
25225 
25226 		ports = *(uint32_t *)up;
25227 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25228 		    (ire_type == IRE_BROADCAST),
25229 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25230 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25231 		    ill, zoneid);
25232 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25233 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25234 		return;
25235 	}
25236 	case IPPROTO_TCP: {
25237 
25238 		/*
25239 		 * For TCP, discard broadcast packets.
25240 		 */
25241 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25242 			freemsg(first_mp);
25243 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25244 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25245 			return;
25246 		}
25247 
25248 		if (mp->b_datap->db_type == M_DATA) {
25249 			/*
25250 			 * M_DATA mblk, so init mblk (chain) for no struio().
25251 			 */
25252 			mblk_t	*mp1 = mp;
25253 
25254 			do {
25255 				mp1->b_datap->db_struioflag = 0;
25256 			} while ((mp1 = mp1->b_cont) != NULL);
25257 		}
25258 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25259 		    <= mp->b_wptr);
25260 		ip_fanout_tcp(q, first_mp, ill, ipha,
25261 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25262 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25263 		    mctl_present, B_FALSE, zoneid);
25264 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25265 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25266 		return;
25267 	}
25268 	case IPPROTO_SCTP:
25269 	{
25270 		uint32_t	ports;
25271 
25272 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25273 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25274 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25275 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25276 		return;
25277 	}
25278 
25279 	default:
25280 		break;
25281 	}
25282 	/*
25283 	 * Find a client for some other protocol.  We give
25284 	 * copies to multiple clients, if more than one is
25285 	 * bound.
25286 	 */
25287 	ip_fanout_proto(q, first_mp, ill, ipha,
25288 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25289 	    mctl_present, B_FALSE, ill, zoneid);
25290 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25291 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25292 #undef	rptr
25293 }
25294 
25295 /*
25296  * Update any source route, record route, or timestamp options.
25297  * Check that we are at end of strict source route.
25298  * The options have been sanity checked by ip_wput_options().
25299  */
25300 static void
25301 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25302 {
25303 	ipoptp_t	opts;
25304 	uchar_t		*opt;
25305 	uint8_t		optval;
25306 	uint8_t		optlen;
25307 	ipaddr_t	dst;
25308 	uint32_t	ts;
25309 	ire_t		*ire;
25310 	timestruc_t	now;
25311 
25312 	ip2dbg(("ip_wput_local_options\n"));
25313 	for (optval = ipoptp_first(&opts, ipha);
25314 	    optval != IPOPT_EOL;
25315 	    optval = ipoptp_next(&opts)) {
25316 		opt = opts.ipoptp_cur;
25317 		optlen = opts.ipoptp_len;
25318 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25319 		switch (optval) {
25320 			uint32_t off;
25321 		case IPOPT_SSRR:
25322 		case IPOPT_LSRR:
25323 			off = opt[IPOPT_OFFSET];
25324 			off--;
25325 			if (optlen < IP_ADDR_LEN ||
25326 			    off > optlen - IP_ADDR_LEN) {
25327 				/* End of source route */
25328 				break;
25329 			}
25330 			/*
25331 			 * This will only happen if two consecutive entries
25332 			 * in the source route contains our address or if
25333 			 * it is a packet with a loose source route which
25334 			 * reaches us before consuming the whole source route
25335 			 */
25336 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25337 			if (optval == IPOPT_SSRR) {
25338 				return;
25339 			}
25340 			/*
25341 			 * Hack: instead of dropping the packet truncate the
25342 			 * source route to what has been used by filling the
25343 			 * rest with IPOPT_NOP.
25344 			 */
25345 			opt[IPOPT_OLEN] = (uint8_t)off;
25346 			while (off < optlen) {
25347 				opt[off++] = IPOPT_NOP;
25348 			}
25349 			break;
25350 		case IPOPT_RR:
25351 			off = opt[IPOPT_OFFSET];
25352 			off--;
25353 			if (optlen < IP_ADDR_LEN ||
25354 			    off > optlen - IP_ADDR_LEN) {
25355 				/* No more room - ignore */
25356 				ip1dbg((
25357 				    "ip_wput_forward_options: end of RR\n"));
25358 				break;
25359 			}
25360 			dst = htonl(INADDR_LOOPBACK);
25361 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25362 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25363 			break;
25364 		case IPOPT_TS:
25365 			/* Insert timestamp if there is romm */
25366 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25367 			case IPOPT_TS_TSONLY:
25368 				off = IPOPT_TS_TIMELEN;
25369 				break;
25370 			case IPOPT_TS_PRESPEC:
25371 			case IPOPT_TS_PRESPEC_RFC791:
25372 				/* Verify that the address matched */
25373 				off = opt[IPOPT_OFFSET] - 1;
25374 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25375 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25376 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25377 				    ipst);
25378 				if (ire == NULL) {
25379 					/* Not for us */
25380 					break;
25381 				}
25382 				ire_refrele(ire);
25383 				/* FALLTHRU */
25384 			case IPOPT_TS_TSANDADDR:
25385 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25386 				break;
25387 			default:
25388 				/*
25389 				 * ip_*put_options should have already
25390 				 * dropped this packet.
25391 				 */
25392 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25393 				    "unknown IT - bug in ip_wput_options?\n");
25394 				return;	/* Keep "lint" happy */
25395 			}
25396 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25397 				/* Increase overflow counter */
25398 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25399 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25400 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25401 				    (off << 4);
25402 				break;
25403 			}
25404 			off = opt[IPOPT_OFFSET] - 1;
25405 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25406 			case IPOPT_TS_PRESPEC:
25407 			case IPOPT_TS_PRESPEC_RFC791:
25408 			case IPOPT_TS_TSANDADDR:
25409 				dst = htonl(INADDR_LOOPBACK);
25410 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25411 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25412 				/* FALLTHRU */
25413 			case IPOPT_TS_TSONLY:
25414 				off = opt[IPOPT_OFFSET] - 1;
25415 				/* Compute # of milliseconds since midnight */
25416 				gethrestime(&now);
25417 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25418 				    now.tv_nsec / (NANOSEC / MILLISEC);
25419 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25420 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25421 				break;
25422 			}
25423 			break;
25424 		}
25425 	}
25426 }
25427 
25428 /*
25429  * Send out a multicast packet on interface ipif.
25430  * The sender does not have an conn.
25431  * Caller verifies that this isn't a PHYI_LOOPBACK.
25432  */
25433 void
25434 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25435 {
25436 	ipha_t	*ipha;
25437 	ire_t	*ire;
25438 	ipaddr_t	dst;
25439 	mblk_t		*first_mp;
25440 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25441 
25442 	/* igmp_sendpkt always allocates a ipsec_out_t */
25443 	ASSERT(mp->b_datap->db_type == M_CTL);
25444 	ASSERT(!ipif->ipif_isv6);
25445 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25446 
25447 	first_mp = mp;
25448 	mp = first_mp->b_cont;
25449 	ASSERT(mp->b_datap->db_type == M_DATA);
25450 	ipha = (ipha_t *)mp->b_rptr;
25451 
25452 	/*
25453 	 * Find an IRE which matches the destination and the outgoing
25454 	 * queue (i.e. the outgoing interface.)
25455 	 */
25456 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25457 		dst = ipif->ipif_pp_dst_addr;
25458 	else
25459 		dst = ipha->ipha_dst;
25460 	/*
25461 	 * The source address has already been initialized by the
25462 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25463 	 * be sufficient rather than MATCH_IRE_IPIF.
25464 	 *
25465 	 * This function is used for sending IGMP packets.  For IPMP,
25466 	 * we sidestep IGMP snooping issues by sending all multicast
25467 	 * traffic on a single interface in the IPMP group.
25468 	 */
25469 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25470 	    MATCH_IRE_ILL, ipst);
25471 	if (!ire) {
25472 		/*
25473 		 * Mark this packet to make it be delivered to
25474 		 * ip_wput_ire after the new ire has been
25475 		 * created.
25476 		 */
25477 		mp->b_prev = NULL;
25478 		mp->b_next = NULL;
25479 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25480 		    zoneid, &zero_info);
25481 		return;
25482 	}
25483 
25484 	/*
25485 	 * Honor the RTF_SETSRC flag; this is the only case
25486 	 * where we force this addr whatever the current src addr is,
25487 	 * because this address is set by igmp_sendpkt(), and
25488 	 * cannot be specified by any user.
25489 	 */
25490 	if (ire->ire_flags & RTF_SETSRC) {
25491 		ipha->ipha_src = ire->ire_src_addr;
25492 	}
25493 
25494 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25495 }
25496 
25497 /*
25498  * NOTE : This function does not ire_refrele the ire argument passed in.
25499  *
25500  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25501  * failure. The nce_fp_mp can vanish any time in the case of
25502  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25503  * the ire_lock to access the nce_fp_mp in this case.
25504  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25505  * prepending a fastpath message IPQoS processing must precede it, we also set
25506  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25507  * (IPQoS might have set the b_band for CoS marking).
25508  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25509  * must follow it so that IPQoS can mark the dl_priority field for CoS
25510  * marking, if needed.
25511  */
25512 static mblk_t *
25513 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25514     uint32_t ill_index, ipha_t **iphap)
25515 {
25516 	uint_t	hlen;
25517 	ipha_t *ipha;
25518 	mblk_t *mp1;
25519 	boolean_t qos_done = B_FALSE;
25520 	uchar_t	*ll_hdr;
25521 	ip_stack_t	*ipst = ire->ire_ipst;
25522 
25523 #define	rptr	((uchar_t *)ipha)
25524 
25525 	ipha = (ipha_t *)mp->b_rptr;
25526 	hlen = 0;
25527 	LOCK_IRE_FP_MP(ire);
25528 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25529 		ASSERT(DB_TYPE(mp1) == M_DATA);
25530 		/* Initiate IPPF processing */
25531 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25532 			UNLOCK_IRE_FP_MP(ire);
25533 			ip_process(proc, &mp, ill_index);
25534 			if (mp == NULL)
25535 				return (NULL);
25536 
25537 			ipha = (ipha_t *)mp->b_rptr;
25538 			LOCK_IRE_FP_MP(ire);
25539 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25540 				qos_done = B_TRUE;
25541 				goto no_fp_mp;
25542 			}
25543 			ASSERT(DB_TYPE(mp1) == M_DATA);
25544 		}
25545 		hlen = MBLKL(mp1);
25546 		/*
25547 		 * Check if we have enough room to prepend fastpath
25548 		 * header
25549 		 */
25550 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25551 			ll_hdr = rptr - hlen;
25552 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25553 			/*
25554 			 * Set the b_rptr to the start of the link layer
25555 			 * header
25556 			 */
25557 			mp->b_rptr = ll_hdr;
25558 			mp1 = mp;
25559 		} else {
25560 			mp1 = copyb(mp1);
25561 			if (mp1 == NULL)
25562 				goto unlock_err;
25563 			mp1->b_band = mp->b_band;
25564 			mp1->b_cont = mp;
25565 			/*
25566 			 * XXX disable ICK_VALID and compute checksum
25567 			 * here; can happen if nce_fp_mp changes and
25568 			 * it can't be copied now due to insufficient
25569 			 * space. (unlikely, fp mp can change, but it
25570 			 * does not increase in length)
25571 			 */
25572 		}
25573 		UNLOCK_IRE_FP_MP(ire);
25574 	} else {
25575 no_fp_mp:
25576 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25577 		if (mp1 == NULL) {
25578 unlock_err:
25579 			UNLOCK_IRE_FP_MP(ire);
25580 			freemsg(mp);
25581 			return (NULL);
25582 		}
25583 		UNLOCK_IRE_FP_MP(ire);
25584 		mp1->b_cont = mp;
25585 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25586 			ip_process(proc, &mp1, ill_index);
25587 			if (mp1 == NULL)
25588 				return (NULL);
25589 
25590 			if (mp1->b_cont == NULL)
25591 				ipha = NULL;
25592 			else
25593 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25594 		}
25595 	}
25596 
25597 	*iphap = ipha;
25598 	return (mp1);
25599 #undef rptr
25600 }
25601 
25602 /*
25603  * Finish the outbound IPsec processing for an IPv6 packet. This function
25604  * is called from ipsec_out_process() if the IPsec packet was processed
25605  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25606  * asynchronously.
25607  */
25608 void
25609 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25610     ire_t *ire_arg)
25611 {
25612 	in6_addr_t *v6dstp;
25613 	ire_t *ire;
25614 	mblk_t *mp;
25615 	ip6_t *ip6h1;
25616 	uint_t	ill_index;
25617 	ipsec_out_t *io;
25618 	boolean_t hwaccel;
25619 	uint32_t flags = IP6_NO_IPPOLICY;
25620 	int match_flags;
25621 	zoneid_t zoneid;
25622 	boolean_t ill_need_rele = B_FALSE;
25623 	boolean_t ire_need_rele = B_FALSE;
25624 	ip_stack_t	*ipst;
25625 
25626 	mp = ipsec_mp->b_cont;
25627 	ip6h1 = (ip6_t *)mp->b_rptr;
25628 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25629 	ASSERT(io->ipsec_out_ns != NULL);
25630 	ipst = io->ipsec_out_ns->netstack_ip;
25631 	ill_index = io->ipsec_out_ill_index;
25632 	if (io->ipsec_out_reachable) {
25633 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25634 	}
25635 	hwaccel = io->ipsec_out_accelerated;
25636 	zoneid = io->ipsec_out_zoneid;
25637 	ASSERT(zoneid != ALL_ZONES);
25638 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25639 	/* Multicast addresses should have non-zero ill_index. */
25640 	v6dstp = &ip6h->ip6_dst;
25641 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25642 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25643 
25644 	if (ill == NULL && ill_index != 0) {
25645 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25646 		/* Failure case frees things for us. */
25647 		if (ill == NULL)
25648 			return;
25649 
25650 		ill_need_rele = B_TRUE;
25651 	}
25652 	ASSERT(mp != NULL);
25653 
25654 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25655 		boolean_t unspec_src;
25656 		ipif_t	*ipif;
25657 
25658 		/*
25659 		 * Use the ill_index to get the right ill.
25660 		 */
25661 		unspec_src = io->ipsec_out_unspec_src;
25662 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25663 		if (ipif == NULL) {
25664 			if (ill_need_rele)
25665 				ill_refrele(ill);
25666 			freemsg(ipsec_mp);
25667 			return;
25668 		}
25669 
25670 		if (ire_arg != NULL) {
25671 			ire = ire_arg;
25672 		} else {
25673 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25674 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25675 			ire_need_rele = B_TRUE;
25676 		}
25677 		if (ire != NULL) {
25678 			ipif_refrele(ipif);
25679 			/*
25680 			 * XXX Do the multicast forwarding now, as the IPsec
25681 			 * processing has been done.
25682 			 */
25683 			goto send;
25684 		}
25685 
25686 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25687 		mp->b_prev = NULL;
25688 		mp->b_next = NULL;
25689 
25690 		/*
25691 		 * If the IPsec packet was processed asynchronously,
25692 		 * drop it now.
25693 		 */
25694 		if (q == NULL) {
25695 			if (ill_need_rele)
25696 				ill_refrele(ill);
25697 			freemsg(ipsec_mp);
25698 			return;
25699 		}
25700 
25701 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25702 		    unspec_src, zoneid);
25703 		ipif_refrele(ipif);
25704 	} else {
25705 		if (ire_arg != NULL) {
25706 			ire = ire_arg;
25707 		} else {
25708 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25709 			ire_need_rele = B_TRUE;
25710 		}
25711 		if (ire != NULL)
25712 			goto send;
25713 		/*
25714 		 * ire disappeared underneath.
25715 		 *
25716 		 * What we need to do here is the ip_newroute
25717 		 * logic to get the ire without doing the IPsec
25718 		 * processing. Follow the same old path. But this
25719 		 * time, ip_wput or ire_add_then_send will call us
25720 		 * directly as all the IPsec operations are done.
25721 		 */
25722 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25723 		mp->b_prev = NULL;
25724 		mp->b_next = NULL;
25725 
25726 		/*
25727 		 * If the IPsec packet was processed asynchronously,
25728 		 * drop it now.
25729 		 */
25730 		if (q == NULL) {
25731 			if (ill_need_rele)
25732 				ill_refrele(ill);
25733 			freemsg(ipsec_mp);
25734 			return;
25735 		}
25736 
25737 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25738 		    zoneid, ipst);
25739 	}
25740 	if (ill != NULL && ill_need_rele)
25741 		ill_refrele(ill);
25742 	return;
25743 send:
25744 	if (ill != NULL && ill_need_rele)
25745 		ill_refrele(ill);
25746 
25747 	/* Local delivery */
25748 	if (ire->ire_stq == NULL) {
25749 		ill_t	*out_ill;
25750 		ASSERT(q != NULL);
25751 
25752 		/* PFHooks: LOOPBACK_OUT */
25753 		out_ill = ire_to_ill(ire);
25754 
25755 		/*
25756 		 * DTrace this as ip:::send.  A blocked packet will fire the
25757 		 * send probe, but not the receive probe.
25758 		 */
25759 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25760 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25761 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25762 
25763 		DTRACE_PROBE4(ip6__loopback__out__start,
25764 		    ill_t *, NULL, ill_t *, out_ill,
25765 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25766 
25767 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25768 		    ipst->ips_ipv6firewall_loopback_out,
25769 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25770 
25771 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25772 
25773 		if (ipsec_mp != NULL) {
25774 			ip_wput_local_v6(RD(q), out_ill,
25775 			    ip6h, ipsec_mp, ire, 0, zoneid);
25776 		}
25777 		if (ire_need_rele)
25778 			ire_refrele(ire);
25779 		return;
25780 	}
25781 	/*
25782 	 * Everything is done. Send it out on the wire.
25783 	 * We force the insertion of a fragment header using the
25784 	 * IPH_FRAG_HDR flag in two cases:
25785 	 * - after reception of an ICMPv6 "packet too big" message
25786 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25787 	 * - for multirouted IPv6 packets, so that the receiver can
25788 	 *   discard duplicates according to their fragment identifier
25789 	 */
25790 	/* XXX fix flow control problems. */
25791 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25792 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25793 		if (hwaccel) {
25794 			/*
25795 			 * hardware acceleration does not handle these
25796 			 * "slow path" cases.
25797 			 */
25798 			/* IPsec KSTATS: should bump bean counter here. */
25799 			if (ire_need_rele)
25800 				ire_refrele(ire);
25801 			freemsg(ipsec_mp);
25802 			return;
25803 		}
25804 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25805 		    (mp->b_cont ? msgdsize(mp) :
25806 		    mp->b_wptr - (uchar_t *)ip6h)) {
25807 			/* IPsec KSTATS: should bump bean counter here. */
25808 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25809 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25810 			    msgdsize(mp)));
25811 			if (ire_need_rele)
25812 				ire_refrele(ire);
25813 			freemsg(ipsec_mp);
25814 			return;
25815 		}
25816 		ASSERT(mp->b_prev == NULL);
25817 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25818 		    ntohs(ip6h->ip6_plen) +
25819 		    IPV6_HDR_LEN, ire->ire_max_frag));
25820 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25821 		    ire->ire_max_frag);
25822 	} else {
25823 		UPDATE_OB_PKT_COUNT(ire);
25824 		ire->ire_last_used_time = lbolt;
25825 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25826 	}
25827 	if (ire_need_rele)
25828 		ire_refrele(ire);
25829 	freeb(ipsec_mp);
25830 }
25831 
25832 void
25833 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25834 {
25835 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25836 	da_ipsec_t *hada;	/* data attributes */
25837 	ill_t *ill = (ill_t *)q->q_ptr;
25838 
25839 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25840 
25841 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25842 		/* IPsec KSTATS: Bump lose counter here! */
25843 		freemsg(mp);
25844 		return;
25845 	}
25846 
25847 	/*
25848 	 * It's an IPsec packet that must be
25849 	 * accelerated by the Provider, and the
25850 	 * outbound ill is IPsec acceleration capable.
25851 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25852 	 * to the ill.
25853 	 * IPsec KSTATS: should bump packet counter here.
25854 	 */
25855 
25856 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25857 	if (hada_mp == NULL) {
25858 		/* IPsec KSTATS: should bump packet counter here. */
25859 		freemsg(mp);
25860 		return;
25861 	}
25862 
25863 	hada_mp->b_datap->db_type = M_CTL;
25864 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25865 	hada_mp->b_cont = mp;
25866 
25867 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25868 	bzero(hada, sizeof (da_ipsec_t));
25869 	hada->da_type = IPHADA_M_CTL;
25870 
25871 	putnext(q, hada_mp);
25872 }
25873 
25874 /*
25875  * Finish the outbound IPsec processing. This function is called from
25876  * ipsec_out_process() if the IPsec packet was processed
25877  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25878  * asynchronously.
25879  */
25880 void
25881 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25882     ire_t *ire_arg)
25883 {
25884 	uint32_t v_hlen_tos_len;
25885 	ipaddr_t	dst;
25886 	ipif_t	*ipif = NULL;
25887 	ire_t *ire;
25888 	ire_t *ire1 = NULL;
25889 	mblk_t *next_mp = NULL;
25890 	uint32_t max_frag;
25891 	boolean_t multirt_send = B_FALSE;
25892 	mblk_t *mp;
25893 	ipha_t *ipha1;
25894 	uint_t	ill_index;
25895 	ipsec_out_t *io;
25896 	int match_flags;
25897 	irb_t *irb = NULL;
25898 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25899 	zoneid_t zoneid;
25900 	ipxmit_state_t	pktxmit_state;
25901 	ip_stack_t	*ipst;
25902 
25903 #ifdef	_BIG_ENDIAN
25904 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25905 #else
25906 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25907 #endif
25908 
25909 	mp = ipsec_mp->b_cont;
25910 	ipha1 = (ipha_t *)mp->b_rptr;
25911 	ASSERT(mp != NULL);
25912 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25913 	dst = ipha->ipha_dst;
25914 
25915 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25916 	ill_index = io->ipsec_out_ill_index;
25917 	zoneid = io->ipsec_out_zoneid;
25918 	ASSERT(zoneid != ALL_ZONES);
25919 	ipst = io->ipsec_out_ns->netstack_ip;
25920 	ASSERT(io->ipsec_out_ns != NULL);
25921 
25922 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25923 	if (ill == NULL && ill_index != 0) {
25924 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25925 		/* Failure case frees things for us. */
25926 		if (ill == NULL)
25927 			return;
25928 
25929 		ill_need_rele = B_TRUE;
25930 	}
25931 
25932 	if (CLASSD(dst)) {
25933 		boolean_t conn_dontroute;
25934 		/*
25935 		 * Use the ill_index to get the right ipif.
25936 		 */
25937 		conn_dontroute = io->ipsec_out_dontroute;
25938 		if (ill_index == 0)
25939 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25940 		else
25941 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25942 		if (ipif == NULL) {
25943 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25944 			    " multicast\n"));
25945 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25946 			freemsg(ipsec_mp);
25947 			goto done;
25948 		}
25949 		/*
25950 		 * ipha_src has already been intialized with the
25951 		 * value of the ipif in ip_wput. All we need now is
25952 		 * an ire to send this downstream.
25953 		 */
25954 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25955 		    msg_getlabel(mp), match_flags, ipst);
25956 		if (ire != NULL) {
25957 			ill_t *ill1;
25958 			/*
25959 			 * Do the multicast forwarding now, as the IPsec
25960 			 * processing has been done.
25961 			 */
25962 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25963 			    (ill1 = ire_to_ill(ire))) {
25964 				if (ip_mforward(ill1, ipha, mp)) {
25965 					freemsg(ipsec_mp);
25966 					ip1dbg(("ip_wput_ipsec_out: mforward "
25967 					    "failed\n"));
25968 					ire_refrele(ire);
25969 					goto done;
25970 				}
25971 			}
25972 			goto send;
25973 		}
25974 
25975 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25976 		mp->b_prev = NULL;
25977 		mp->b_next = NULL;
25978 
25979 		/*
25980 		 * If the IPsec packet was processed asynchronously,
25981 		 * drop it now.
25982 		 */
25983 		if (q == NULL) {
25984 			freemsg(ipsec_mp);
25985 			goto done;
25986 		}
25987 
25988 		/*
25989 		 * We may be using a wrong ipif to create the ire.
25990 		 * But it is okay as the source address is assigned
25991 		 * for the packet already. Next outbound packet would
25992 		 * create the IRE with the right IPIF in ip_wput.
25993 		 *
25994 		 * Also handle RTF_MULTIRT routes.
25995 		 */
25996 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25997 		    zoneid, &zero_info);
25998 	} else {
25999 		if (ire_arg != NULL) {
26000 			ire = ire_arg;
26001 			ire_need_rele = B_FALSE;
26002 		} else {
26003 			ire = ire_cache_lookup(dst, zoneid,
26004 			    msg_getlabel(mp), ipst);
26005 		}
26006 		if (ire != NULL) {
26007 			goto send;
26008 		}
26009 
26010 		/*
26011 		 * ire disappeared underneath.
26012 		 *
26013 		 * What we need to do here is the ip_newroute
26014 		 * logic to get the ire without doing the IPsec
26015 		 * processing. Follow the same old path. But this
26016 		 * time, ip_wput or ire_add_then_put will call us
26017 		 * directly as all the IPsec operations are done.
26018 		 */
26019 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26020 		mp->b_prev = NULL;
26021 		mp->b_next = NULL;
26022 
26023 		/*
26024 		 * If the IPsec packet was processed asynchronously,
26025 		 * drop it now.
26026 		 */
26027 		if (q == NULL) {
26028 			freemsg(ipsec_mp);
26029 			goto done;
26030 		}
26031 
26032 		/*
26033 		 * Since we're going through ip_newroute() again, we
26034 		 * need to make sure we don't:
26035 		 *
26036 		 *	1.) Trigger the ASSERT() with the ipha_ident
26037 		 *	    overloading.
26038 		 *	2.) Redo transport-layer checksumming, since we've
26039 		 *	    already done all that to get this far.
26040 		 *
26041 		 * The easiest way not do either of the above is to set
26042 		 * the ipha_ident field to IP_HDR_INCLUDED.
26043 		 */
26044 		ipha->ipha_ident = IP_HDR_INCLUDED;
26045 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26046 		    zoneid, ipst);
26047 	}
26048 	goto done;
26049 send:
26050 	if (ire->ire_stq == NULL) {
26051 		ill_t	*out_ill;
26052 		/*
26053 		 * Loopbacks go through ip_wput_local except for one case.
26054 		 * We come here if we generate a icmp_frag_needed message
26055 		 * after IPsec processing is over. When this function calls
26056 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26057 		 * icmp_frag_needed. The message generated comes back here
26058 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26059 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26060 		 * source address as it is usually set in ip_wput_ire. As
26061 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26062 		 * and we end up here. We can't enter ip_wput_ire once the
26063 		 * IPsec processing is over and hence we need to do it here.
26064 		 */
26065 		ASSERT(q != NULL);
26066 		UPDATE_OB_PKT_COUNT(ire);
26067 		ire->ire_last_used_time = lbolt;
26068 		if (ipha->ipha_src == 0)
26069 			ipha->ipha_src = ire->ire_src_addr;
26070 
26071 		/* PFHooks: LOOPBACK_OUT */
26072 		out_ill = ire_to_ill(ire);
26073 
26074 		/*
26075 		 * DTrace this as ip:::send.  A blocked packet will fire the
26076 		 * send probe, but not the receive probe.
26077 		 */
26078 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26079 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26080 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26081 
26082 		DTRACE_PROBE4(ip4__loopback__out__start,
26083 		    ill_t *, NULL, ill_t *, out_ill,
26084 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26085 
26086 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26087 		    ipst->ips_ipv4firewall_loopback_out,
26088 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26089 
26090 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26091 
26092 		if (ipsec_mp != NULL)
26093 			ip_wput_local(RD(q), out_ill,
26094 			    ipha, ipsec_mp, ire, 0, zoneid);
26095 		if (ire_need_rele)
26096 			ire_refrele(ire);
26097 		goto done;
26098 	}
26099 
26100 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26101 		/*
26102 		 * We are through with IPsec processing.
26103 		 * Fragment this and send it on the wire.
26104 		 */
26105 		if (io->ipsec_out_accelerated) {
26106 			/*
26107 			 * The packet has been accelerated but must
26108 			 * be fragmented. This should not happen
26109 			 * since AH and ESP must not accelerate
26110 			 * packets that need fragmentation, however
26111 			 * the configuration could have changed
26112 			 * since the AH or ESP processing.
26113 			 * Drop packet.
26114 			 * IPsec KSTATS: bump bean counter here.
26115 			 */
26116 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26117 			    "fragmented accelerated packet!\n"));
26118 			freemsg(ipsec_mp);
26119 		} else {
26120 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26121 			    zoneid, ipst, NULL);
26122 		}
26123 		if (ire_need_rele)
26124 			ire_refrele(ire);
26125 		goto done;
26126 	}
26127 
26128 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26129 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26130 	    (void *)ire->ire_ipif, (void *)ipif));
26131 
26132 	/*
26133 	 * Multiroute the secured packet.
26134 	 */
26135 	if (ire->ire_flags & RTF_MULTIRT) {
26136 		ire_t *first_ire;
26137 		irb = ire->ire_bucket;
26138 		ASSERT(irb != NULL);
26139 		/*
26140 		 * This ire has been looked up as the one that
26141 		 * goes through the given ipif;
26142 		 * make sure we do not omit any other multiroute ire
26143 		 * that may be present in the bucket before this one.
26144 		 */
26145 		IRB_REFHOLD(irb);
26146 		for (first_ire = irb->irb_ire;
26147 		    first_ire != NULL;
26148 		    first_ire = first_ire->ire_next) {
26149 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26150 			    (first_ire->ire_addr == ire->ire_addr) &&
26151 			    !(first_ire->ire_marks &
26152 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26153 				break;
26154 		}
26155 
26156 		if ((first_ire != NULL) && (first_ire != ire)) {
26157 			/*
26158 			 * Don't change the ire if the packet must
26159 			 * be fragmented if sent via this new one.
26160 			 */
26161 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26162 				IRE_REFHOLD(first_ire);
26163 				if (ire_need_rele)
26164 					ire_refrele(ire);
26165 				else
26166 					ire_need_rele = B_TRUE;
26167 				ire = first_ire;
26168 			}
26169 		}
26170 		IRB_REFRELE(irb);
26171 
26172 		multirt_send = B_TRUE;
26173 		max_frag = ire->ire_max_frag;
26174 	}
26175 
26176 	/*
26177 	 * In most cases, the emission loop below is entered only once.
26178 	 * Only in the case where the ire holds the RTF_MULTIRT
26179 	 * flag, we loop to process all RTF_MULTIRT ires in the
26180 	 * bucket, and send the packet through all crossed
26181 	 * RTF_MULTIRT routes.
26182 	 */
26183 	do {
26184 		if (multirt_send) {
26185 			/*
26186 			 * ire1 holds here the next ire to process in the
26187 			 * bucket. If multirouting is expected,
26188 			 * any non-RTF_MULTIRT ire that has the
26189 			 * right destination address is ignored.
26190 			 */
26191 			ASSERT(irb != NULL);
26192 			IRB_REFHOLD(irb);
26193 			for (ire1 = ire->ire_next;
26194 			    ire1 != NULL;
26195 			    ire1 = ire1->ire_next) {
26196 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26197 					continue;
26198 				if (ire1->ire_addr != ire->ire_addr)
26199 					continue;
26200 				if (ire1->ire_marks &
26201 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26202 					continue;
26203 				/* No loopback here */
26204 				if (ire1->ire_stq == NULL)
26205 					continue;
26206 				/*
26207 				 * Ensure we do not exceed the MTU
26208 				 * of the next route.
26209 				 */
26210 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26211 					ip_multirt_bad_mtu(ire1, max_frag);
26212 					continue;
26213 				}
26214 
26215 				IRE_REFHOLD(ire1);
26216 				break;
26217 			}
26218 			IRB_REFRELE(irb);
26219 			if (ire1 != NULL) {
26220 				/*
26221 				 * We are in a multiple send case, need to
26222 				 * make a copy of the packet.
26223 				 */
26224 				next_mp = copymsg(ipsec_mp);
26225 				if (next_mp == NULL) {
26226 					ire_refrele(ire1);
26227 					ire1 = NULL;
26228 				}
26229 			}
26230 		}
26231 		/*
26232 		 * Everything is done. Send it out on the wire
26233 		 *
26234 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26235 		 * either send it on the wire or, in the case of
26236 		 * HW acceleration, call ipsec_hw_putnext.
26237 		 */
26238 		if (ire->ire_nce &&
26239 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26240 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26241 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26242 			/*
26243 			 * If ire's link-layer is unresolved (this
26244 			 * would only happen if the incomplete ire
26245 			 * was added to cachetable via forwarding path)
26246 			 * don't bother going to ip_xmit_v4. Just drop the
26247 			 * packet.
26248 			 * There is a slight risk here, in that, if we
26249 			 * have the forwarding path create an incomplete
26250 			 * IRE, then until the IRE is completed, any
26251 			 * transmitted IPsec packets will be dropped
26252 			 * instead of being queued waiting for resolution.
26253 			 *
26254 			 * But the likelihood of a forwarding packet and a wput
26255 			 * packet sending to the same dst at the same time
26256 			 * and there not yet be an ARP entry for it is small.
26257 			 * Furthermore, if this actually happens, it might
26258 			 * be likely that wput would generate multiple
26259 			 * packets (and forwarding would also have a train
26260 			 * of packets) for that destination. If this is
26261 			 * the case, some of them would have been dropped
26262 			 * anyway, since ARP only queues a few packets while
26263 			 * waiting for resolution
26264 			 *
26265 			 * NOTE: We should really call ip_xmit_v4,
26266 			 * and let it queue the packet and send the
26267 			 * ARP query and have ARP come back thus:
26268 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26269 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26270 			 * hw accel work. But it's too complex to get
26271 			 * the IPsec hw  acceleration approach to fit
26272 			 * well with ip_xmit_v4 doing ARP without
26273 			 * doing IPsec simplification. For now, we just
26274 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26275 			 * that we can continue with the send on the next
26276 			 * attempt.
26277 			 *
26278 			 * XXX THis should be revisited, when
26279 			 * the IPsec/IP interaction is cleaned up
26280 			 */
26281 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26282 			    " - dropping packet\n"));
26283 			freemsg(ipsec_mp);
26284 			/*
26285 			 * Call ip_xmit_v4() to trigger ARP query
26286 			 * in case the nce_state is ND_INITIAL
26287 			 */
26288 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26289 			goto drop_pkt;
26290 		}
26291 
26292 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26293 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26294 		    mblk_t *, ipsec_mp);
26295 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26296 		    ipst->ips_ipv4firewall_physical_out, NULL,
26297 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26298 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26299 		if (ipsec_mp == NULL)
26300 			goto drop_pkt;
26301 
26302 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26303 		pktxmit_state = ip_xmit_v4(mp, ire,
26304 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26305 
26306 		if ((pktxmit_state ==  SEND_FAILED) ||
26307 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26308 
26309 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26310 drop_pkt:
26311 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26312 			    ipIfStatsOutDiscards);
26313 			if (ire_need_rele)
26314 				ire_refrele(ire);
26315 			if (ire1 != NULL) {
26316 				ire_refrele(ire1);
26317 				freemsg(next_mp);
26318 			}
26319 			goto done;
26320 		}
26321 
26322 		freeb(ipsec_mp);
26323 		if (ire_need_rele)
26324 			ire_refrele(ire);
26325 
26326 		if (ire1 != NULL) {
26327 			ire = ire1;
26328 			ire_need_rele = B_TRUE;
26329 			ASSERT(next_mp);
26330 			ipsec_mp = next_mp;
26331 			mp = ipsec_mp->b_cont;
26332 			ire1 = NULL;
26333 			next_mp = NULL;
26334 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26335 		} else {
26336 			multirt_send = B_FALSE;
26337 		}
26338 	} while (multirt_send);
26339 done:
26340 	if (ill != NULL && ill_need_rele)
26341 		ill_refrele(ill);
26342 	if (ipif != NULL)
26343 		ipif_refrele(ipif);
26344 }
26345 
26346 /*
26347  * Get the ill corresponding to the specified ire, and compare its
26348  * capabilities with the protocol and algorithms specified by the
26349  * the SA obtained from ipsec_out. If they match, annotate the
26350  * ipsec_out structure to indicate that the packet needs acceleration.
26351  *
26352  *
26353  * A packet is eligible for outbound hardware acceleration if the
26354  * following conditions are satisfied:
26355  *
26356  * 1. the packet will not be fragmented
26357  * 2. the provider supports the algorithm
26358  * 3. there is no pending control message being exchanged
26359  * 4. snoop is not attached
26360  * 5. the destination address is not a broadcast or multicast address.
26361  *
26362  * Rationale:
26363  *	- Hardware drivers do not support fragmentation with
26364  *	  the current interface.
26365  *	- snoop, multicast, and broadcast may result in exposure of
26366  *	  a cleartext datagram.
26367  * We check all five of these conditions here.
26368  *
26369  * XXX would like to nuke "ire_t *" parameter here; problem is that
26370  * IRE is only way to figure out if a v4 address is a broadcast and
26371  * thus ineligible for acceleration...
26372  */
26373 static void
26374 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26375 {
26376 	ipsec_out_t *io;
26377 	mblk_t *data_mp;
26378 	uint_t plen, overhead;
26379 	ip_stack_t	*ipst;
26380 
26381 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26382 		return;
26383 
26384 	if (ill == NULL)
26385 		return;
26386 	ipst = ill->ill_ipst;
26387 	/*
26388 	 * Destination address is a broadcast or multicast.  Punt.
26389 	 */
26390 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26391 	    IRE_LOCAL)))
26392 		return;
26393 
26394 	data_mp = ipsec_mp->b_cont;
26395 
26396 	if (ill->ill_isv6) {
26397 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26398 
26399 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26400 			return;
26401 
26402 		plen = ip6h->ip6_plen;
26403 	} else {
26404 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26405 
26406 		if (CLASSD(ipha->ipha_dst))
26407 			return;
26408 
26409 		plen = ipha->ipha_length;
26410 	}
26411 	/*
26412 	 * Is there a pending DLPI control message being exchanged
26413 	 * between IP/IPsec and the DLS Provider? If there is, it
26414 	 * could be a SADB update, and the state of the DLS Provider
26415 	 * SADB might not be in sync with the SADB maintained by
26416 	 * IPsec. To avoid dropping packets or using the wrong keying
26417 	 * material, we do not accelerate this packet.
26418 	 */
26419 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26420 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26421 		    "ill_dlpi_pending! don't accelerate packet\n"));
26422 		return;
26423 	}
26424 
26425 	/*
26426 	 * Is the Provider in promiscous mode? If it does, we don't
26427 	 * accelerate the packet since it will bounce back up to the
26428 	 * listeners in the clear.
26429 	 */
26430 	if (ill->ill_promisc_on_phys) {
26431 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26432 		    "ill in promiscous mode, don't accelerate packet\n"));
26433 		return;
26434 	}
26435 
26436 	/*
26437 	 * Will the packet require fragmentation?
26438 	 */
26439 
26440 	/*
26441 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26442 	 * as is used elsewhere.
26443 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26444 	 *	+ 2-byte trailer
26445 	 */
26446 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26447 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26448 
26449 	if ((plen + overhead) > ill->ill_max_mtu)
26450 		return;
26451 
26452 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26453 
26454 	/*
26455 	 * Can the ill accelerate this IPsec protocol and algorithm
26456 	 * specified by the SA?
26457 	 */
26458 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26459 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26460 		return;
26461 	}
26462 
26463 	/*
26464 	 * Tell AH or ESP that the outbound ill is capable of
26465 	 * accelerating this packet.
26466 	 */
26467 	io->ipsec_out_is_capab_ill = B_TRUE;
26468 }
26469 
26470 /*
26471  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26472  *
26473  * If this function returns B_TRUE, the requested SA's have been filled
26474  * into the ipsec_out_*_sa pointers.
26475  *
26476  * If the function returns B_FALSE, the packet has been "consumed", most
26477  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26478  *
26479  * The SA references created by the protocol-specific "select"
26480  * function will be released when the ipsec_mp is freed, thanks to the
26481  * ipsec_out_free destructor -- see spd.c.
26482  */
26483 static boolean_t
26484 ipsec_out_select_sa(mblk_t *ipsec_mp)
26485 {
26486 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26487 	ipsec_out_t *io;
26488 	ipsec_policy_t *pp;
26489 	ipsec_action_t *ap;
26490 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26491 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26492 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26493 
26494 	if (!io->ipsec_out_secure) {
26495 		/*
26496 		 * We came here by mistake.
26497 		 * Don't bother with ipsec processing
26498 		 * We should "discourage" this path in the future.
26499 		 */
26500 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26501 		return (B_FALSE);
26502 	}
26503 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26504 	ASSERT((io->ipsec_out_policy != NULL) ||
26505 	    (io->ipsec_out_act != NULL));
26506 
26507 	ASSERT(io->ipsec_out_failed == B_FALSE);
26508 
26509 	/*
26510 	 * IPsec processing has started.
26511 	 */
26512 	io->ipsec_out_proc_begin = B_TRUE;
26513 	ap = io->ipsec_out_act;
26514 	if (ap == NULL) {
26515 		pp = io->ipsec_out_policy;
26516 		ASSERT(pp != NULL);
26517 		ap = pp->ipsp_act;
26518 		ASSERT(ap != NULL);
26519 	}
26520 
26521 	/*
26522 	 * We have an action.  now, let's select SA's.
26523 	 * (In the future, we can cache this in the conn_t..)
26524 	 */
26525 	if (ap->ipa_want_esp) {
26526 		if (io->ipsec_out_esp_sa == NULL) {
26527 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26528 			    IPPROTO_ESP);
26529 		}
26530 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26531 	}
26532 
26533 	if (ap->ipa_want_ah) {
26534 		if (io->ipsec_out_ah_sa == NULL) {
26535 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26536 			    IPPROTO_AH);
26537 		}
26538 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26539 		/*
26540 		 * The ESP and AH processing order needs to be preserved
26541 		 * when both protocols are required (ESP should be applied
26542 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26543 		 * when both ESP and AH are required, and an AH ACQUIRE
26544 		 * is needed.
26545 		 */
26546 		if (ap->ipa_want_esp && need_ah_acquire)
26547 			need_esp_acquire = B_TRUE;
26548 	}
26549 
26550 	/*
26551 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26552 	 * Release SAs that got referenced, but will not be used until we
26553 	 * acquire _all_ of the SAs we need.
26554 	 */
26555 	if (need_ah_acquire || need_esp_acquire) {
26556 		if (io->ipsec_out_ah_sa != NULL) {
26557 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26558 			io->ipsec_out_ah_sa = NULL;
26559 		}
26560 		if (io->ipsec_out_esp_sa != NULL) {
26561 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26562 			io->ipsec_out_esp_sa = NULL;
26563 		}
26564 
26565 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26566 		return (B_FALSE);
26567 	}
26568 
26569 	return (B_TRUE);
26570 }
26571 
26572 /*
26573  * Process an IPSEC_OUT message and see what you can
26574  * do with it.
26575  * IPQoS Notes:
26576  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26577  * IPsec.
26578  * XXX would like to nuke ire_t.
26579  * XXX ill_index better be "real"
26580  */
26581 void
26582 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26583 {
26584 	ipsec_out_t *io;
26585 	ipsec_policy_t *pp;
26586 	ipsec_action_t *ap;
26587 	ipha_t *ipha;
26588 	ip6_t *ip6h;
26589 	mblk_t *mp;
26590 	ill_t *ill;
26591 	zoneid_t zoneid;
26592 	ipsec_status_t ipsec_rc;
26593 	boolean_t ill_need_rele = B_FALSE;
26594 	ip_stack_t	*ipst;
26595 	ipsec_stack_t	*ipss;
26596 
26597 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26598 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26599 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26600 	ipst = io->ipsec_out_ns->netstack_ip;
26601 	mp = ipsec_mp->b_cont;
26602 
26603 	/*
26604 	 * Initiate IPPF processing. We do it here to account for packets
26605 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26606 	 * We can check for ipsec_out_proc_begin even for such packets, as
26607 	 * they will always be false (asserted below).
26608 	 */
26609 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26610 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26611 		    io->ipsec_out_ill_index : ill_index);
26612 		if (mp == NULL) {
26613 			ip2dbg(("ipsec_out_process: packet dropped "\
26614 			    "during IPPF processing\n"));
26615 			freeb(ipsec_mp);
26616 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26617 			return;
26618 		}
26619 	}
26620 
26621 	if (!io->ipsec_out_secure) {
26622 		/*
26623 		 * We came here by mistake.
26624 		 * Don't bother with ipsec processing
26625 		 * Should "discourage" this path in the future.
26626 		 */
26627 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26628 		goto done;
26629 	}
26630 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26631 	ASSERT((io->ipsec_out_policy != NULL) ||
26632 	    (io->ipsec_out_act != NULL));
26633 	ASSERT(io->ipsec_out_failed == B_FALSE);
26634 
26635 	ipss = ipst->ips_netstack->netstack_ipsec;
26636 	if (!ipsec_loaded(ipss)) {
26637 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26638 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26639 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26640 		} else {
26641 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26642 		}
26643 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26644 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26645 		    &ipss->ipsec_dropper);
26646 		return;
26647 	}
26648 
26649 	/*
26650 	 * IPsec processing has started.
26651 	 */
26652 	io->ipsec_out_proc_begin = B_TRUE;
26653 	ap = io->ipsec_out_act;
26654 	if (ap == NULL) {
26655 		pp = io->ipsec_out_policy;
26656 		ASSERT(pp != NULL);
26657 		ap = pp->ipsp_act;
26658 		ASSERT(ap != NULL);
26659 	}
26660 
26661 	/*
26662 	 * Save the outbound ill index. When the packet comes back
26663 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26664 	 * before sending it the accelerated packet.
26665 	 */
26666 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26667 		ill = ire_to_ill(ire);
26668 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26669 	}
26670 
26671 	/*
26672 	 * The order of processing is first insert a IP header if needed.
26673 	 * Then insert the ESP header and then the AH header.
26674 	 */
26675 	if ((io->ipsec_out_se_done == B_FALSE) &&
26676 	    (ap->ipa_want_se)) {
26677 		/*
26678 		 * First get the outer IP header before sending
26679 		 * it to ESP.
26680 		 */
26681 		ipha_t *oipha, *iipha;
26682 		mblk_t *outer_mp, *inner_mp;
26683 
26684 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26685 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26686 			    "ipsec_out_process: "
26687 			    "Self-Encapsulation failed: Out of memory\n");
26688 			freemsg(ipsec_mp);
26689 			if (ill != NULL) {
26690 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26691 			} else {
26692 				BUMP_MIB(&ipst->ips_ip_mib,
26693 				    ipIfStatsOutDiscards);
26694 			}
26695 			return;
26696 		}
26697 		inner_mp = ipsec_mp->b_cont;
26698 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26699 		oipha = (ipha_t *)outer_mp->b_rptr;
26700 		iipha = (ipha_t *)inner_mp->b_rptr;
26701 		*oipha = *iipha;
26702 		outer_mp->b_wptr += sizeof (ipha_t);
26703 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26704 		    sizeof (ipha_t));
26705 		oipha->ipha_protocol = IPPROTO_ENCAP;
26706 		oipha->ipha_version_and_hdr_length =
26707 		    IP_SIMPLE_HDR_VERSION;
26708 		oipha->ipha_hdr_checksum = 0;
26709 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26710 		outer_mp->b_cont = inner_mp;
26711 		ipsec_mp->b_cont = outer_mp;
26712 
26713 		io->ipsec_out_se_done = B_TRUE;
26714 		io->ipsec_out_tunnel = B_TRUE;
26715 	}
26716 
26717 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26718 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26719 	    !ipsec_out_select_sa(ipsec_mp))
26720 		return;
26721 
26722 	/*
26723 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26724 	 * to do the heavy lifting.
26725 	 */
26726 	zoneid = io->ipsec_out_zoneid;
26727 	ASSERT(zoneid != ALL_ZONES);
26728 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26729 		ASSERT(io->ipsec_out_esp_sa != NULL);
26730 		io->ipsec_out_esp_done = B_TRUE;
26731 		/*
26732 		 * Note that since hw accel can only apply one transform,
26733 		 * not two, we skip hw accel for ESP if we also have AH
26734 		 * This is an design limitation of the interface
26735 		 * which should be revisited.
26736 		 */
26737 		ASSERT(ire != NULL);
26738 		if (io->ipsec_out_ah_sa == NULL) {
26739 			ill = (ill_t *)ire->ire_stq->q_ptr;
26740 			ipsec_out_is_accelerated(ipsec_mp,
26741 			    io->ipsec_out_esp_sa, ill, ire);
26742 		}
26743 
26744 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26745 		switch (ipsec_rc) {
26746 		case IPSEC_STATUS_SUCCESS:
26747 			break;
26748 		case IPSEC_STATUS_FAILED:
26749 			if (ill != NULL) {
26750 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26751 			} else {
26752 				BUMP_MIB(&ipst->ips_ip_mib,
26753 				    ipIfStatsOutDiscards);
26754 			}
26755 			/* FALLTHRU */
26756 		case IPSEC_STATUS_PENDING:
26757 			return;
26758 		}
26759 	}
26760 
26761 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26762 		ASSERT(io->ipsec_out_ah_sa != NULL);
26763 		io->ipsec_out_ah_done = B_TRUE;
26764 		if (ire == NULL) {
26765 			int idx = io->ipsec_out_capab_ill_index;
26766 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26767 			    NULL, NULL, NULL, NULL, ipst);
26768 			ill_need_rele = B_TRUE;
26769 		} else {
26770 			ill = (ill_t *)ire->ire_stq->q_ptr;
26771 		}
26772 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26773 		    ire);
26774 
26775 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26776 		switch (ipsec_rc) {
26777 		case IPSEC_STATUS_SUCCESS:
26778 			break;
26779 		case IPSEC_STATUS_FAILED:
26780 			if (ill != NULL) {
26781 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26782 			} else {
26783 				BUMP_MIB(&ipst->ips_ip_mib,
26784 				    ipIfStatsOutDiscards);
26785 			}
26786 			/* FALLTHRU */
26787 		case IPSEC_STATUS_PENDING:
26788 			if (ill != NULL && ill_need_rele)
26789 				ill_refrele(ill);
26790 			return;
26791 		}
26792 	}
26793 	/*
26794 	 * We are done with IPsec processing. Send it over the wire.
26795 	 */
26796 done:
26797 	mp = ipsec_mp->b_cont;
26798 	ipha = (ipha_t *)mp->b_rptr;
26799 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26800 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26801 		    ire);
26802 	} else {
26803 		ip6h = (ip6_t *)ipha;
26804 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26805 		    ire);
26806 	}
26807 	if (ill != NULL && ill_need_rele)
26808 		ill_refrele(ill);
26809 }
26810 
26811 /* ARGSUSED */
26812 void
26813 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26814 {
26815 	opt_restart_t	*or;
26816 	int	err;
26817 	conn_t	*connp;
26818 	cred_t	*cr;
26819 
26820 	ASSERT(CONN_Q(q));
26821 	connp = Q_TO_CONN(q);
26822 
26823 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26824 	or = (opt_restart_t *)first_mp->b_rptr;
26825 	/*
26826 	 * We checked for a db_credp the first time svr4_optcom_req
26827 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26828 	 */
26829 	cr = msg_getcred(first_mp, NULL);
26830 	ASSERT(cr != NULL);
26831 
26832 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26833 		err = svr4_optcom_req(q, first_mp, cr,
26834 		    &ip_opt_obj, B_FALSE);
26835 	} else {
26836 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26837 		err = tpi_optcom_req(q, first_mp, cr,
26838 		    &ip_opt_obj, B_FALSE);
26839 	}
26840 	if (err != EINPROGRESS) {
26841 		/* operation is done */
26842 		CONN_OPER_PENDING_DONE(connp);
26843 	}
26844 }
26845 
26846 /*
26847  * ioctls that go through a down/up sequence may need to wait for the down
26848  * to complete. This involves waiting for the ire and ipif refcnts to go down
26849  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26850  */
26851 /* ARGSUSED */
26852 void
26853 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26854 {
26855 	struct iocblk *iocp;
26856 	mblk_t *mp1;
26857 	ip_ioctl_cmd_t *ipip;
26858 	int err;
26859 	sin_t	*sin;
26860 	struct lifreq *lifr;
26861 	struct ifreq *ifr;
26862 
26863 	iocp = (struct iocblk *)mp->b_rptr;
26864 	ASSERT(ipsq != NULL);
26865 	/* Existence of mp1 verified in ip_wput_nondata */
26866 	mp1 = mp->b_cont->b_cont;
26867 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26868 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26869 		/*
26870 		 * Special case where ipx_current_ipif is not set:
26871 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26872 		 * We are here as were not able to complete the operation in
26873 		 * ipif_set_values because we could not become exclusive on
26874 		 * the new ipsq.
26875 		 */
26876 		ill_t *ill = q->q_ptr;
26877 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26878 	}
26879 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26880 
26881 	if (ipip->ipi_cmd_type == IF_CMD) {
26882 		/* This a old style SIOC[GS]IF* command */
26883 		ifr = (struct ifreq *)mp1->b_rptr;
26884 		sin = (sin_t *)&ifr->ifr_addr;
26885 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26886 		/* This a new style SIOC[GS]LIF* command */
26887 		lifr = (struct lifreq *)mp1->b_rptr;
26888 		sin = (sin_t *)&lifr->lifr_addr;
26889 	} else {
26890 		sin = NULL;
26891 	}
26892 
26893 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26894 	    q, mp, ipip, mp1->b_rptr);
26895 
26896 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26897 }
26898 
26899 /*
26900  * ioctl processing
26901  *
26902  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26903  * the ioctl command in the ioctl tables, determines the copyin data size
26904  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26905  *
26906  * ioctl processing then continues when the M_IOCDATA makes its way down to
26907  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26908  * associated 'conn' is refheld till the end of the ioctl and the general
26909  * ioctl processing function ip_process_ioctl() is called to extract the
26910  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26911  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26912  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26913  * is used to extract the ioctl's arguments.
26914  *
26915  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26916  * so goes thru the serialization primitive ipsq_try_enter. Then the
26917  * appropriate function to handle the ioctl is called based on the entry in
26918  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26919  * which also refreleases the 'conn' that was refheld at the start of the
26920  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26921  *
26922  * Many exclusive ioctls go thru an internal down up sequence as part of
26923  * the operation. For example an attempt to change the IP address of an
26924  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26925  * does all the cleanup such as deleting all ires that use this address.
26926  * Then we need to wait till all references to the interface go away.
26927  */
26928 void
26929 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26930 {
26931 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26932 	ip_ioctl_cmd_t *ipip = arg;
26933 	ip_extract_func_t *extract_funcp;
26934 	cmd_info_t ci;
26935 	int err;
26936 	boolean_t entered_ipsq = B_FALSE;
26937 
26938 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26939 
26940 	if (ipip == NULL)
26941 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26942 
26943 	/*
26944 	 * SIOCLIFADDIF needs to go thru a special path since the
26945 	 * ill may not exist yet. This happens in the case of lo0
26946 	 * which is created using this ioctl.
26947 	 */
26948 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26949 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26950 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26951 		return;
26952 	}
26953 
26954 	ci.ci_ipif = NULL;
26955 	if (ipip->ipi_cmd_type == MISC_CMD) {
26956 		/*
26957 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26958 		 */
26959 		if (ipip->ipi_cmd == IF_UNITSEL) {
26960 			/* ioctl comes down the ill */
26961 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26962 			ipif_refhold(ci.ci_ipif);
26963 		}
26964 		err = 0;
26965 		ci.ci_sin = NULL;
26966 		ci.ci_sin6 = NULL;
26967 		ci.ci_lifr = NULL;
26968 	} else {
26969 		switch (ipip->ipi_cmd_type) {
26970 		case IF_CMD:
26971 		case LIF_CMD:
26972 			extract_funcp = ip_extract_lifreq;
26973 			break;
26974 
26975 		case ARP_CMD:
26976 		case XARP_CMD:
26977 			extract_funcp = ip_extract_arpreq;
26978 			break;
26979 
26980 		case TUN_CMD:
26981 			extract_funcp = ip_extract_tunreq;
26982 			break;
26983 
26984 		case MSFILT_CMD:
26985 			extract_funcp = ip_extract_msfilter;
26986 			break;
26987 
26988 		default:
26989 			ASSERT(0);
26990 		}
26991 
26992 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26993 		if (err != 0) {
26994 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26995 			return;
26996 		}
26997 
26998 		/*
26999 		 * All of the extraction functions return a refheld ipif.
27000 		 */
27001 		ASSERT(ci.ci_ipif != NULL);
27002 	}
27003 
27004 	if (!(ipip->ipi_flags & IPI_WR)) {
27005 		/*
27006 		 * A return value of EINPROGRESS means the ioctl is
27007 		 * either queued and waiting for some reason or has
27008 		 * already completed.
27009 		 */
27010 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27011 		    ci.ci_lifr);
27012 		if (ci.ci_ipif != NULL)
27013 			ipif_refrele(ci.ci_ipif);
27014 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27015 		return;
27016 	}
27017 
27018 	ASSERT(ci.ci_ipif != NULL);
27019 
27020 	/*
27021 	 * If ipsq is non-NULL, we are already being called exclusively.
27022 	 */
27023 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27024 	if (ipsq == NULL) {
27025 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27026 		    NEW_OP, B_TRUE);
27027 		if (ipsq == NULL) {
27028 			ipif_refrele(ci.ci_ipif);
27029 			return;
27030 		}
27031 		entered_ipsq = B_TRUE;
27032 	}
27033 
27034 	/*
27035 	 * Release the ipif so that ipif_down and friends that wait for
27036 	 * references to go away are not misled about the current ipif_refcnt
27037 	 * values. We are writer so we can access the ipif even after releasing
27038 	 * the ipif.
27039 	 */
27040 	ipif_refrele(ci.ci_ipif);
27041 
27042 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27043 
27044 	/*
27045 	 * A return value of EINPROGRESS means the ioctl is
27046 	 * either queued and waiting for some reason or has
27047 	 * already completed.
27048 	 */
27049 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27050 
27051 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27052 
27053 	if (entered_ipsq)
27054 		ipsq_exit(ipsq);
27055 }
27056 
27057 /*
27058  * Complete the ioctl. Typically ioctls use the mi package and need to
27059  * do mi_copyout/mi_copy_done.
27060  */
27061 void
27062 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27063 {
27064 	conn_t	*connp = NULL;
27065 
27066 	if (err == EINPROGRESS)
27067 		return;
27068 
27069 	if (CONN_Q(q)) {
27070 		connp = Q_TO_CONN(q);
27071 		ASSERT(connp->conn_ref >= 2);
27072 	}
27073 
27074 	switch (mode) {
27075 	case COPYOUT:
27076 		if (err == 0)
27077 			mi_copyout(q, mp);
27078 		else
27079 			mi_copy_done(q, mp, err);
27080 		break;
27081 
27082 	case NO_COPYOUT:
27083 		mi_copy_done(q, mp, err);
27084 		break;
27085 
27086 	default:
27087 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27088 		break;
27089 	}
27090 
27091 	/*
27092 	 * The refhold placed at the start of the ioctl is released here.
27093 	 */
27094 	if (connp != NULL)
27095 		CONN_OPER_PENDING_DONE(connp);
27096 
27097 	if (ipsq != NULL)
27098 		ipsq_current_finish(ipsq);
27099 }
27100 
27101 /* Called from ip_wput for all non data messages */
27102 /* ARGSUSED */
27103 void
27104 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27105 {
27106 	mblk_t		*mp1;
27107 	ire_t		*ire, *fake_ire;
27108 	ill_t		*ill;
27109 	struct iocblk	*iocp;
27110 	ip_ioctl_cmd_t	*ipip;
27111 	cred_t		*cr;
27112 	conn_t		*connp;
27113 	int		err;
27114 	nce_t		*nce;
27115 	ipif_t		*ipif;
27116 	ip_stack_t	*ipst;
27117 	char		*proto_str;
27118 
27119 	if (CONN_Q(q)) {
27120 		connp = Q_TO_CONN(q);
27121 		ipst = connp->conn_netstack->netstack_ip;
27122 	} else {
27123 		connp = NULL;
27124 		ipst = ILLQ_TO_IPST(q);
27125 	}
27126 
27127 	switch (DB_TYPE(mp)) {
27128 	case M_IOCTL:
27129 		/*
27130 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27131 		 * will arrange to copy in associated control structures.
27132 		 */
27133 		ip_sioctl_copyin_setup(q, mp);
27134 		return;
27135 	case M_IOCDATA:
27136 		/*
27137 		 * Ensure that this is associated with one of our trans-
27138 		 * parent ioctls.  If it's not ours, discard it if we're
27139 		 * running as a driver, or pass it on if we're a module.
27140 		 */
27141 		iocp = (struct iocblk *)mp->b_rptr;
27142 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27143 		if (ipip == NULL) {
27144 			if (q->q_next == NULL) {
27145 				goto nak;
27146 			} else {
27147 				putnext(q, mp);
27148 			}
27149 			return;
27150 		}
27151 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27152 			/*
27153 			 * the ioctl is one we recognise, but is not
27154 			 * consumed by IP as a module, pass M_IOCDATA
27155 			 * for processing downstream, but only for
27156 			 * common Streams ioctls.
27157 			 */
27158 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27159 				putnext(q, mp);
27160 				return;
27161 			} else {
27162 				goto nak;
27163 			}
27164 		}
27165 
27166 		/* IOCTL continuation following copyin or copyout. */
27167 		if (mi_copy_state(q, mp, NULL) == -1) {
27168 			/*
27169 			 * The copy operation failed.  mi_copy_state already
27170 			 * cleaned up, so we're out of here.
27171 			 */
27172 			return;
27173 		}
27174 		/*
27175 		 * If we just completed a copy in, we become writer and
27176 		 * continue processing in ip_sioctl_copyin_done.  If it
27177 		 * was a copy out, we call mi_copyout again.  If there is
27178 		 * nothing more to copy out, it will complete the IOCTL.
27179 		 */
27180 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27181 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27182 				mi_copy_done(q, mp, EPROTO);
27183 				return;
27184 			}
27185 			/*
27186 			 * Check for cases that need more copying.  A return
27187 			 * value of 0 means a second copyin has been started,
27188 			 * so we return; a return value of 1 means no more
27189 			 * copying is needed, so we continue.
27190 			 */
27191 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27192 			    MI_COPY_COUNT(mp) == 1) {
27193 				if (ip_copyin_msfilter(q, mp) == 0)
27194 					return;
27195 			}
27196 			/*
27197 			 * Refhold the conn, till the ioctl completes. This is
27198 			 * needed in case the ioctl ends up in the pending mp
27199 			 * list. Every mp in the ill_pending_mp list and
27200 			 * the ipx_pending_mp must have a refhold on the conn
27201 			 * to resume processing. The refhold is released when
27202 			 * the ioctl completes. (normally or abnormally)
27203 			 * In all cases ip_ioctl_finish is called to finish
27204 			 * the ioctl.
27205 			 */
27206 			if (connp != NULL) {
27207 				/* This is not a reentry */
27208 				ASSERT(ipsq == NULL);
27209 				CONN_INC_REF(connp);
27210 			} else {
27211 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27212 					mi_copy_done(q, mp, EINVAL);
27213 					return;
27214 				}
27215 			}
27216 
27217 			ip_process_ioctl(ipsq, q, mp, ipip);
27218 
27219 		} else {
27220 			mi_copyout(q, mp);
27221 		}
27222 		return;
27223 nak:
27224 		iocp->ioc_error = EINVAL;
27225 		mp->b_datap->db_type = M_IOCNAK;
27226 		iocp->ioc_count = 0;
27227 		qreply(q, mp);
27228 		return;
27229 
27230 	case M_IOCNAK:
27231 		/*
27232 		 * The only way we could get here is if a resolver didn't like
27233 		 * an IOCTL we sent it.	 This shouldn't happen.
27234 		 */
27235 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27236 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27237 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27238 		freemsg(mp);
27239 		return;
27240 	case M_IOCACK:
27241 		/* /dev/ip shouldn't see this */
27242 		if (CONN_Q(q))
27243 			goto nak;
27244 
27245 		/*
27246 		 * Finish socket ioctls passed through to ARP.  We use the
27247 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27248 		 * we need to become writer before calling ip_sioctl_iocack().
27249 		 * Note that qwriter_ip() will release the refhold, and that a
27250 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27251 		 * ill stream.
27252 		 */
27253 		iocp = (struct iocblk *)mp->b_rptr;
27254 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27255 			ip_sioctl_iocack(NULL, q, mp, NULL);
27256 			return;
27257 		}
27258 
27259 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27260 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27261 		ill = q->q_ptr;
27262 		ill_refhold(ill);
27263 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27264 		return;
27265 	case M_FLUSH:
27266 		if (*mp->b_rptr & FLUSHW)
27267 			flushq(q, FLUSHALL);
27268 		if (q->q_next) {
27269 			putnext(q, mp);
27270 			return;
27271 		}
27272 		if (*mp->b_rptr & FLUSHR) {
27273 			*mp->b_rptr &= ~FLUSHW;
27274 			qreply(q, mp);
27275 			return;
27276 		}
27277 		freemsg(mp);
27278 		return;
27279 	case IRE_DB_REQ_TYPE:
27280 		if (connp == NULL) {
27281 			proto_str = "IRE_DB_REQ_TYPE";
27282 			goto protonak;
27283 		}
27284 		/* An Upper Level Protocol wants a copy of an IRE. */
27285 		ip_ire_req(q, mp);
27286 		return;
27287 	case M_CTL:
27288 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27289 			break;
27290 
27291 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27292 		    TUN_HELLO) {
27293 			ASSERT(connp != NULL);
27294 			connp->conn_flags |= IPCL_IPTUN;
27295 			freeb(mp);
27296 			return;
27297 		}
27298 
27299 		/* M_CTL messages are used by ARP to tell us things. */
27300 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27301 			break;
27302 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27303 		case AR_ENTRY_SQUERY:
27304 			putnext(q, mp);
27305 			return;
27306 		case AR_CLIENT_NOTIFY:
27307 			ip_arp_news(q, mp);
27308 			return;
27309 		case AR_DLPIOP_DONE:
27310 			ASSERT(q->q_next != NULL);
27311 			ill = (ill_t *)q->q_ptr;
27312 			/* qwriter_ip releases the refhold */
27313 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27314 			ill_refhold(ill);
27315 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27316 			return;
27317 		case AR_ARP_CLOSING:
27318 			/*
27319 			 * ARP (above us) is closing. If no ARP bringup is
27320 			 * currently pending, ack the message so that ARP
27321 			 * can complete its close. Also mark ill_arp_closing
27322 			 * so that new ARP bringups will fail. If any
27323 			 * ARP bringup is currently in progress, we will
27324 			 * ack this when the current ARP bringup completes.
27325 			 */
27326 			ASSERT(q->q_next != NULL);
27327 			ill = (ill_t *)q->q_ptr;
27328 			mutex_enter(&ill->ill_lock);
27329 			ill->ill_arp_closing = 1;
27330 			if (!ill->ill_arp_bringup_pending) {
27331 				mutex_exit(&ill->ill_lock);
27332 				qreply(q, mp);
27333 			} else {
27334 				mutex_exit(&ill->ill_lock);
27335 				freemsg(mp);
27336 			}
27337 			return;
27338 		case AR_ARP_EXTEND:
27339 			/*
27340 			 * The ARP module above us is capable of duplicate
27341 			 * address detection.  Old ATM drivers will not send
27342 			 * this message.
27343 			 */
27344 			ASSERT(q->q_next != NULL);
27345 			ill = (ill_t *)q->q_ptr;
27346 			ill->ill_arp_extend = B_TRUE;
27347 			freemsg(mp);
27348 			return;
27349 		default:
27350 			break;
27351 		}
27352 		break;
27353 	case M_PROTO:
27354 	case M_PCPROTO:
27355 		/*
27356 		 * The only PROTO messages we expect are copies of option
27357 		 * negotiation acknowledgements, AH and ESP bind requests
27358 		 * are also expected.
27359 		 */
27360 		switch (((union T_primitives *)mp->b_rptr)->type) {
27361 		case O_T_BIND_REQ:
27362 		case T_BIND_REQ: {
27363 			/* Request can get queued in bind */
27364 			if (connp == NULL) {
27365 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27366 				goto protonak;
27367 			}
27368 			/*
27369 			 * The transports except SCTP call ip_bind_{v4,v6}()
27370 			 * directly instead of a a putnext. SCTP doesn't
27371 			 * generate any T_BIND_REQ since it has its own
27372 			 * fanout data structures. However, ESP and AH
27373 			 * come in for regular binds; all other cases are
27374 			 * bind retries.
27375 			 */
27376 			ASSERT(!IPCL_IS_SCTP(connp));
27377 
27378 			/* Don't increment refcnt if this is a re-entry */
27379 			if (ipsq == NULL)
27380 				CONN_INC_REF(connp);
27381 
27382 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27383 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27384 			ASSERT(mp != NULL);
27385 
27386 			ASSERT(!IPCL_IS_TCP(connp));
27387 			ASSERT(!IPCL_IS_UDP(connp));
27388 			ASSERT(!IPCL_IS_RAWIP(connp));
27389 
27390 			/* The case of AH and ESP */
27391 			qreply(q, mp);
27392 			CONN_OPER_PENDING_DONE(connp);
27393 			return;
27394 		}
27395 		case T_SVR4_OPTMGMT_REQ:
27396 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27397 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27398 
27399 			if (connp == NULL) {
27400 				proto_str = "T_SVR4_OPTMGMT_REQ";
27401 				goto protonak;
27402 			}
27403 
27404 			/*
27405 			 * All Solaris components should pass a db_credp
27406 			 * for this TPI message, hence we ASSERT.
27407 			 * But in case there is some other M_PROTO that looks
27408 			 * like a TPI message sent by some other kernel
27409 			 * component, we check and return an error.
27410 			 */
27411 			cr = msg_getcred(mp, NULL);
27412 			ASSERT(cr != NULL);
27413 			if (cr == NULL) {
27414 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27415 				if (mp != NULL)
27416 					qreply(q, mp);
27417 				return;
27418 			}
27419 
27420 			if (!snmpcom_req(q, mp, ip_snmp_set,
27421 			    ip_snmp_get, cr)) {
27422 				/*
27423 				 * Call svr4_optcom_req so that it can
27424 				 * generate the ack. We don't come here
27425 				 * if this operation is being restarted.
27426 				 * ip_restart_optmgmt will drop the conn ref.
27427 				 * In the case of ipsec option after the ipsec
27428 				 * load is complete conn_restart_ipsec_waiter
27429 				 * drops the conn ref.
27430 				 */
27431 				ASSERT(ipsq == NULL);
27432 				CONN_INC_REF(connp);
27433 				if (ip_check_for_ipsec_opt(q, mp))
27434 					return;
27435 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27436 				    B_FALSE);
27437 				if (err != EINPROGRESS) {
27438 					/* Operation is done */
27439 					CONN_OPER_PENDING_DONE(connp);
27440 				}
27441 			}
27442 			return;
27443 		case T_OPTMGMT_REQ:
27444 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27445 			/*
27446 			 * Note: No snmpcom_req support through new
27447 			 * T_OPTMGMT_REQ.
27448 			 * Call tpi_optcom_req so that it can
27449 			 * generate the ack.
27450 			 */
27451 			if (connp == NULL) {
27452 				proto_str = "T_OPTMGMT_REQ";
27453 				goto protonak;
27454 			}
27455 
27456 			/*
27457 			 * All Solaris components should pass a db_credp
27458 			 * for this TPI message, hence we ASSERT.
27459 			 * But in case there is some other M_PROTO that looks
27460 			 * like a TPI message sent by some other kernel
27461 			 * component, we check and return an error.
27462 			 */
27463 			cr = msg_getcred(mp, NULL);
27464 			ASSERT(cr != NULL);
27465 			if (cr == NULL) {
27466 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27467 				if (mp != NULL)
27468 					qreply(q, mp);
27469 				return;
27470 			}
27471 			ASSERT(ipsq == NULL);
27472 			/*
27473 			 * We don't come here for restart. ip_restart_optmgmt
27474 			 * will drop the conn ref. In the case of ipsec option
27475 			 * after the ipsec load is complete
27476 			 * conn_restart_ipsec_waiter drops the conn ref.
27477 			 */
27478 			CONN_INC_REF(connp);
27479 			if (ip_check_for_ipsec_opt(q, mp))
27480 				return;
27481 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27482 			if (err != EINPROGRESS) {
27483 				/* Operation is done */
27484 				CONN_OPER_PENDING_DONE(connp);
27485 			}
27486 			return;
27487 		case T_UNBIND_REQ:
27488 			if (connp == NULL) {
27489 				proto_str = "T_UNBIND_REQ";
27490 				goto protonak;
27491 			}
27492 			ip_unbind(Q_TO_CONN(q));
27493 			mp = mi_tpi_ok_ack_alloc(mp);
27494 			qreply(q, mp);
27495 			return;
27496 		default:
27497 			/*
27498 			 * Have to drop any DLPI messages coming down from
27499 			 * arp (such as an info_req which would cause ip
27500 			 * to receive an extra info_ack if it was passed
27501 			 * through.
27502 			 */
27503 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27504 			    (int)*(uint_t *)mp->b_rptr));
27505 			freemsg(mp);
27506 			return;
27507 		}
27508 		/* NOTREACHED */
27509 	case IRE_DB_TYPE: {
27510 		nce_t		*nce;
27511 		ill_t		*ill;
27512 		in6_addr_t	gw_addr_v6;
27513 
27514 		/*
27515 		 * This is a response back from a resolver.  It
27516 		 * consists of a message chain containing:
27517 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27518 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27519 		 * The LL_HDR_MBLK is the DLPI header to use to get
27520 		 * the attached packet, and subsequent ones for the
27521 		 * same destination, transmitted.
27522 		 */
27523 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27524 			break;
27525 		/*
27526 		 * First, check to make sure the resolution succeeded.
27527 		 * If it failed, the second mblk will be empty.
27528 		 * If it is, free the chain, dropping the packet.
27529 		 * (We must ire_delete the ire; that frees the ire mblk)
27530 		 * We're doing this now to support PVCs for ATM; it's
27531 		 * a partial xresolv implementation. When we fully implement
27532 		 * xresolv interfaces, instead of freeing everything here
27533 		 * we'll initiate neighbor discovery.
27534 		 *
27535 		 * For v4 (ARP and other external resolvers) the resolver
27536 		 * frees the message, so no check is needed. This check
27537 		 * is required, though, for a full xresolve implementation.
27538 		 * Including this code here now both shows how external
27539 		 * resolvers can NACK a resolution request using an
27540 		 * existing design that has no specific provisions for NACKs,
27541 		 * and also takes into account that the current non-ARP
27542 		 * external resolver has been coded to use this method of
27543 		 * NACKing for all IPv6 (xresolv) cases,
27544 		 * whether our xresolv implementation is complete or not.
27545 		 *
27546 		 */
27547 		ire = (ire_t *)mp->b_rptr;
27548 		ill = ire_to_ill(ire);
27549 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27550 		if (mp1->b_rptr == mp1->b_wptr) {
27551 			if (ire->ire_ipversion == IPV6_VERSION) {
27552 				/*
27553 				 * XRESOLV interface.
27554 				 */
27555 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27556 				mutex_enter(&ire->ire_lock);
27557 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27558 				mutex_exit(&ire->ire_lock);
27559 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27560 					nce = ndp_lookup_v6(ill, B_FALSE,
27561 					    &ire->ire_addr_v6, B_FALSE);
27562 				} else {
27563 					nce = ndp_lookup_v6(ill, B_FALSE,
27564 					    &gw_addr_v6, B_FALSE);
27565 				}
27566 				if (nce != NULL) {
27567 					nce_resolv_failed(nce);
27568 					ndp_delete(nce);
27569 					NCE_REFRELE(nce);
27570 				}
27571 			}
27572 			mp->b_cont = NULL;
27573 			freemsg(mp1);		/* frees the pkt as well */
27574 			ASSERT(ire->ire_nce == NULL);
27575 			ire_delete((ire_t *)mp->b_rptr);
27576 			return;
27577 		}
27578 
27579 		/*
27580 		 * Split them into IRE_MBLK and pkt and feed it into
27581 		 * ire_add_then_send. Then in ire_add_then_send
27582 		 * the IRE will be added, and then the packet will be
27583 		 * run back through ip_wput. This time it will make
27584 		 * it to the wire.
27585 		 */
27586 		mp->b_cont = NULL;
27587 		mp = mp1->b_cont;		/* now, mp points to pkt */
27588 		mp1->b_cont = NULL;
27589 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27590 		if (ire->ire_ipversion == IPV6_VERSION) {
27591 			/*
27592 			 * XRESOLV interface. Find the nce and put a copy
27593 			 * of the dl_unitdata_req in nce_res_mp
27594 			 */
27595 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27596 			mutex_enter(&ire->ire_lock);
27597 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27598 			mutex_exit(&ire->ire_lock);
27599 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27600 				nce = ndp_lookup_v6(ill, B_FALSE,
27601 				    &ire->ire_addr_v6, B_FALSE);
27602 			} else {
27603 				nce = ndp_lookup_v6(ill, B_FALSE,
27604 				    &gw_addr_v6, B_FALSE);
27605 			}
27606 			if (nce != NULL) {
27607 				/*
27608 				 * We have to protect nce_res_mp here
27609 				 * from being accessed by other threads
27610 				 * while we change the mblk pointer.
27611 				 * Other functions will also lock the nce when
27612 				 * accessing nce_res_mp.
27613 				 *
27614 				 * The reason we change the mblk pointer
27615 				 * here rather than copying the resolved address
27616 				 * into the template is that, unlike with
27617 				 * ethernet, we have no guarantee that the
27618 				 * resolved address length will be
27619 				 * smaller than or equal to the lla length
27620 				 * with which the template was allocated,
27621 				 * (for ethernet, they're equal)
27622 				 * so we have to use the actual resolved
27623 				 * address mblk - which holds the real
27624 				 * dl_unitdata_req with the resolved address.
27625 				 *
27626 				 * Doing this is the same behavior as was
27627 				 * previously used in the v4 ARP case.
27628 				 */
27629 				mutex_enter(&nce->nce_lock);
27630 				if (nce->nce_res_mp != NULL)
27631 					freemsg(nce->nce_res_mp);
27632 				nce->nce_res_mp = mp1;
27633 				mutex_exit(&nce->nce_lock);
27634 				/*
27635 				 * We do a fastpath probe here because
27636 				 * we have resolved the address without
27637 				 * using Neighbor Discovery.
27638 				 * In the non-XRESOLV v6 case, the fastpath
27639 				 * probe is done right after neighbor
27640 				 * discovery completes.
27641 				 */
27642 				if (nce->nce_res_mp != NULL) {
27643 					int res;
27644 					nce_fastpath_list_add(nce);
27645 					res = ill_fastpath_probe(ill,
27646 					    nce->nce_res_mp);
27647 					if (res != 0 && res != EAGAIN)
27648 						nce_fastpath_list_delete(nce);
27649 				}
27650 
27651 				ire_add_then_send(q, ire, mp);
27652 				/*
27653 				 * Now we have to clean out any packets
27654 				 * that may have been queued on the nce
27655 				 * while it was waiting for address resolution
27656 				 * to complete.
27657 				 */
27658 				mutex_enter(&nce->nce_lock);
27659 				mp1 = nce->nce_qd_mp;
27660 				nce->nce_qd_mp = NULL;
27661 				mutex_exit(&nce->nce_lock);
27662 				while (mp1 != NULL) {
27663 					mblk_t *nxt_mp;
27664 					queue_t *fwdq = NULL;
27665 					ill_t   *inbound_ill;
27666 					uint_t ifindex;
27667 
27668 					nxt_mp = mp1->b_next;
27669 					mp1->b_next = NULL;
27670 					/*
27671 					 * Retrieve ifindex stored in
27672 					 * ip_rput_data_v6()
27673 					 */
27674 					ifindex =
27675 					    (uint_t)(uintptr_t)mp1->b_prev;
27676 					inbound_ill =
27677 					    ill_lookup_on_ifindex(ifindex,
27678 					    B_TRUE, NULL, NULL, NULL,
27679 					    NULL, ipst);
27680 					mp1->b_prev = NULL;
27681 					if (inbound_ill != NULL)
27682 						fwdq = inbound_ill->ill_rq;
27683 
27684 					if (fwdq != NULL) {
27685 						put(fwdq, mp1);
27686 						ill_refrele(inbound_ill);
27687 					} else
27688 						put(WR(ill->ill_rq), mp1);
27689 					mp1 = nxt_mp;
27690 				}
27691 				NCE_REFRELE(nce);
27692 			} else {	/* nce is NULL; clean up */
27693 				ire_delete(ire);
27694 				freemsg(mp);
27695 				freemsg(mp1);
27696 				return;
27697 			}
27698 		} else {
27699 			nce_t *arpce;
27700 			/*
27701 			 * Link layer resolution succeeded. Recompute the
27702 			 * ire_nce.
27703 			 */
27704 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27705 			if ((arpce = ndp_lookup_v4(ill,
27706 			    (ire->ire_gateway_addr != INADDR_ANY ?
27707 			    &ire->ire_gateway_addr : &ire->ire_addr),
27708 			    B_FALSE)) == NULL) {
27709 				freeb(ire->ire_mp);
27710 				freeb(mp1);
27711 				freemsg(mp);
27712 				return;
27713 			}
27714 			mutex_enter(&arpce->nce_lock);
27715 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27716 			if (arpce->nce_state == ND_REACHABLE) {
27717 				/*
27718 				 * Someone resolved this before us;
27719 				 * cleanup the res_mp. Since ire has
27720 				 * not been added yet, the call to ire_add_v4
27721 				 * from ire_add_then_send (when a dup is
27722 				 * detected) will clean up the ire.
27723 				 */
27724 				freeb(mp1);
27725 			} else {
27726 				ASSERT(arpce->nce_res_mp == NULL);
27727 				arpce->nce_res_mp = mp1;
27728 				arpce->nce_state = ND_REACHABLE;
27729 			}
27730 			mutex_exit(&arpce->nce_lock);
27731 			if (ire->ire_marks & IRE_MARK_NOADD) {
27732 				/*
27733 				 * this ire will not be added to the ire
27734 				 * cache table, so we can set the ire_nce
27735 				 * here, as there are no atomicity constraints.
27736 				 */
27737 				ire->ire_nce = arpce;
27738 				/*
27739 				 * We are associating this nce with the ire
27740 				 * so change the nce ref taken in
27741 				 * ndp_lookup_v4() from
27742 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27743 				 */
27744 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27745 			} else {
27746 				NCE_REFRELE(arpce);
27747 			}
27748 			ire_add_then_send(q, ire, mp);
27749 		}
27750 		return;	/* All is well, the packet has been sent. */
27751 	}
27752 	case IRE_ARPRESOLVE_TYPE: {
27753 
27754 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27755 			break;
27756 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27757 		mp->b_cont = NULL;
27758 		/*
27759 		 * First, check to make sure the resolution succeeded.
27760 		 * If it failed, the second mblk will be empty.
27761 		 */
27762 		if (mp1->b_rptr == mp1->b_wptr) {
27763 			/* cleanup  the incomplete ire, free queued packets */
27764 			freemsg(mp); /* fake ire */
27765 			freeb(mp1);  /* dl_unitdata response */
27766 			return;
27767 		}
27768 
27769 		/*
27770 		 * Update any incomplete nce_t found. We search the ctable
27771 		 * and find the nce from the ire->ire_nce because we need
27772 		 * to pass the ire to ip_xmit_v4 later, and can find both
27773 		 * ire and nce in one lookup.
27774 		 */
27775 		fake_ire = (ire_t *)mp->b_rptr;
27776 
27777 		/*
27778 		 * By the time we come back here from ARP the logical outgoing
27779 		 * interface of the incomplete ire we added in ire_forward()
27780 		 * could have disappeared, causing the incomplete ire to also
27781 		 * disappear.  So we need to retreive the proper ipif for the
27782 		 * ire before looking in ctable.  In the case of IPMP, the
27783 		 * ipif may be on the IPMP ill, so look it up based on the
27784 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27785 		 * Then, we can verify that ire_ipif_seqid still exists.
27786 		 */
27787 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27788 		    NULL, NULL, NULL, NULL, ipst);
27789 		if (ill == NULL) {
27790 			ip1dbg(("ill for incomplete ire vanished\n"));
27791 			freemsg(mp); /* fake ire */
27792 			freeb(mp1);  /* dl_unitdata response */
27793 			return;
27794 		}
27795 
27796 		/* Get the outgoing ipif */
27797 		mutex_enter(&ill->ill_lock);
27798 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27799 		if (ipif == NULL) {
27800 			mutex_exit(&ill->ill_lock);
27801 			ill_refrele(ill);
27802 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27803 			freemsg(mp); /* fake_ire */
27804 			freeb(mp1);  /* dl_unitdata response */
27805 			return;
27806 		}
27807 
27808 		ipif_refhold_locked(ipif);
27809 		mutex_exit(&ill->ill_lock);
27810 		ill_refrele(ill);
27811 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27812 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27813 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27814 		ipif_refrele(ipif);
27815 		if (ire == NULL) {
27816 			/*
27817 			 * no ire was found; check if there is an nce
27818 			 * for this lookup; if it has no ire's pointing at it
27819 			 * cleanup.
27820 			 */
27821 			if ((nce = ndp_lookup_v4(q->q_ptr,
27822 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27823 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27824 			    B_FALSE)) != NULL) {
27825 				/*
27826 				 * cleanup:
27827 				 * We check for refcnt 2 (one for the nce
27828 				 * hash list + 1 for the ref taken by
27829 				 * ndp_lookup_v4) to check that there are
27830 				 * no ire's pointing at the nce.
27831 				 */
27832 				if (nce->nce_refcnt == 2)
27833 					ndp_delete(nce);
27834 				NCE_REFRELE(nce);
27835 			}
27836 			freeb(mp1);  /* dl_unitdata response */
27837 			freemsg(mp); /* fake ire */
27838 			return;
27839 		}
27840 
27841 		nce = ire->ire_nce;
27842 		DTRACE_PROBE2(ire__arpresolve__type,
27843 		    ire_t *, ire, nce_t *, nce);
27844 		ASSERT(nce->nce_state != ND_INITIAL);
27845 		mutex_enter(&nce->nce_lock);
27846 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27847 		if (nce->nce_state == ND_REACHABLE) {
27848 			/*
27849 			 * Someone resolved this before us;
27850 			 * our response is not needed any more.
27851 			 */
27852 			mutex_exit(&nce->nce_lock);
27853 			freeb(mp1);  /* dl_unitdata response */
27854 		} else {
27855 			ASSERT(nce->nce_res_mp == NULL);
27856 			nce->nce_res_mp = mp1;
27857 			nce->nce_state = ND_REACHABLE;
27858 			mutex_exit(&nce->nce_lock);
27859 			nce_fastpath(nce);
27860 		}
27861 		/*
27862 		 * The cached nce_t has been updated to be reachable;
27863 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27864 		 */
27865 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27866 		freemsg(mp);
27867 		/*
27868 		 * send out queued packets.
27869 		 */
27870 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27871 
27872 		IRE_REFRELE(ire);
27873 		return;
27874 	}
27875 	default:
27876 		break;
27877 	}
27878 	if (q->q_next) {
27879 		putnext(q, mp);
27880 	} else
27881 		freemsg(mp);
27882 	return;
27883 
27884 protonak:
27885 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27886 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27887 		qreply(q, mp);
27888 }
27889 
27890 /*
27891  * Process IP options in an outbound packet.  Modify the destination if there
27892  * is a source route option.
27893  * Returns non-zero if something fails in which case an ICMP error has been
27894  * sent and mp freed.
27895  */
27896 static int
27897 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27898     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27899 {
27900 	ipoptp_t	opts;
27901 	uchar_t		*opt;
27902 	uint8_t		optval;
27903 	uint8_t		optlen;
27904 	ipaddr_t	dst;
27905 	intptr_t	code = 0;
27906 	mblk_t		*mp;
27907 	ire_t		*ire = NULL;
27908 
27909 	ip2dbg(("ip_wput_options\n"));
27910 	mp = ipsec_mp;
27911 	if (mctl_present) {
27912 		mp = ipsec_mp->b_cont;
27913 	}
27914 
27915 	dst = ipha->ipha_dst;
27916 	for (optval = ipoptp_first(&opts, ipha);
27917 	    optval != IPOPT_EOL;
27918 	    optval = ipoptp_next(&opts)) {
27919 		opt = opts.ipoptp_cur;
27920 		optlen = opts.ipoptp_len;
27921 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27922 		    optval, optlen));
27923 		switch (optval) {
27924 			uint32_t off;
27925 		case IPOPT_SSRR:
27926 		case IPOPT_LSRR:
27927 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27928 				ip1dbg((
27929 				    "ip_wput_options: bad option offset\n"));
27930 				code = (char *)&opt[IPOPT_OLEN] -
27931 				    (char *)ipha;
27932 				goto param_prob;
27933 			}
27934 			off = opt[IPOPT_OFFSET];
27935 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27936 			    ntohl(dst)));
27937 			/*
27938 			 * For strict: verify that dst is directly
27939 			 * reachable.
27940 			 */
27941 			if (optval == IPOPT_SSRR) {
27942 				ire = ire_ftable_lookup(dst, 0, 0,
27943 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27944 				    msg_getlabel(mp),
27945 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27946 				if (ire == NULL) {
27947 					ip1dbg(("ip_wput_options: SSRR not"
27948 					    " directly reachable: 0x%x\n",
27949 					    ntohl(dst)));
27950 					goto bad_src_route;
27951 				}
27952 				ire_refrele(ire);
27953 			}
27954 			break;
27955 		case IPOPT_RR:
27956 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27957 				ip1dbg((
27958 				    "ip_wput_options: bad option offset\n"));
27959 				code = (char *)&opt[IPOPT_OLEN] -
27960 				    (char *)ipha;
27961 				goto param_prob;
27962 			}
27963 			break;
27964 		case IPOPT_TS:
27965 			/*
27966 			 * Verify that length >=5 and that there is either
27967 			 * room for another timestamp or that the overflow
27968 			 * counter is not maxed out.
27969 			 */
27970 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27971 			if (optlen < IPOPT_MINLEN_IT) {
27972 				goto param_prob;
27973 			}
27974 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27975 				ip1dbg((
27976 				    "ip_wput_options: bad option offset\n"));
27977 				code = (char *)&opt[IPOPT_OFFSET] -
27978 				    (char *)ipha;
27979 				goto param_prob;
27980 			}
27981 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27982 			case IPOPT_TS_TSONLY:
27983 				off = IPOPT_TS_TIMELEN;
27984 				break;
27985 			case IPOPT_TS_TSANDADDR:
27986 			case IPOPT_TS_PRESPEC:
27987 			case IPOPT_TS_PRESPEC_RFC791:
27988 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27989 				break;
27990 			default:
27991 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27992 				    (char *)ipha;
27993 				goto param_prob;
27994 			}
27995 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27996 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27997 				/*
27998 				 * No room and the overflow counter is 15
27999 				 * already.
28000 				 */
28001 				goto param_prob;
28002 			}
28003 			break;
28004 		}
28005 	}
28006 
28007 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28008 		return (0);
28009 
28010 	ip1dbg(("ip_wput_options: error processing IP options."));
28011 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28012 
28013 param_prob:
28014 	/*
28015 	 * Since ip_wput() isn't close to finished, we fill
28016 	 * in enough of the header for credible error reporting.
28017 	 */
28018 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28019 		/* Failed */
28020 		freemsg(ipsec_mp);
28021 		return (-1);
28022 	}
28023 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28024 	return (-1);
28025 
28026 bad_src_route:
28027 	/*
28028 	 * Since ip_wput() isn't close to finished, we fill
28029 	 * in enough of the header for credible error reporting.
28030 	 */
28031 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28032 		/* Failed */
28033 		freemsg(ipsec_mp);
28034 		return (-1);
28035 	}
28036 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28037 	return (-1);
28038 }
28039 
28040 /*
28041  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28042  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28043  * thru /etc/system.
28044  */
28045 #define	CONN_MAXDRAINCNT	64
28046 
28047 static void
28048 conn_drain_init(ip_stack_t *ipst)
28049 {
28050 	int i, j;
28051 	idl_tx_list_t *itl_tx;
28052 
28053 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28054 
28055 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28056 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28057 		/*
28058 		 * Default value of the number of drainers is the
28059 		 * number of cpus, subject to maximum of 8 drainers.
28060 		 */
28061 		if (boot_max_ncpus != -1)
28062 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28063 		else
28064 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28065 	}
28066 
28067 	ipst->ips_idl_tx_list =
28068 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28069 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28070 		itl_tx =  &ipst->ips_idl_tx_list[i];
28071 		itl_tx->txl_drain_list =
28072 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28073 		    sizeof (idl_t), KM_SLEEP);
28074 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28075 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28076 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28077 			    MUTEX_DEFAULT, NULL);
28078 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28079 		}
28080 	}
28081 }
28082 
28083 static void
28084 conn_drain_fini(ip_stack_t *ipst)
28085 {
28086 	int i;
28087 	idl_tx_list_t *itl_tx;
28088 
28089 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28090 		itl_tx =  &ipst->ips_idl_tx_list[i];
28091 		kmem_free(itl_tx->txl_drain_list,
28092 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28093 	}
28094 	kmem_free(ipst->ips_idl_tx_list,
28095 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28096 	ipst->ips_idl_tx_list = NULL;
28097 }
28098 
28099 /*
28100  * Note: For an overview of how flowcontrol is handled in IP please see the
28101  * IP Flowcontrol notes at the top of this file.
28102  *
28103  * Flow control has blocked us from proceeding. Insert the given conn in one
28104  * of the conn drain lists. These conn wq's will be qenabled later on when
28105  * STREAMS flow control does a backenable. conn_walk_drain will enable
28106  * the first conn in each of these drain lists. Each of these qenabled conns
28107  * in turn enables the next in the list, after it runs, or when it closes,
28108  * thus sustaining the drain process.
28109  */
28110 void
28111 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28112 {
28113 	idl_t	*idl = tx_list->txl_drain_list;
28114 	uint_t	index;
28115 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28116 
28117 	mutex_enter(&connp->conn_lock);
28118 	if (connp->conn_state_flags & CONN_CLOSING) {
28119 		/*
28120 		 * The conn is closing as a result of which CONN_CLOSING
28121 		 * is set. Return.
28122 		 */
28123 		mutex_exit(&connp->conn_lock);
28124 		return;
28125 	} else if (connp->conn_idl == NULL) {
28126 		/*
28127 		 * Assign the next drain list round robin. We dont' use
28128 		 * a lock, and thus it may not be strictly round robin.
28129 		 * Atomicity of load/stores is enough to make sure that
28130 		 * conn_drain_list_index is always within bounds.
28131 		 */
28132 		index = tx_list->txl_drain_index;
28133 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28134 		connp->conn_idl = &tx_list->txl_drain_list[index];
28135 		index++;
28136 		if (index == ipst->ips_conn_drain_list_cnt)
28137 			index = 0;
28138 		tx_list->txl_drain_index = index;
28139 	}
28140 	mutex_exit(&connp->conn_lock);
28141 
28142 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28143 	if ((connp->conn_drain_prev != NULL) ||
28144 	    (connp->conn_state_flags & CONN_CLOSING)) {
28145 		/*
28146 		 * The conn is already in the drain list, OR
28147 		 * the conn is closing. We need to check again for
28148 		 * the closing case again since close can happen
28149 		 * after we drop the conn_lock, and before we
28150 		 * acquire the CONN_DRAIN_LIST_LOCK.
28151 		 */
28152 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28153 		return;
28154 	} else {
28155 		idl = connp->conn_idl;
28156 	}
28157 
28158 	/*
28159 	 * The conn is not in the drain list. Insert it at the
28160 	 * tail of the drain list. The drain list is circular
28161 	 * and doubly linked. idl_conn points to the 1st element
28162 	 * in the list.
28163 	 */
28164 	if (idl->idl_conn == NULL) {
28165 		idl->idl_conn = connp;
28166 		connp->conn_drain_next = connp;
28167 		connp->conn_drain_prev = connp;
28168 	} else {
28169 		conn_t *head = idl->idl_conn;
28170 
28171 		connp->conn_drain_next = head;
28172 		connp->conn_drain_prev = head->conn_drain_prev;
28173 		head->conn_drain_prev->conn_drain_next = connp;
28174 		head->conn_drain_prev = connp;
28175 	}
28176 	/*
28177 	 * For non streams based sockets assert flow control.
28178 	 */
28179 	if (IPCL_IS_NONSTR(connp)) {
28180 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28181 		(*connp->conn_upcalls->su_txq_full)
28182 		    (connp->conn_upper_handle, B_TRUE);
28183 	} else {
28184 		conn_setqfull(connp);
28185 		noenable(connp->conn_wq);
28186 	}
28187 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28188 }
28189 
28190 /*
28191  * This conn is closing, and we are called from ip_close. OR
28192  * This conn has been serviced by ip_wsrv, and we need to do the tail
28193  * processing.
28194  * If this conn is part of the drain list, we may need to sustain the drain
28195  * process by qenabling the next conn in the drain list. We may also need to
28196  * remove this conn from the list, if it is done.
28197  */
28198 static void
28199 conn_drain_tail(conn_t *connp, boolean_t closing)
28200 {
28201 	idl_t *idl;
28202 
28203 	/*
28204 	 * connp->conn_idl is stable at this point, and no lock is needed
28205 	 * to check it. If we are called from ip_close, close has already
28206 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28207 	 * called us only because conn_idl is non-null. If we are called thru
28208 	 * service, conn_idl could be null, but it cannot change because
28209 	 * service is single-threaded per queue, and there cannot be another
28210 	 * instance of service trying to call conn_drain_insert on this conn
28211 	 * now.
28212 	 */
28213 	ASSERT(!closing || (connp->conn_idl != NULL));
28214 
28215 	/*
28216 	 * If connp->conn_idl is null, the conn has not been inserted into any
28217 	 * drain list even once since creation of the conn. Just return.
28218 	 */
28219 	if (connp->conn_idl == NULL)
28220 		return;
28221 
28222 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28223 
28224 	if (connp->conn_drain_prev == NULL) {
28225 		/* This conn is currently not in the drain list.  */
28226 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28227 		return;
28228 	}
28229 	idl = connp->conn_idl;
28230 	if (idl->idl_conn_draining == connp) {
28231 		/*
28232 		 * This conn is the current drainer. If this is the last conn
28233 		 * in the drain list, we need to do more checks, in the 'if'
28234 		 * below. Otherwwise we need to just qenable the next conn,
28235 		 * to sustain the draining, and is handled in the 'else'
28236 		 * below.
28237 		 */
28238 		if (connp->conn_drain_next == idl->idl_conn) {
28239 			/*
28240 			 * This conn is the last in this list. This round
28241 			 * of draining is complete. If idl_repeat is set,
28242 			 * it means another flow enabling has happened from
28243 			 * the driver/streams and we need to another round
28244 			 * of draining.
28245 			 * If there are more than 2 conns in the drain list,
28246 			 * do a left rotate by 1, so that all conns except the
28247 			 * conn at the head move towards the head by 1, and the
28248 			 * the conn at the head goes to the tail. This attempts
28249 			 * a more even share for all queues that are being
28250 			 * drained.
28251 			 */
28252 			if ((connp->conn_drain_next != connp) &&
28253 			    (idl->idl_conn->conn_drain_next != connp)) {
28254 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28255 			}
28256 			if (idl->idl_repeat) {
28257 				qenable(idl->idl_conn->conn_wq);
28258 				idl->idl_conn_draining = idl->idl_conn;
28259 				idl->idl_repeat = 0;
28260 			} else {
28261 				idl->idl_conn_draining = NULL;
28262 			}
28263 		} else {
28264 			/*
28265 			 * If the next queue that we are now qenable'ing,
28266 			 * is closing, it will remove itself from this list
28267 			 * and qenable the subsequent queue in ip_close().
28268 			 * Serialization is acheived thru idl_lock.
28269 			 */
28270 			qenable(connp->conn_drain_next->conn_wq);
28271 			idl->idl_conn_draining = connp->conn_drain_next;
28272 		}
28273 	}
28274 	if (!connp->conn_did_putbq || closing) {
28275 		/*
28276 		 * Remove ourself from the drain list, if we did not do
28277 		 * a putbq, or if the conn is closing.
28278 		 * Note: It is possible that q->q_first is non-null. It means
28279 		 * that these messages landed after we did a enableok() in
28280 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28281 		 * service them.
28282 		 */
28283 		if (connp->conn_drain_next == connp) {
28284 			/* Singleton in the list */
28285 			ASSERT(connp->conn_drain_prev == connp);
28286 			idl->idl_conn = NULL;
28287 			idl->idl_conn_draining = NULL;
28288 		} else {
28289 			connp->conn_drain_prev->conn_drain_next =
28290 			    connp->conn_drain_next;
28291 			connp->conn_drain_next->conn_drain_prev =
28292 			    connp->conn_drain_prev;
28293 			if (idl->idl_conn == connp)
28294 				idl->idl_conn = connp->conn_drain_next;
28295 			ASSERT(idl->idl_conn_draining != connp);
28296 
28297 		}
28298 		connp->conn_drain_next = NULL;
28299 		connp->conn_drain_prev = NULL;
28300 
28301 		/*
28302 		 * For non streams based sockets open up flow control.
28303 		 */
28304 		if (IPCL_IS_NONSTR(connp)) {
28305 			(*connp->conn_upcalls->su_txq_full)
28306 			    (connp->conn_upper_handle, B_FALSE);
28307 		} else {
28308 			conn_clrqfull(connp);
28309 			enableok(connp->conn_wq);
28310 		}
28311 	}
28312 
28313 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28314 }
28315 
28316 /*
28317  * Write service routine. Shared perimeter entry point.
28318  * ip_wsrv can be called in any of the following ways.
28319  * 1. The device queue's messages has fallen below the low water mark
28320  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28321  *    the drain lists and backenable the first conn in each list.
28322  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28323  *    qenabled non-tcp upper layers. We start dequeing messages and call
28324  *    ip_wput for each message.
28325  */
28326 
28327 void
28328 ip_wsrv(queue_t *q)
28329 {
28330 	conn_t	*connp;
28331 	ill_t	*ill;
28332 	mblk_t	*mp;
28333 
28334 	if (q->q_next) {
28335 		ill = (ill_t *)q->q_ptr;
28336 		if (ill->ill_state_flags == 0) {
28337 			ip_stack_t *ipst = ill->ill_ipst;
28338 
28339 			/*
28340 			 * The device flow control has opened up.
28341 			 * Walk through conn drain lists and qenable the
28342 			 * first conn in each list. This makes sense only
28343 			 * if the stream is fully plumbed and setup.
28344 			 * Hence the if check above.
28345 			 */
28346 			ip1dbg(("ip_wsrv: walking\n"));
28347 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28348 		}
28349 		return;
28350 	}
28351 
28352 	connp = Q_TO_CONN(q);
28353 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28354 
28355 	/*
28356 	 * 1. Set conn_draining flag to signal that service is active.
28357 	 *
28358 	 * 2. ip_output determines whether it has been called from service,
28359 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28360 	 *    has been called from service.
28361 	 *
28362 	 * 3. Message ordering is preserved by the following logic.
28363 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28364 	 *    the message at the tail, if conn_draining is set (i.e. service
28365 	 *    is running) or if q->q_first is non-null.
28366 	 *
28367 	 *    ii. If ip_output is called from service, and if ip_output cannot
28368 	 *    putnext due to flow control, it does a putbq.
28369 	 *
28370 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28371 	 *    (causing an infinite loop).
28372 	 */
28373 	ASSERT(!connp->conn_did_putbq);
28374 
28375 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28376 		connp->conn_draining = 1;
28377 		noenable(q);
28378 		while ((mp = getq(q)) != NULL) {
28379 			ASSERT(CONN_Q(q));
28380 
28381 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28382 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28383 			if (connp->conn_did_putbq) {
28384 				/* ip_wput did a putbq */
28385 				break;
28386 			}
28387 		}
28388 		/*
28389 		 * At this point, a thread coming down from top, calling
28390 		 * ip_wput, may end up queueing the message. We have not yet
28391 		 * enabled the queue, so ip_wsrv won't be called again.
28392 		 * To avoid this race, check q->q_first again (in the loop)
28393 		 * If the other thread queued the message before we call
28394 		 * enableok(), we will catch it in the q->q_first check.
28395 		 * If the other thread queues the message after we call
28396 		 * enableok(), ip_wsrv will be called again by STREAMS.
28397 		 */
28398 		connp->conn_draining = 0;
28399 		enableok(q);
28400 	}
28401 
28402 	/* Enable the next conn for draining */
28403 	conn_drain_tail(connp, B_FALSE);
28404 
28405 	/*
28406 	 * conn_direct_blocked is used to indicate blocked
28407 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28408 	 * This is the only place where it is set without
28409 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28410 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28411 	 */
28412 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28413 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28414 		connp->conn_direct_blocked = B_FALSE;
28415 	}
28416 
28417 	connp->conn_did_putbq = 0;
28418 }
28419 
28420 /*
28421  * Callback to disable flow control in IP.
28422  *
28423  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28424  * is enabled.
28425  *
28426  * When MAC_TX() is not able to send any more packets, dld sets its queue
28427  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28428  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28429  * function and wakes up corresponding mac worker threads, which in turn
28430  * calls this callback function, and disables flow control.
28431  */
28432 void
28433 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28434 {
28435 	ill_t *ill = (ill_t *)arg;
28436 	ip_stack_t *ipst = ill->ill_ipst;
28437 	idl_tx_list_t *idl_txl;
28438 
28439 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28440 	mutex_enter(&idl_txl->txl_lock);
28441 	/* add code to to set a flag to indicate idl_txl is enabled */
28442 	conn_walk_drain(ipst, idl_txl);
28443 	mutex_exit(&idl_txl->txl_lock);
28444 }
28445 
28446 /*
28447  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28448  * of conns that need to be drained, check if drain is already in progress.
28449  * If so set the idl_repeat bit, indicating that the last conn in the list
28450  * needs to reinitiate the drain once again, for the list. If drain is not
28451  * in progress for the list, initiate the draining, by qenabling the 1st
28452  * conn in the list. The drain is self-sustaining, each qenabled conn will
28453  * in turn qenable the next conn, when it is done/blocked/closing.
28454  */
28455 static void
28456 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28457 {
28458 	int i;
28459 	idl_t *idl;
28460 
28461 	IP_STAT(ipst, ip_conn_walk_drain);
28462 
28463 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28464 		idl = &tx_list->txl_drain_list[i];
28465 		mutex_enter(&idl->idl_lock);
28466 		if (idl->idl_conn == NULL) {
28467 			mutex_exit(&idl->idl_lock);
28468 			continue;
28469 		}
28470 		/*
28471 		 * If this list is not being drained currently by
28472 		 * an ip_wsrv thread, start the process.
28473 		 */
28474 		if (idl->idl_conn_draining == NULL) {
28475 			ASSERT(idl->idl_repeat == 0);
28476 			qenable(idl->idl_conn->conn_wq);
28477 			idl->idl_conn_draining = idl->idl_conn;
28478 		} else {
28479 			idl->idl_repeat = 1;
28480 		}
28481 		mutex_exit(&idl->idl_lock);
28482 	}
28483 }
28484 
28485 /*
28486  * Determine if the ill and multicast aspects of that packets
28487  * "matches" the conn.
28488  */
28489 boolean_t
28490 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28491     zoneid_t zoneid)
28492 {
28493 	ill_t *bound_ill;
28494 	boolean_t found;
28495 	ipif_t *ipif;
28496 	ire_t *ire;
28497 	ipaddr_t dst, src;
28498 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28499 
28500 	dst = ipha->ipha_dst;
28501 	src = ipha->ipha_src;
28502 
28503 	/*
28504 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28505 	 * unicast, broadcast and multicast reception to
28506 	 * conn_incoming_ill. conn_wantpacket itself is called
28507 	 * only for BROADCAST and multicast.
28508 	 */
28509 	bound_ill = connp->conn_incoming_ill;
28510 	if (bound_ill != NULL) {
28511 		if (IS_IPMP(bound_ill)) {
28512 			if (bound_ill->ill_grp != ill->ill_grp)
28513 				return (B_FALSE);
28514 		} else {
28515 			if (bound_ill != ill)
28516 				return (B_FALSE);
28517 		}
28518 	}
28519 
28520 	if (!CLASSD(dst)) {
28521 		if (IPCL_ZONE_MATCH(connp, zoneid))
28522 			return (B_TRUE);
28523 		/*
28524 		 * The conn is in a different zone; we need to check that this
28525 		 * broadcast address is configured in the application's zone.
28526 		 */
28527 		ipif = ipif_get_next_ipif(NULL, ill);
28528 		if (ipif == NULL)
28529 			return (B_FALSE);
28530 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28531 		    connp->conn_zoneid, NULL,
28532 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28533 		ipif_refrele(ipif);
28534 		if (ire != NULL) {
28535 			ire_refrele(ire);
28536 			return (B_TRUE);
28537 		} else {
28538 			return (B_FALSE);
28539 		}
28540 	}
28541 
28542 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28543 	    connp->conn_zoneid == zoneid) {
28544 		/*
28545 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28546 		 * disabled, therefore we don't dispatch the multicast packet to
28547 		 * the sending zone.
28548 		 */
28549 		return (B_FALSE);
28550 	}
28551 
28552 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28553 		/*
28554 		 * Multicast packet on the loopback interface: we only match
28555 		 * conns who joined the group in the specified zone.
28556 		 */
28557 		return (B_FALSE);
28558 	}
28559 
28560 	if (connp->conn_multi_router) {
28561 		/* multicast packet and multicast router socket: send up */
28562 		return (B_TRUE);
28563 	}
28564 
28565 	mutex_enter(&connp->conn_lock);
28566 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28567 	mutex_exit(&connp->conn_lock);
28568 	return (found);
28569 }
28570 
28571 static void
28572 conn_setqfull(conn_t *connp)
28573 {
28574 	queue_t *q = connp->conn_wq;
28575 
28576 	if (!(q->q_flag & QFULL)) {
28577 		mutex_enter(QLOCK(q));
28578 		if (!(q->q_flag & QFULL)) {
28579 			/* still need to set QFULL */
28580 			q->q_flag |= QFULL;
28581 			mutex_exit(QLOCK(q));
28582 		} else {
28583 			mutex_exit(QLOCK(q));
28584 		}
28585 	}
28586 }
28587 
28588 static void
28589 conn_clrqfull(conn_t *connp)
28590 {
28591 	queue_t *q = connp->conn_wq;
28592 
28593 	if (q->q_flag & QFULL) {
28594 		mutex_enter(QLOCK(q));
28595 		if (q->q_flag & QFULL) {
28596 			q->q_flag &= ~QFULL;
28597 			mutex_exit(QLOCK(q));
28598 			if (q->q_flag & QWANTW)
28599 				qbackenable(q, 0);
28600 		} else {
28601 			mutex_exit(QLOCK(q));
28602 		}
28603 	}
28604 }
28605 
28606 /*
28607  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28608  */
28609 /* ARGSUSED */
28610 static void
28611 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28612 {
28613 	ill_t *ill = (ill_t *)q->q_ptr;
28614 	mblk_t	*mp1, *mp2;
28615 	ipif_t  *ipif;
28616 	int err = 0;
28617 	conn_t *connp = NULL;
28618 	ipsq_t	*ipsq;
28619 	arc_t	*arc;
28620 
28621 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28622 
28623 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28624 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28625 
28626 	ASSERT(IAM_WRITER_ILL(ill));
28627 	mp2 = mp->b_cont;
28628 	mp->b_cont = NULL;
28629 
28630 	/*
28631 	 * We have now received the arp bringup completion message
28632 	 * from ARP. Mark the arp bringup as done. Also if the arp
28633 	 * stream has already started closing, send up the AR_ARP_CLOSING
28634 	 * ack now since ARP is waiting in close for this ack.
28635 	 */
28636 	mutex_enter(&ill->ill_lock);
28637 	ill->ill_arp_bringup_pending = 0;
28638 	if (ill->ill_arp_closing) {
28639 		mutex_exit(&ill->ill_lock);
28640 		/* Let's reuse the mp for sending the ack */
28641 		arc = (arc_t *)mp->b_rptr;
28642 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28643 		arc->arc_cmd = AR_ARP_CLOSING;
28644 		qreply(q, mp);
28645 	} else {
28646 		mutex_exit(&ill->ill_lock);
28647 		freeb(mp);
28648 	}
28649 
28650 	ipsq = ill->ill_phyint->phyint_ipsq;
28651 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28652 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28653 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28654 	if (mp1 == NULL) {
28655 		/* bringup was aborted by the user */
28656 		freemsg(mp2);
28657 		return;
28658 	}
28659 
28660 	/*
28661 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28662 	 * must have an associated conn_t.  Otherwise, we're bringing this
28663 	 * interface back up as part of handling an asynchronous event (e.g.,
28664 	 * physical address change).
28665 	 */
28666 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28667 		ASSERT(connp != NULL);
28668 		q = CONNP_TO_WQ(connp);
28669 	} else {
28670 		ASSERT(connp == NULL);
28671 		q = ill->ill_rq;
28672 	}
28673 
28674 	/*
28675 	 * If the DL_BIND_REQ fails, it is noted
28676 	 * in arc_name_offset.
28677 	 */
28678 	err = *((int *)mp2->b_rptr);
28679 	if (err == 0) {
28680 		if (ipif->ipif_isv6) {
28681 			if ((err = ipif_up_done_v6(ipif)) != 0)
28682 				ip0dbg(("ip_arp_done: init failed\n"));
28683 		} else {
28684 			if ((err = ipif_up_done(ipif)) != 0)
28685 				ip0dbg(("ip_arp_done: init failed\n"));
28686 		}
28687 	} else {
28688 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28689 	}
28690 
28691 	freemsg(mp2);
28692 
28693 	if ((err == 0) && (ill->ill_up_ipifs)) {
28694 		err = ill_up_ipifs(ill, q, mp1);
28695 		if (err == EINPROGRESS)
28696 			return;
28697 	}
28698 
28699 	/*
28700 	 * If we have a moved ipif to bring up, and everything has succeeded
28701 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28702 	 * down -- the admin can try to bring it up by hand if need be.
28703 	 */
28704 	if (ill->ill_move_ipif != NULL) {
28705 		ipif = ill->ill_move_ipif;
28706 		ill->ill_move_ipif = NULL;
28707 		if (err == 0) {
28708 			err = ipif_up(ipif, q, mp1);
28709 			if (err == EINPROGRESS)
28710 				return;
28711 		}
28712 	}
28713 
28714 	/*
28715 	 * The operation must complete without EINPROGRESS since
28716 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28717 	 * operation will be stuck forever in the ipsq.
28718 	 */
28719 	ASSERT(err != EINPROGRESS);
28720 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28721 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28722 	else
28723 		ipsq_current_finish(ipsq);
28724 }
28725 
28726 /* Allocate the private structure */
28727 static int
28728 ip_priv_alloc(void **bufp)
28729 {
28730 	void	*buf;
28731 
28732 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28733 		return (ENOMEM);
28734 
28735 	*bufp = buf;
28736 	return (0);
28737 }
28738 
28739 /* Function to delete the private structure */
28740 void
28741 ip_priv_free(void *buf)
28742 {
28743 	ASSERT(buf != NULL);
28744 	kmem_free(buf, sizeof (ip_priv_t));
28745 }
28746 
28747 /*
28748  * The entry point for IPPF processing.
28749  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28750  * routine just returns.
28751  *
28752  * When called, ip_process generates an ipp_packet_t structure
28753  * which holds the state information for this packet and invokes the
28754  * the classifier (via ipp_packet_process). The classification, depending on
28755  * configured filters, results in a list of actions for this packet. Invoking
28756  * an action may cause the packet to be dropped, in which case the resulting
28757  * mblk (*mpp) is NULL. proc indicates the callout position for
28758  * this packet and ill_index is the interface this packet on or will leave
28759  * on (inbound and outbound resp.).
28760  */
28761 void
28762 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28763 {
28764 	mblk_t		*mp;
28765 	ip_priv_t	*priv;
28766 	ipp_action_id_t	aid;
28767 	int		rc = 0;
28768 	ipp_packet_t	*pp;
28769 #define	IP_CLASS	"ip"
28770 
28771 	/* If the classifier is not loaded, return  */
28772 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28773 		return;
28774 	}
28775 
28776 	mp = *mpp;
28777 	ASSERT(mp != NULL);
28778 
28779 	/* Allocate the packet structure */
28780 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28781 	if (rc != 0) {
28782 		*mpp = NULL;
28783 		freemsg(mp);
28784 		return;
28785 	}
28786 
28787 	/* Allocate the private structure */
28788 	rc = ip_priv_alloc((void **)&priv);
28789 	if (rc != 0) {
28790 		*mpp = NULL;
28791 		freemsg(mp);
28792 		ipp_packet_free(pp);
28793 		return;
28794 	}
28795 	priv->proc = proc;
28796 	priv->ill_index = ill_index;
28797 	ipp_packet_set_private(pp, priv, ip_priv_free);
28798 	ipp_packet_set_data(pp, mp);
28799 
28800 	/* Invoke the classifier */
28801 	rc = ipp_packet_process(&pp);
28802 	if (pp != NULL) {
28803 		mp = ipp_packet_get_data(pp);
28804 		ipp_packet_free(pp);
28805 		if (rc != 0) {
28806 			freemsg(mp);
28807 			*mpp = NULL;
28808 		}
28809 	} else {
28810 		*mpp = NULL;
28811 	}
28812 #undef	IP_CLASS
28813 }
28814 
28815 /*
28816  * Propagate a multicast group membership operation (add/drop) on
28817  * all the interfaces crossed by the related multirt routes.
28818  * The call is considered successful if the operation succeeds
28819  * on at least one interface.
28820  */
28821 static int
28822 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28823     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28824     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28825     mblk_t *first_mp)
28826 {
28827 	ire_t		*ire_gw;
28828 	irb_t		*irb;
28829 	int		error = 0;
28830 	opt_restart_t	*or;
28831 	ip_stack_t	*ipst = ire->ire_ipst;
28832 
28833 	irb = ire->ire_bucket;
28834 	ASSERT(irb != NULL);
28835 
28836 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28837 
28838 	or = (opt_restart_t *)first_mp->b_rptr;
28839 	IRB_REFHOLD(irb);
28840 	for (; ire != NULL; ire = ire->ire_next) {
28841 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28842 			continue;
28843 		if (ire->ire_addr != group)
28844 			continue;
28845 
28846 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28847 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28848 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28849 		/* No resolver exists for the gateway; skip this ire. */
28850 		if (ire_gw == NULL)
28851 			continue;
28852 
28853 		/*
28854 		 * This function can return EINPROGRESS. If so the operation
28855 		 * will be restarted from ip_restart_optmgmt which will
28856 		 * call ip_opt_set and option processing will restart for
28857 		 * this option. So we may end up calling 'fn' more than once.
28858 		 * This requires that 'fn' is idempotent except for the
28859 		 * return value. The operation is considered a success if
28860 		 * it succeeds at least once on any one interface.
28861 		 */
28862 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28863 		    NULL, fmode, src, first_mp);
28864 		if (error == 0)
28865 			or->or_private = CGTP_MCAST_SUCCESS;
28866 
28867 		if (ip_debug > 0) {
28868 			ulong_t	off;
28869 			char	*ksym;
28870 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28871 			ip2dbg(("ip_multirt_apply_membership: "
28872 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28873 			    "error %d [success %u]\n",
28874 			    ksym ? ksym : "?",
28875 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28876 			    error, or->or_private));
28877 		}
28878 
28879 		ire_refrele(ire_gw);
28880 		if (error == EINPROGRESS) {
28881 			IRB_REFRELE(irb);
28882 			return (error);
28883 		}
28884 	}
28885 	IRB_REFRELE(irb);
28886 	/*
28887 	 * Consider the call as successful if we succeeded on at least
28888 	 * one interface. Otherwise, return the last encountered error.
28889 	 */
28890 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28891 }
28892 
28893 /*
28894  * Issue a warning regarding a route crossing an interface with an
28895  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28896  * amount of time is logged.
28897  */
28898 static void
28899 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28900 {
28901 	hrtime_t	current = gethrtime();
28902 	char		buf[INET_ADDRSTRLEN];
28903 	ip_stack_t	*ipst = ire->ire_ipst;
28904 
28905 	/* Convert interval in ms to hrtime in ns */
28906 	if (ipst->ips_multirt_bad_mtu_last_time +
28907 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28908 	    current) {
28909 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28910 		    "to %s, incorrect MTU %u (expected %u)\n",
28911 		    ip_dot_addr(ire->ire_addr, buf),
28912 		    ire->ire_max_frag, max_frag);
28913 
28914 		ipst->ips_multirt_bad_mtu_last_time = current;
28915 	}
28916 }
28917 
28918 /*
28919  * Get the CGTP (multirouting) filtering status.
28920  * If 0, the CGTP hooks are transparent.
28921  */
28922 /* ARGSUSED */
28923 static int
28924 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28925 {
28926 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28927 
28928 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28929 	return (0);
28930 }
28931 
28932 /*
28933  * Set the CGTP (multirouting) filtering status.
28934  * If the status is changed from active to transparent
28935  * or from transparent to active, forward the new status
28936  * to the filtering module (if loaded).
28937  */
28938 /* ARGSUSED */
28939 static int
28940 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28941     cred_t *ioc_cr)
28942 {
28943 	long		new_value;
28944 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28945 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28946 
28947 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28948 		return (EPERM);
28949 
28950 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28951 	    new_value < 0 || new_value > 1) {
28952 		return (EINVAL);
28953 	}
28954 
28955 	if ((!*ip_cgtp_filter_value) && new_value) {
28956 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28957 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28958 		    " (module not loaded)" : "");
28959 	}
28960 	if (*ip_cgtp_filter_value && (!new_value)) {
28961 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28962 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28963 		    " (module not loaded)" : "");
28964 	}
28965 
28966 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28967 		int	res;
28968 		netstackid_t stackid;
28969 
28970 		stackid = ipst->ips_netstack->netstack_stackid;
28971 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28972 		    new_value);
28973 		if (res)
28974 			return (res);
28975 	}
28976 
28977 	*ip_cgtp_filter_value = (boolean_t)new_value;
28978 
28979 	return (0);
28980 }
28981 
28982 /*
28983  * Return the expected CGTP hooks version number.
28984  */
28985 int
28986 ip_cgtp_filter_supported(void)
28987 {
28988 	return (ip_cgtp_filter_rev);
28989 }
28990 
28991 /*
28992  * CGTP hooks can be registered by invoking this function.
28993  * Checks that the version number matches.
28994  */
28995 int
28996 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28997 {
28998 	netstack_t *ns;
28999 	ip_stack_t *ipst;
29000 
29001 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29002 		return (ENOTSUP);
29003 
29004 	ns = netstack_find_by_stackid(stackid);
29005 	if (ns == NULL)
29006 		return (EINVAL);
29007 	ipst = ns->netstack_ip;
29008 	ASSERT(ipst != NULL);
29009 
29010 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29011 		netstack_rele(ns);
29012 		return (EALREADY);
29013 	}
29014 
29015 	ipst->ips_ip_cgtp_filter_ops = ops;
29016 	netstack_rele(ns);
29017 	return (0);
29018 }
29019 
29020 /*
29021  * CGTP hooks can be unregistered by invoking this function.
29022  * Returns ENXIO if there was no registration.
29023  * Returns EBUSY if the ndd variable has not been turned off.
29024  */
29025 int
29026 ip_cgtp_filter_unregister(netstackid_t stackid)
29027 {
29028 	netstack_t *ns;
29029 	ip_stack_t *ipst;
29030 
29031 	ns = netstack_find_by_stackid(stackid);
29032 	if (ns == NULL)
29033 		return (EINVAL);
29034 	ipst = ns->netstack_ip;
29035 	ASSERT(ipst != NULL);
29036 
29037 	if (ipst->ips_ip_cgtp_filter) {
29038 		netstack_rele(ns);
29039 		return (EBUSY);
29040 	}
29041 
29042 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29043 		netstack_rele(ns);
29044 		return (ENXIO);
29045 	}
29046 	ipst->ips_ip_cgtp_filter_ops = NULL;
29047 	netstack_rele(ns);
29048 	return (0);
29049 }
29050 
29051 /*
29052  * Check whether there is a CGTP filter registration.
29053  * Returns non-zero if there is a registration, otherwise returns zero.
29054  * Note: returns zero if bad stackid.
29055  */
29056 int
29057 ip_cgtp_filter_is_registered(netstackid_t stackid)
29058 {
29059 	netstack_t *ns;
29060 	ip_stack_t *ipst;
29061 	int ret;
29062 
29063 	ns = netstack_find_by_stackid(stackid);
29064 	if (ns == NULL)
29065 		return (0);
29066 	ipst = ns->netstack_ip;
29067 	ASSERT(ipst != NULL);
29068 
29069 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29070 		ret = 1;
29071 	else
29072 		ret = 0;
29073 
29074 	netstack_rele(ns);
29075 	return (ret);
29076 }
29077 
29078 static int
29079 ip_squeue_switch(int val)
29080 {
29081 	int rval = SQ_FILL;
29082 
29083 	switch (val) {
29084 	case IP_SQUEUE_ENTER_NODRAIN:
29085 		rval = SQ_NODRAIN;
29086 		break;
29087 	case IP_SQUEUE_ENTER:
29088 		rval = SQ_PROCESS;
29089 		break;
29090 	default:
29091 		break;
29092 	}
29093 	return (rval);
29094 }
29095 
29096 /* ARGSUSED */
29097 static int
29098 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29099     caddr_t addr, cred_t *cr)
29100 {
29101 	int *v = (int *)addr;
29102 	long new_value;
29103 
29104 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29105 		return (EPERM);
29106 
29107 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29108 		return (EINVAL);
29109 
29110 	ip_squeue_flag = ip_squeue_switch(new_value);
29111 	*v = new_value;
29112 	return (0);
29113 }
29114 
29115 /*
29116  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29117  * ip_debug.
29118  */
29119 /* ARGSUSED */
29120 static int
29121 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29122     caddr_t addr, cred_t *cr)
29123 {
29124 	int *v = (int *)addr;
29125 	long new_value;
29126 
29127 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29128 		return (EPERM);
29129 
29130 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29131 		return (EINVAL);
29132 
29133 	*v = new_value;
29134 	return (0);
29135 }
29136 
29137 static void *
29138 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29139 {
29140 	kstat_t *ksp;
29141 
29142 	ip_stat_t template = {
29143 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29144 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29145 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29146 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29147 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29148 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29149 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29150 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29151 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29152 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29153 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29154 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29155 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29156 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29157 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29158 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29159 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29160 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29161 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29162 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29163 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29164 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29165 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29166 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29167 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29168 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29169 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29170 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29171 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29172 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29173 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29174 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29175 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29176 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29177 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29178 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29179 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29180 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29181 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29182 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29183 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29184 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29185 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29186 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29187 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29188 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29189 	};
29190 
29191 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29192 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29193 	    KSTAT_FLAG_VIRTUAL, stackid);
29194 
29195 	if (ksp == NULL)
29196 		return (NULL);
29197 
29198 	bcopy(&template, ip_statisticsp, sizeof (template));
29199 	ksp->ks_data = (void *)ip_statisticsp;
29200 	ksp->ks_private = (void *)(uintptr_t)stackid;
29201 
29202 	kstat_install(ksp);
29203 	return (ksp);
29204 }
29205 
29206 static void
29207 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29208 {
29209 	if (ksp != NULL) {
29210 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29211 		kstat_delete_netstack(ksp, stackid);
29212 	}
29213 }
29214 
29215 static void *
29216 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29217 {
29218 	kstat_t	*ksp;
29219 
29220 	ip_named_kstat_t template = {
29221 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29222 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29223 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29224 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29225 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29226 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29227 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29228 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29229 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29230 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29231 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29232 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29233 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29234 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29235 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29236 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29237 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29238 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29239 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29240 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29241 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29242 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29243 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29244 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29245 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29246 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29247 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29248 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29249 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29250 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29251 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29252 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29253 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29254 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29255 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29256 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29257 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29258 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29259 	};
29260 
29261 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29262 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29263 	if (ksp == NULL || ksp->ks_data == NULL)
29264 		return (NULL);
29265 
29266 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29267 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29268 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29269 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29270 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29271 
29272 	template.netToMediaEntrySize.value.i32 =
29273 	    sizeof (mib2_ipNetToMediaEntry_t);
29274 
29275 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29276 
29277 	bcopy(&template, ksp->ks_data, sizeof (template));
29278 	ksp->ks_update = ip_kstat_update;
29279 	ksp->ks_private = (void *)(uintptr_t)stackid;
29280 
29281 	kstat_install(ksp);
29282 	return (ksp);
29283 }
29284 
29285 static void
29286 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29287 {
29288 	if (ksp != NULL) {
29289 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29290 		kstat_delete_netstack(ksp, stackid);
29291 	}
29292 }
29293 
29294 static int
29295 ip_kstat_update(kstat_t *kp, int rw)
29296 {
29297 	ip_named_kstat_t *ipkp;
29298 	mib2_ipIfStatsEntry_t ipmib;
29299 	ill_walk_context_t ctx;
29300 	ill_t *ill;
29301 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29302 	netstack_t	*ns;
29303 	ip_stack_t	*ipst;
29304 
29305 	if (kp == NULL || kp->ks_data == NULL)
29306 		return (EIO);
29307 
29308 	if (rw == KSTAT_WRITE)
29309 		return (EACCES);
29310 
29311 	ns = netstack_find_by_stackid(stackid);
29312 	if (ns == NULL)
29313 		return (-1);
29314 	ipst = ns->netstack_ip;
29315 	if (ipst == NULL) {
29316 		netstack_rele(ns);
29317 		return (-1);
29318 	}
29319 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29320 
29321 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29322 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29323 	ill = ILL_START_WALK_V4(&ctx, ipst);
29324 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29325 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29326 	rw_exit(&ipst->ips_ill_g_lock);
29327 
29328 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29329 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29330 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29331 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29332 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29333 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29334 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29335 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29336 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29337 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29338 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29339 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29340 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29341 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29342 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29343 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29344 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29345 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29346 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29347 
29348 	ipkp->routingDiscards.value.ui32 =	0;
29349 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29350 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29351 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29352 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29353 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29354 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29355 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29356 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29357 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29358 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29359 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29360 
29361 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29362 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29363 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29364 
29365 	netstack_rele(ns);
29366 
29367 	return (0);
29368 }
29369 
29370 static void *
29371 icmp_kstat_init(netstackid_t stackid)
29372 {
29373 	kstat_t	*ksp;
29374 
29375 	icmp_named_kstat_t template = {
29376 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29377 		{ "inErrors",		KSTAT_DATA_UINT32 },
29378 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29379 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29380 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29381 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29382 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29383 		{ "inEchos",		KSTAT_DATA_UINT32 },
29384 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29385 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29386 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29387 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29388 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29389 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29390 		{ "outErrors",		KSTAT_DATA_UINT32 },
29391 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29392 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29393 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29394 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29395 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29396 		{ "outEchos",		KSTAT_DATA_UINT32 },
29397 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29398 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29399 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29400 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29401 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29402 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29403 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29404 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29405 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29406 		{ "outDrops",		KSTAT_DATA_UINT32 },
29407 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29408 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29409 	};
29410 
29411 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29412 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29413 	if (ksp == NULL || ksp->ks_data == NULL)
29414 		return (NULL);
29415 
29416 	bcopy(&template, ksp->ks_data, sizeof (template));
29417 
29418 	ksp->ks_update = icmp_kstat_update;
29419 	ksp->ks_private = (void *)(uintptr_t)stackid;
29420 
29421 	kstat_install(ksp);
29422 	return (ksp);
29423 }
29424 
29425 static void
29426 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29427 {
29428 	if (ksp != NULL) {
29429 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29430 		kstat_delete_netstack(ksp, stackid);
29431 	}
29432 }
29433 
29434 static int
29435 icmp_kstat_update(kstat_t *kp, int rw)
29436 {
29437 	icmp_named_kstat_t *icmpkp;
29438 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29439 	netstack_t	*ns;
29440 	ip_stack_t	*ipst;
29441 
29442 	if ((kp == NULL) || (kp->ks_data == NULL))
29443 		return (EIO);
29444 
29445 	if (rw == KSTAT_WRITE)
29446 		return (EACCES);
29447 
29448 	ns = netstack_find_by_stackid(stackid);
29449 	if (ns == NULL)
29450 		return (-1);
29451 	ipst = ns->netstack_ip;
29452 	if (ipst == NULL) {
29453 		netstack_rele(ns);
29454 		return (-1);
29455 	}
29456 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29457 
29458 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29459 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29460 	icmpkp->inDestUnreachs.value.ui32 =
29461 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29462 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29463 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29464 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29465 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29466 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29467 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29468 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29469 	icmpkp->inTimestampReps.value.ui32 =
29470 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29471 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29472 	icmpkp->inAddrMaskReps.value.ui32 =
29473 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29474 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29475 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29476 	icmpkp->outDestUnreachs.value.ui32 =
29477 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29478 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29479 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29480 	icmpkp->outSrcQuenchs.value.ui32 =
29481 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29482 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29483 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29484 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29485 	icmpkp->outTimestamps.value.ui32 =
29486 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29487 	icmpkp->outTimestampReps.value.ui32 =
29488 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29489 	icmpkp->outAddrMasks.value.ui32 =
29490 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29491 	icmpkp->outAddrMaskReps.value.ui32 =
29492 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29493 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29494 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29495 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29496 	icmpkp->outFragNeeded.value.ui32 =
29497 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29498 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29499 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29500 	icmpkp->inBadRedirects.value.ui32 =
29501 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29502 
29503 	netstack_rele(ns);
29504 	return (0);
29505 }
29506 
29507 /*
29508  * This is the fanout function for raw socket opened for SCTP.  Note
29509  * that it is called after SCTP checks that there is no socket which
29510  * wants a packet.  Then before SCTP handles this out of the blue packet,
29511  * this function is called to see if there is any raw socket for SCTP.
29512  * If there is and it is bound to the correct address, the packet will
29513  * be sent to that socket.  Note that only one raw socket can be bound to
29514  * a port.  This is assured in ipcl_sctp_hash_insert();
29515  */
29516 void
29517 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29518     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29519     zoneid_t zoneid)
29520 {
29521 	conn_t		*connp;
29522 	queue_t		*rq;
29523 	mblk_t		*first_mp;
29524 	boolean_t	secure;
29525 	ip6_t		*ip6h;
29526 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29527 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29528 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29529 	boolean_t	sctp_csum_err = B_FALSE;
29530 
29531 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29532 		sctp_csum_err = B_TRUE;
29533 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29534 	}
29535 
29536 	first_mp = mp;
29537 	if (mctl_present) {
29538 		mp = first_mp->b_cont;
29539 		secure = ipsec_in_is_secure(first_mp);
29540 		ASSERT(mp != NULL);
29541 	} else {
29542 		secure = B_FALSE;
29543 	}
29544 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29545 
29546 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29547 	if (connp == NULL) {
29548 		/*
29549 		 * Although raw sctp is not summed, OOB chunks must be.
29550 		 * Drop the packet here if the sctp checksum failed.
29551 		 */
29552 		if (sctp_csum_err) {
29553 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29554 			freemsg(first_mp);
29555 			return;
29556 		}
29557 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29558 		return;
29559 	}
29560 	rq = connp->conn_rq;
29561 	if (!canputnext(rq)) {
29562 		CONN_DEC_REF(connp);
29563 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29564 		freemsg(first_mp);
29565 		return;
29566 	}
29567 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29568 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29569 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29570 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29571 		if (first_mp == NULL) {
29572 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29573 			CONN_DEC_REF(connp);
29574 			return;
29575 		}
29576 	}
29577 	/*
29578 	 * We probably should not send M_CTL message up to
29579 	 * raw socket.
29580 	 */
29581 	if (mctl_present)
29582 		freeb(first_mp);
29583 
29584 	/* Initiate IPPF processing here if needed. */
29585 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29586 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29587 		ip_process(IPP_LOCAL_IN, &mp,
29588 		    recv_ill->ill_phyint->phyint_ifindex);
29589 		if (mp == NULL) {
29590 			CONN_DEC_REF(connp);
29591 			return;
29592 		}
29593 	}
29594 
29595 	if (connp->conn_recvif || connp->conn_recvslla ||
29596 	    ((connp->conn_ip_recvpktinfo ||
29597 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29598 	    (flags & IP_FF_IPINFO))) {
29599 		int in_flags = 0;
29600 
29601 		/*
29602 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29603 		 * IPF_RECVIF.
29604 		 */
29605 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29606 			in_flags = IPF_RECVIF;
29607 		}
29608 		if (connp->conn_recvslla) {
29609 			in_flags |= IPF_RECVSLLA;
29610 		}
29611 		if (isv4) {
29612 			mp = ip_add_info(mp, recv_ill, in_flags,
29613 			    IPCL_ZONEID(connp), ipst);
29614 		} else {
29615 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29616 			if (mp == NULL) {
29617 				BUMP_MIB(recv_ill->ill_ip_mib,
29618 				    ipIfStatsInDiscards);
29619 				CONN_DEC_REF(connp);
29620 				return;
29621 			}
29622 		}
29623 	}
29624 
29625 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29626 	/*
29627 	 * We are sending the IPSEC_IN message also up. Refer
29628 	 * to comments above this function.
29629 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29630 	 */
29631 	(connp->conn_recv)(connp, mp, NULL);
29632 	CONN_DEC_REF(connp);
29633 }
29634 
29635 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29636 {									\
29637 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29638 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29639 }
29640 /*
29641  * This function should be called only if all packet processing
29642  * including fragmentation is complete. Callers of this function
29643  * must set mp->b_prev to one of these values:
29644  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29645  * prior to handing over the mp as first argument to this function.
29646  *
29647  * If the ire passed by caller is incomplete, this function
29648  * queues the packet and if necessary, sends ARP request and bails.
29649  * If the ire passed is fully resolved, we simply prepend
29650  * the link-layer header to the packet, do ipsec hw acceleration
29651  * work if necessary, and send the packet out on the wire.
29652  *
29653  * NOTE: IPsec will only call this function with fully resolved
29654  * ires if hw acceleration is involved.
29655  * TODO list :
29656  * 	a Handle M_MULTIDATA so that
29657  *	  tcp_multisend->tcp_multisend_data can
29658  *	  call ip_xmit_v4 directly
29659  *	b Handle post-ARP work for fragments so that
29660  *	  ip_wput_frag can call this function.
29661  */
29662 ipxmit_state_t
29663 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29664     boolean_t flow_ctl_enabled, conn_t *connp)
29665 {
29666 	nce_t		*arpce;
29667 	ipha_t		*ipha;
29668 	queue_t		*q;
29669 	int		ill_index;
29670 	mblk_t		*nxt_mp, *first_mp;
29671 	boolean_t	xmit_drop = B_FALSE;
29672 	ip_proc_t	proc;
29673 	ill_t		*out_ill;
29674 	int		pkt_len;
29675 
29676 	arpce = ire->ire_nce;
29677 	ASSERT(arpce != NULL);
29678 
29679 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29680 
29681 	mutex_enter(&arpce->nce_lock);
29682 	switch (arpce->nce_state) {
29683 	case ND_REACHABLE:
29684 		/* If there are other queued packets, queue this packet */
29685 		if (arpce->nce_qd_mp != NULL) {
29686 			if (mp != NULL)
29687 				nce_queue_mp_common(arpce, mp, B_FALSE);
29688 			mp = arpce->nce_qd_mp;
29689 		}
29690 		arpce->nce_qd_mp = NULL;
29691 		mutex_exit(&arpce->nce_lock);
29692 
29693 		/*
29694 		 * Flush the queue.  In the common case, where the
29695 		 * ARP is already resolved,  it will go through the
29696 		 * while loop only once.
29697 		 */
29698 		while (mp != NULL) {
29699 
29700 			nxt_mp = mp->b_next;
29701 			mp->b_next = NULL;
29702 			ASSERT(mp->b_datap->db_type != M_CTL);
29703 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29704 			/*
29705 			 * This info is needed for IPQOS to do COS marking
29706 			 * in ip_wput_attach_llhdr->ip_process.
29707 			 */
29708 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29709 			mp->b_prev = NULL;
29710 
29711 			/* set up ill index for outbound qos processing */
29712 			out_ill = ire_to_ill(ire);
29713 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29714 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29715 			    ill_index, &ipha);
29716 			if (first_mp == NULL) {
29717 				xmit_drop = B_TRUE;
29718 				BUMP_MIB(out_ill->ill_ip_mib,
29719 				    ipIfStatsOutDiscards);
29720 				goto next_mp;
29721 			}
29722 
29723 			/* non-ipsec hw accel case */
29724 			if (io == NULL || !io->ipsec_out_accelerated) {
29725 				/* send it */
29726 				q = ire->ire_stq;
29727 				if (proc == IPP_FWD_OUT) {
29728 					UPDATE_IB_PKT_COUNT(ire);
29729 				} else {
29730 					UPDATE_OB_PKT_COUNT(ire);
29731 				}
29732 				ire->ire_last_used_time = lbolt;
29733 
29734 				if (flow_ctl_enabled || canputnext(q)) {
29735 					if (proc == IPP_FWD_OUT) {
29736 
29737 					BUMP_MIB(out_ill->ill_ip_mib,
29738 					    ipIfStatsHCOutForwDatagrams);
29739 
29740 					}
29741 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29742 					    pkt_len);
29743 
29744 					DTRACE_IP7(send, mblk_t *, first_mp,
29745 					    conn_t *, NULL, void_ip_t *, ipha,
29746 					    __dtrace_ipsr_ill_t *, out_ill,
29747 					    ipha_t *, ipha, ip6_t *, NULL, int,
29748 					    0);
29749 
29750 					ILL_SEND_TX(out_ill,
29751 					    ire, connp, first_mp, 0, connp);
29752 				} else {
29753 					BUMP_MIB(out_ill->ill_ip_mib,
29754 					    ipIfStatsOutDiscards);
29755 					xmit_drop = B_TRUE;
29756 					freemsg(first_mp);
29757 				}
29758 			} else {
29759 				/*
29760 				 * Safety Pup says: make sure this
29761 				 *  is going to the right interface!
29762 				 */
29763 				ill_t *ill1 =
29764 				    (ill_t *)ire->ire_stq->q_ptr;
29765 				int ifindex =
29766 				    ill1->ill_phyint->phyint_ifindex;
29767 				if (ifindex !=
29768 				    io->ipsec_out_capab_ill_index) {
29769 					xmit_drop = B_TRUE;
29770 					freemsg(mp);
29771 				} else {
29772 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29773 					    pkt_len);
29774 
29775 					DTRACE_IP7(send, mblk_t *, first_mp,
29776 					    conn_t *, NULL, void_ip_t *, ipha,
29777 					    __dtrace_ipsr_ill_t *, ill1,
29778 					    ipha_t *, ipha, ip6_t *, NULL,
29779 					    int, 0);
29780 
29781 					ipsec_hw_putnext(ire->ire_stq, mp);
29782 				}
29783 			}
29784 next_mp:
29785 			mp = nxt_mp;
29786 		} /* while (mp != NULL) */
29787 		if (xmit_drop)
29788 			return (SEND_FAILED);
29789 		else
29790 			return (SEND_PASSED);
29791 
29792 	case ND_INITIAL:
29793 	case ND_INCOMPLETE:
29794 
29795 		/*
29796 		 * While we do send off packets to dests that
29797 		 * use fully-resolved CGTP routes, we do not
29798 		 * handle unresolved CGTP routes.
29799 		 */
29800 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29801 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29802 
29803 		if (mp != NULL) {
29804 			/* queue the packet */
29805 			nce_queue_mp_common(arpce, mp, B_FALSE);
29806 		}
29807 
29808 		if (arpce->nce_state == ND_INCOMPLETE) {
29809 			mutex_exit(&arpce->nce_lock);
29810 			DTRACE_PROBE3(ip__xmit__incomplete,
29811 			    (ire_t *), ire, (mblk_t *), mp,
29812 			    (ipsec_out_t *), io);
29813 			return (LOOKUP_IN_PROGRESS);
29814 		}
29815 
29816 		arpce->nce_state = ND_INCOMPLETE;
29817 		mutex_exit(&arpce->nce_lock);
29818 
29819 		/*
29820 		 * Note that ire_add() (called from ire_forward())
29821 		 * holds a ref on the ire until ARP is completed.
29822 		 */
29823 		ire_arpresolve(ire);
29824 		return (LOOKUP_IN_PROGRESS);
29825 	default:
29826 		ASSERT(0);
29827 		mutex_exit(&arpce->nce_lock);
29828 		return (LLHDR_RESLV_FAILED);
29829 	}
29830 }
29831 
29832 #undef	UPDATE_IP_MIB_OB_COUNTERS
29833 
29834 /*
29835  * Return B_TRUE if the buffers differ in length or content.
29836  * This is used for comparing extension header buffers.
29837  * Note that an extension header would be declared different
29838  * even if all that changed was the next header value in that header i.e.
29839  * what really changed is the next extension header.
29840  */
29841 boolean_t
29842 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29843     uint_t blen)
29844 {
29845 	if (!b_valid)
29846 		blen = 0;
29847 
29848 	if (alen != blen)
29849 		return (B_TRUE);
29850 	if (alen == 0)
29851 		return (B_FALSE);	/* Both zero length */
29852 	return (bcmp(abuf, bbuf, alen));
29853 }
29854 
29855 /*
29856  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29857  * Return B_FALSE if memory allocation fails - don't change any state!
29858  */
29859 boolean_t
29860 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29861     const void *src, uint_t srclen)
29862 {
29863 	void *dst;
29864 
29865 	if (!src_valid)
29866 		srclen = 0;
29867 
29868 	ASSERT(*dstlenp == 0);
29869 	if (src != NULL && srclen != 0) {
29870 		dst = mi_alloc(srclen, BPRI_MED);
29871 		if (dst == NULL)
29872 			return (B_FALSE);
29873 	} else {
29874 		dst = NULL;
29875 	}
29876 	if (*dstp != NULL)
29877 		mi_free(*dstp);
29878 	*dstp = dst;
29879 	*dstlenp = dst == NULL ? 0 : srclen;
29880 	return (B_TRUE);
29881 }
29882 
29883 /*
29884  * Replace what is in *dst, *dstlen with the source.
29885  * Assumes ip_allocbuf has already been called.
29886  */
29887 void
29888 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29889     const void *src, uint_t srclen)
29890 {
29891 	if (!src_valid)
29892 		srclen = 0;
29893 
29894 	ASSERT(*dstlenp == srclen);
29895 	if (src != NULL && srclen != 0)
29896 		bcopy(src, *dstp, srclen);
29897 }
29898 
29899 /*
29900  * Free the storage pointed to by the members of an ip6_pkt_t.
29901  */
29902 void
29903 ip6_pkt_free(ip6_pkt_t *ipp)
29904 {
29905 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29906 
29907 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29908 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29909 		ipp->ipp_hopopts = NULL;
29910 		ipp->ipp_hopoptslen = 0;
29911 	}
29912 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29913 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29914 		ipp->ipp_rtdstopts = NULL;
29915 		ipp->ipp_rtdstoptslen = 0;
29916 	}
29917 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29918 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29919 		ipp->ipp_dstopts = NULL;
29920 		ipp->ipp_dstoptslen = 0;
29921 	}
29922 	if (ipp->ipp_fields & IPPF_RTHDR) {
29923 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29924 		ipp->ipp_rthdr = NULL;
29925 		ipp->ipp_rthdrlen = 0;
29926 	}
29927 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29928 	    IPPF_RTHDR);
29929 }
29930 
29931 zoneid_t
29932 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29933     zoneid_t lookup_zoneid)
29934 {
29935 	ire_t		*ire;
29936 	int		ire_flags = MATCH_IRE_TYPE;
29937 	zoneid_t	zoneid = ALL_ZONES;
29938 
29939 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29940 		return (ALL_ZONES);
29941 
29942 	if (lookup_zoneid != ALL_ZONES)
29943 		ire_flags |= MATCH_IRE_ZONEONLY;
29944 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29945 	    lookup_zoneid, NULL, ire_flags, ipst);
29946 	if (ire != NULL) {
29947 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29948 		ire_refrele(ire);
29949 	}
29950 	return (zoneid);
29951 }
29952 
29953 zoneid_t
29954 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29955     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29956 {
29957 	ire_t		*ire;
29958 	int		ire_flags = MATCH_IRE_TYPE;
29959 	zoneid_t	zoneid = ALL_ZONES;
29960 	ipif_t		*ipif_arg = NULL;
29961 
29962 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29963 		return (ALL_ZONES);
29964 
29965 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29966 		ire_flags |= MATCH_IRE_ILL;
29967 		ipif_arg = ill->ill_ipif;
29968 	}
29969 	if (lookup_zoneid != ALL_ZONES)
29970 		ire_flags |= MATCH_IRE_ZONEONLY;
29971 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29972 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29973 	if (ire != NULL) {
29974 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29975 		ire_refrele(ire);
29976 	}
29977 	return (zoneid);
29978 }
29979 
29980 /*
29981  * IP obserability hook support functions.
29982  */
29983 
29984 static void
29985 ipobs_init(ip_stack_t *ipst)
29986 {
29987 	ipst->ips_ipobs_enabled = B_FALSE;
29988 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
29989 	    offsetof(ipobs_cb_t, ipobs_cbnext));
29990 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
29991 	ipst->ips_ipobs_cb_nwalkers = 0;
29992 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
29993 }
29994 
29995 static void
29996 ipobs_fini(ip_stack_t *ipst)
29997 {
29998 	ipobs_cb_t *cb;
29999 
30000 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30001 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30002 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30003 
30004 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30005 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30006 		kmem_free(cb, sizeof (*cb));
30007 	}
30008 	list_destroy(&ipst->ips_ipobs_cb_list);
30009 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30010 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30011 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30012 }
30013 
30014 void
30015 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30016     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30017 {
30018 	mblk_t *mp2;
30019 	ipobs_cb_t *ipobs_cb;
30020 	ipobs_hook_data_t *ihd;
30021 	uint64_t grifindex = 0;
30022 
30023 	ASSERT(DB_TYPE(mp) == M_DATA);
30024 
30025 	if (IS_UNDER_IPMP(ill))
30026 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30027 
30028 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30029 	ipst->ips_ipobs_cb_nwalkers++;
30030 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30031 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30032 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30033 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30034 		if (mp2 != NULL) {
30035 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30036 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30037 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30038 				freemsg(mp2);
30039 				continue;
30040 			}
30041 			ihd->ihd_mp->b_rptr += hlen;
30042 			ihd->ihd_htype = htype;
30043 			ihd->ihd_ipver = ipver;
30044 			ihd->ihd_zsrc = zsrc;
30045 			ihd->ihd_zdst = zdst;
30046 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30047 			ihd->ihd_grifindex = grifindex;
30048 			ihd->ihd_stack = ipst->ips_netstack;
30049 			mp2->b_wptr += sizeof (*ihd);
30050 			ipobs_cb->ipobs_cbfunc(mp2);
30051 		}
30052 	}
30053 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30054 	ipst->ips_ipobs_cb_nwalkers--;
30055 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30056 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30057 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30058 }
30059 
30060 void
30061 ipobs_register_hook(netstack_t *ns, pfv_t func)
30062 {
30063 	ipobs_cb_t   *cb;
30064 	ip_stack_t *ipst = ns->netstack_ip;
30065 
30066 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30067 
30068 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30069 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30070 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30071 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30072 
30073 	cb->ipobs_cbfunc = func;
30074 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30075 	ipst->ips_ipobs_enabled = B_TRUE;
30076 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30077 }
30078 
30079 void
30080 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30081 {
30082 	ipobs_cb_t	*curcb;
30083 	ip_stack_t	*ipst = ns->netstack_ip;
30084 
30085 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30086 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30087 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30088 
30089 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30090 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30091 		if (func == curcb->ipobs_cbfunc) {
30092 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30093 			kmem_free(curcb, sizeof (*curcb));
30094 			break;
30095 		}
30096 	}
30097 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30098 		ipst->ips_ipobs_enabled = B_FALSE;
30099 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30100 }
30101