xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 98c507c4288789fc67365c4cb51f80eb641e7182)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/iptun/iptun_impl.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 #include <inet/ilb_ip.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <inet/rawip_impl.h>
122 #include <inet/rts_impl.h>
123 
124 #include <sys/tsol/label.h>
125 #include <sys/tsol/tnet.h>
126 
127 #include <rpc/pmap_prot.h>
128 #include <sys/squeue_impl.h>
129 
130 /*
131  * Values for squeue switch:
132  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
133  * IP_SQUEUE_ENTER: SQ_PROCESS
134  * IP_SQUEUE_FILL: SQ_FILL
135  */
136 int ip_squeue_enter = 2;	/* Setable in /etc/system */
137 
138 int ip_squeue_flag;
139 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
140 
141 /*
142  * Setable in /etc/system
143  */
144 int ip_poll_normal_ms = 100;
145 int ip_poll_normal_ticks = 0;
146 int ip_modclose_ackwait_ms = 3000;
147 
148 /*
149  * It would be nice to have these present only in DEBUG systems, but the
150  * current design of the global symbol checking logic requires them to be
151  * unconditionally present.
152  */
153 uint_t ip_thread_data;			/* TSD key for debug support */
154 krwlock_t ip_thread_rwlock;
155 list_t	ip_thread_list;
156 
157 /*
158  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
159  */
160 
161 struct listptr_s {
162 	mblk_t	*lp_head;	/* pointer to the head of the list */
163 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
164 };
165 
166 typedef struct listptr_s listptr_t;
167 
168 /*
169  * This is used by ip_snmp_get_mib2_ip_route_media and
170  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
171  */
172 typedef struct iproutedata_s {
173 	uint_t		ird_idx;
174 	uint_t		ird_flags;	/* see below */
175 	listptr_t	ird_route;	/* ipRouteEntryTable */
176 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
177 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
178 } iproutedata_t;
179 
180 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
181 
182 /*
183  * Cluster specific hooks. These should be NULL when booted as a non-cluster
184  */
185 
186 /*
187  * Hook functions to enable cluster networking
188  * On non-clustered systems these vectors must always be NULL.
189  *
190  * Hook function to Check ip specified ip address is a shared ip address
191  * in the cluster
192  *
193  */
194 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
195     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
196 
197 /*
198  * Hook function to generate cluster wide ip fragment identifier
199  */
200 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
201     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
202     void *args) = NULL;
203 
204 /*
205  * Hook function to generate cluster wide SPI.
206  */
207 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
208     void *) = NULL;
209 
210 /*
211  * Hook function to verify if the SPI is already utlized.
212  */
213 
214 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
215 
216 /*
217  * Hook function to delete the SPI from the cluster wide repository.
218  */
219 
220 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
221 
222 /*
223  * Hook function to inform the cluster when packet received on an IDLE SA
224  */
225 
226 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
227     in6_addr_t, in6_addr_t, void *) = NULL;
228 
229 /*
230  * Synchronization notes:
231  *
232  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
233  * MT level protection given by STREAMS. IP uses a combination of its own
234  * internal serialization mechanism and standard Solaris locking techniques.
235  * The internal serialization is per phyint.  This is used to serialize
236  * plumbing operations, certain multicast operations, most set ioctls,
237  * igmp/mld timers etc.
238  *
239  * Plumbing is a long sequence of operations involving message
240  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
241  * involved in plumbing operations. A natural model is to serialize these
242  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
243  * parallel without any interference. But various set ioctls on hme0 are best
244  * serialized, along with multicast join/leave operations, igmp/mld timer
245  * operations, and processing of DLPI control messages received from drivers
246  * on a per phyint basis.  This serialization is provided by the ipsq_t and
247  * primitives operating on this. Details can be found in ip_if.c above the
248  * core primitives operating on ipsq_t.
249  *
250  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
251  * Simiarly lookup of an ire by a thread also returns a refheld ire.
252  * In addition ipif's and ill's referenced by the ire are also indirectly
253  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
254  * the ipif's address or netmask change as long as an ipif is refheld
255  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
256  * address of an ipif has to go through the ipsq_t. This ensures that only
257  * 1 such exclusive operation proceeds at any time on the ipif. It then
258  * deletes all ires associated with this ipif, and waits for all refcnts
259  * associated with this ipif to come down to zero. The address is changed
260  * only after the ipif has been quiesced. Then the ipif is brought up again.
261  * More details are described above the comment in ip_sioctl_flags.
262  *
263  * Packet processing is based mostly on IREs and are fully multi-threaded
264  * using standard Solaris MT techniques.
265  *
266  * There are explicit locks in IP to handle:
267  * - The ip_g_head list maintained by mi_open_link() and friends.
268  *
269  * - The reassembly data structures (one lock per hash bucket)
270  *
271  * - conn_lock is meant to protect conn_t fields. The fields actually
272  *   protected by conn_lock are documented in the conn_t definition.
273  *
274  * - ire_lock to protect some of the fields of the ire, IRE tables
275  *   (one lock per hash bucket). Refer to ip_ire.c for details.
276  *
277  * - ndp_g_lock and nce_lock for protecting NCEs.
278  *
279  * - ill_lock protects fields of the ill and ipif. Details in ip.h
280  *
281  * - ill_g_lock: This is a global reader/writer lock. Protects the following
282  *	* The AVL tree based global multi list of all ills.
283  *	* The linked list of all ipifs of an ill
284  *	* The <ipsq-xop> mapping
285  *	* <ill-phyint> association
286  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
287  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
288  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
289  *   writer for the actual duration of the insertion/deletion/change.
290  *
291  * - ill_lock:  This is a per ill mutex.
292  *   It protects some members of the ill_t struct; see ip.h for details.
293  *   It also protects the <ill-phyint> assoc.
294  *   It also protects the list of ipifs hanging off the ill.
295  *
296  * - ipsq_lock: This is a per ipsq_t mutex lock.
297  *   This protects some members of the ipsq_t struct; see ip.h for details.
298  *   It also protects the <ipsq-ipxop> mapping
299  *
300  * - ipx_lock: This is a per ipxop_t mutex lock.
301  *   This protects some members of the ipxop_t struct; see ip.h for details.
302  *
303  * - phyint_lock: This is a per phyint mutex lock. Protects just the
304  *   phyint_flags
305  *
306  * - ip_g_nd_lock: This is a global reader/writer lock.
307  *   Any call to nd_load to load a new parameter to the ND table must hold the
308  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
309  *   as reader.
310  *
311  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
312  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
313  *   uniqueness check also done atomically.
314  *
315  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
316  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
317  *   as a writer when adding or deleting elements from these lists, and
318  *   as a reader when walking these lists to send a SADB update to the
319  *   IPsec capable ills.
320  *
321  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
322  *   group list linked by ill_usesrc_grp_next. It also protects the
323  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
324  *   group is being added or deleted.  This lock is taken as a reader when
325  *   walking the list/group(eg: to get the number of members in a usesrc group).
326  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
327  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
328  *   example, it is not necessary to take this lock in the initial portion
329  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
330  *   operations are executed exclusively and that ensures that the "usesrc
331  *   group state" cannot change. The "usesrc group state" change can happen
332  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
333  *
334  * Changing <ill-phyint>, <ipsq-xop> assocications:
335  *
336  * To change the <ill-phyint> association, the ill_g_lock must be held
337  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
338  * must be held.
339  *
340  * To change the <ipsq-xop> association, the ill_g_lock must be held as
341  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
342  * This is only done when ills are added or removed from IPMP groups.
343  *
344  * To add or delete an ipif from the list of ipifs hanging off the ill,
345  * ill_g_lock (writer) and ill_lock must be held and the thread must be
346  * a writer on the associated ipsq.
347  *
348  * To add or delete an ill to the system, the ill_g_lock must be held as
349  * writer and the thread must be a writer on the associated ipsq.
350  *
351  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
352  * must be a writer on the associated ipsq.
353  *
354  * Lock hierarchy
355  *
356  * Some lock hierarchy scenarios are listed below.
357  *
358  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
359  * ill_g_lock -> ill_lock(s) -> phyint_lock
360  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
361  * ill_g_lock -> ip_addr_avail_lock
362  * conn_lock -> irb_lock -> ill_lock -> ire_lock
363  * ill_g_lock -> ip_g_nd_lock
364  *
365  * When more than 1 ill lock is needed to be held, all ill lock addresses
366  * are sorted on address and locked starting from highest addressed lock
367  * downward.
368  *
369  * IPsec scenarios
370  *
371  * ipsa_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
373  * ipsec_capab_ills_lock -> ipsa_lock
374  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
375  *
376  * Trusted Solaris scenarios
377  *
378  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
379  * igsa_lock -> gcdb_lock
380  * gcgrp_rwlock -> ire_lock
381  * gcgrp_rwlock -> gcdb_lock
382  *
383  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
384  *
385  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
386  * sq_lock -> conn_lock -> QLOCK(q)
387  * ill_lock -> ft_lock -> fe_lock
388  *
389  * Routing/forwarding table locking notes:
390  *
391  * Lock acquisition order: Radix tree lock, irb_lock.
392  * Requirements:
393  * i.  Walker must not hold any locks during the walker callback.
394  * ii  Walker must not see a truncated tree during the walk because of any node
395  *     deletion.
396  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
397  *     in many places in the code to walk the irb list. Thus even if all the
398  *     ires in a bucket have been deleted, we still can't free the radix node
399  *     until the ires have actually been inactive'd (freed).
400  *
401  * Tree traversal - Need to hold the global tree lock in read mode.
402  * Before dropping the global tree lock, need to either increment the ire_refcnt
403  * to ensure that the radix node can't be deleted.
404  *
405  * Tree add - Need to hold the global tree lock in write mode to add a
406  * radix node. To prevent the node from being deleted, increment the
407  * irb_refcnt, after the node is added to the tree. The ire itself is
408  * added later while holding the irb_lock, but not the tree lock.
409  *
410  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
411  * All associated ires must be inactive (i.e. freed), and irb_refcnt
412  * must be zero.
413  *
414  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
415  * global tree lock (read mode) for traversal.
416  *
417  * IPsec notes :
418  *
419  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
420  * in front of the actual packet. For outbound datagrams, the M_CTL
421  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
422  * information used by the IPsec code for applying the right level of
423  * protection. The information initialized by IP in the ipsec_out_t
424  * is determined by the per-socket policy or global policy in the system.
425  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
426  * ipsec_info.h) which starts out with nothing in it. It gets filled
427  * with the right information if it goes through the AH/ESP code, which
428  * happens if the incoming packet is secure. The information initialized
429  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
430  * the policy requirements needed by per-socket policy or global policy
431  * is met or not.
432  *
433  * If there is both per-socket policy (set using setsockopt) and there
434  * is also global policy match for the 5 tuples of the socket,
435  * ipsec_override_policy() makes the decision of which one to use.
436  *
437  * For fully connected sockets i.e dst, src [addr, port] is known,
438  * conn_policy_cached is set indicating that policy has been cached.
439  * conn_in_enforce_policy may or may not be set depending on whether
440  * there is a global policy match or per-socket policy match.
441  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
442  * Once the right policy is set on the conn_t, policy cannot change for
443  * this socket. This makes life simpler for TCP (UDP ?) where
444  * re-transmissions go out with the same policy. For symmetry, policy
445  * is cached for fully connected UDP sockets also. Thus if policy is cached,
446  * it also implies that policy is latched i.e policy cannot change
447  * on these sockets. As we have the right policy on the conn, we don't
448  * have to lookup global policy for every outbound and inbound datagram
449  * and thus serving as an optimization. Note that a global policy change
450  * does not affect fully connected sockets if they have policy. If fully
451  * connected sockets did not have any policy associated with it, global
452  * policy change may affect them.
453  *
454  * IP Flow control notes:
455  * ---------------------
456  * Non-TCP streams are flow controlled by IP. The way this is accomplished
457  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
458  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
459  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
460  * functions.
461  *
462  * Per Tx ring udp flow control:
463  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
464  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
465  *
466  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
467  * To achieve best performance, outgoing traffic need to be fanned out among
468  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
469  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
470  * the address of connp as fanout hint to mac_tx(). Under flow controlled
471  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
472  * cookie points to a specific Tx ring that is blocked. The cookie is used to
473  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
474  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
475  * connp's. The drain list is not a single list but a configurable number of
476  * lists.
477  *
478  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
479  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
480  * which is equal to 128. This array in turn contains a pointer to idl_t[],
481  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
482  * list will point to the list of connp's that are flow controlled.
483  *
484  *                      ---------------   -------   -------   -------
485  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
486  *                   |  ---------------   -------   -------   -------
487  *                   |  ---------------   -------   -------   -------
488  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
489  * ----------------  |  ---------------   -------   -------   -------
490  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
491  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
492  *                   |  ---------------   -------   -------   -------
493  *                   .        .              .         .         .
494  *                   |  ---------------   -------   -------   -------
495  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
496  *                      ---------------   -------   -------   -------
497  *                      ---------------   -------   -------   -------
498  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
499  *                   |  ---------------   -------   -------   -------
500  *                   |  ---------------   -------   -------   -------
501  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
502  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
503  * ----------------  |        .              .         .         .
504  *                   |  ---------------   -------   -------   -------
505  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
506  *                      ---------------   -------   -------   -------
507  *     .....
508  * ----------------
509  * |idl_tx_list[n]|-> ...
510  * ----------------
511  *
512  * When mac_tx() returns a cookie, the cookie is used to hash into a
513  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
514  * called passing idl_tx_list. The connp gets inserted in a drain list
515  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
516  * the sockets (non stream based) and sets QFULL condition for conn_wq.
517  * connp->conn_direct_blocked will be set to indicate the blocked
518  * condition.
519  *
520  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
521  * A cookie is passed in the call to ill_flow_enable() that identifies the
522  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
523  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
524  * and goes through each of the drain list (q)enabling the conn_wq of the
525  * first conn in each of the drain list. This causes ip_wsrv to run for the
526  * conn. ip_wsrv drains the queued messages, and removes the conn from the
527  * drain list, if all messages were drained. It also qenables the next conn
528  * in the drain list to continue the drain process.
529  *
530  * In reality the drain list is not a single list, but a configurable number
531  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
532  * each list. If the ip_wsrv of the next qenabled conn does not run, because
533  * the stream closes, ip_close takes responsibility to qenable the next conn
534  * in the drain list. conn_drain_insert and conn_drain_tail are the only
535  * functions that manipulate this drain list. conn_drain_insert is called in
536  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
537  * case -- see below). The synchronization between drain insertion and flow
538  * control wakeup is handled by using idl_txl->txl_lock.
539  *
540  * Flow control using STREAMS:
541  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
542  * is used. On the send side, if the packet cannot be sent down to the
543  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
544  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
545  * the conn in a list of conn's that need to be drained when the flow
546  * control condition subsides. The blocked connps are put in first member
547  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
548  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
549  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
550  * conn_wq of the first conn in the drain lists is (q)enabled to run.
551  * ip_wsrv on this conn drains the queued messages, and removes the conn
552  * from the drain list, if all messages were drained. It also qenables the
553  * next conn in the drain list to continue the drain process.
554  *
555  * If the ip_wsrv of the next qenabled conn does not run, because the
556  * stream closes, ip_close takes responsibility to qenable the next conn in
557  * the drain list. The directly called ip_wput path always does a putq, if
558  * it cannot putnext. Thus synchronization problems are handled between
559  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
560  * functions that manipulate this drain list. Furthermore conn_drain_insert
561  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
562  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
563  * be simultaneously called from both ip_wsrv and ip_close.
564  *
565  * IPQOS notes:
566  *
567  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
568  * and IPQoS modules. IPPF includes hooks in IP at different control points
569  * (callout positions) which direct packets to IPQoS modules for policy
570  * processing. Policies, if present, are global.
571  *
572  * The callout positions are located in the following paths:
573  *		o local_in (packets destined for this host)
574  *		o local_out (packets orginating from this host )
575  *		o fwd_in  (packets forwarded by this m/c - inbound)
576  *		o fwd_out (packets forwarded by this m/c - outbound)
577  * Hooks at these callout points can be enabled/disabled using the ndd variable
578  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
579  * By default all the callout positions are enabled.
580  *
581  * Outbound (local_out)
582  * Hooks are placed in ip_wput_ire and ipsec_out_process.
583  *
584  * Inbound (local_in)
585  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
586  * TCP and UDP fanout routines.
587  *
588  * Forwarding (in and out)
589  * Hooks are placed in ip_rput_forward.
590  *
591  * IP Policy Framework processing (IPPF processing)
592  * Policy processing for a packet is initiated by ip_process, which ascertains
593  * that the classifier (ipgpc) is loaded and configured, failing which the
594  * packet resumes normal processing in IP. If the clasifier is present, the
595  * packet is acted upon by one or more IPQoS modules (action instances), per
596  * filters configured in ipgpc and resumes normal IP processing thereafter.
597  * An action instance can drop a packet in course of its processing.
598  *
599  * A boolean variable, ip_policy, is used in all the fanout routines that can
600  * invoke ip_process for a packet. This variable indicates if the packet should
601  * to be sent for policy processing. The variable is set to B_TRUE by default,
602  * i.e. when the routines are invoked in the normal ip procesing path for a
603  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
604  * ip_policy is set to B_FALSE for all the routines called in these two
605  * functions because, in the former case,  we don't process loopback traffic
606  * currently while in the latter, the packets have already been processed in
607  * icmp_inbound.
608  *
609  * Zones notes:
610  *
611  * The partitioning rules for networking are as follows:
612  * 1) Packets coming from a zone must have a source address belonging to that
613  * zone.
614  * 2) Packets coming from a zone can only be sent on a physical interface on
615  * which the zone has an IP address.
616  * 3) Between two zones on the same machine, packet delivery is only allowed if
617  * there's a matching route for the destination and zone in the forwarding
618  * table.
619  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
620  * different zones can bind to the same port with the wildcard address
621  * (INADDR_ANY).
622  *
623  * The granularity of interface partitioning is at the logical interface level.
624  * Therefore, every zone has its own IP addresses, and incoming packets can be
625  * attributed to a zone unambiguously. A logical interface is placed into a zone
626  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
627  * structure. Rule (1) is implemented by modifying the source address selection
628  * algorithm so that the list of eligible addresses is filtered based on the
629  * sending process zone.
630  *
631  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
632  * across all zones, depending on their type. Here is the break-up:
633  *
634  * IRE type				Shared/exclusive
635  * --------				----------------
636  * IRE_BROADCAST			Exclusive
637  * IRE_DEFAULT (default routes)		Shared (*)
638  * IRE_LOCAL				Exclusive (x)
639  * IRE_LOOPBACK				Exclusive
640  * IRE_PREFIX (net routes)		Shared (*)
641  * IRE_CACHE				Exclusive
642  * IRE_IF_NORESOLVER (interface routes)	Exclusive
643  * IRE_IF_RESOLVER (interface routes)	Exclusive
644  * IRE_HOST (host routes)		Shared (*)
645  *
646  * (*) A zone can only use a default or off-subnet route if the gateway is
647  * directly reachable from the zone, that is, if the gateway's address matches
648  * one of the zone's logical interfaces.
649  *
650  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
651  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
652  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
653  * address of the zone itself (the destination). Since IRE_LOCAL is used
654  * for communication between zones, ip_wput_ire has special logic to set
655  * the right source address when sending using an IRE_LOCAL.
656  *
657  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
658  * ire_cache_lookup restricts loopback using an IRE_LOCAL
659  * between zone to the case when L2 would have conceptually looped the packet
660  * back, i.e. the loopback which is required since neither Ethernet drivers
661  * nor Ethernet hardware loops them back. This is the case when the normal
662  * routes (ignoring IREs with different zoneids) would send out the packet on
663  * the same ill as the ill with which is IRE_LOCAL is associated.
664  *
665  * Multiple zones can share a common broadcast address; typically all zones
666  * share the 255.255.255.255 address. Incoming as well as locally originated
667  * broadcast packets must be dispatched to all the zones on the broadcast
668  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
669  * since some zones may not be on the 10.16.72/24 network. To handle this, each
670  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
671  * sent to every zone that has an IRE_BROADCAST entry for the destination
672  * address on the input ill, see conn_wantpacket().
673  *
674  * Applications in different zones can join the same multicast group address.
675  * For IPv4, group memberships are per-logical interface, so they're already
676  * inherently part of a zone. For IPv6, group memberships are per-physical
677  * interface, so we distinguish IPv6 group memberships based on group address,
678  * interface and zoneid. In both cases, received multicast packets are sent to
679  * every zone for which a group membership entry exists. On IPv6 we need to
680  * check that the target zone still has an address on the receiving physical
681  * interface; it could have been removed since the application issued the
682  * IPV6_JOIN_GROUP.
683  */
684 
685 /*
686  * Squeue Fanout flags:
687  *	0: No fanout.
688  *	1: Fanout across all squeues
689  */
690 boolean_t	ip_squeue_fanout = 0;
691 
692 /*
693  * Maximum dups allowed per packet.
694  */
695 uint_t ip_max_frag_dups = 10;
696 
697 #define	IS_SIMPLE_IPH(ipha)						\
698 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
699 
700 /* RFC 1122 Conformance */
701 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
702 
703 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
704 
705 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
706 
707 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
708 		    cred_t *credp, boolean_t isv6);
709 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
710 		    ipha_t **);
711 
712 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
713 		    ip_stack_t *);
714 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
715 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
716 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
717 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
718 		    mblk_t *, int, ip_stack_t *);
719 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
720 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
721 		    ill_t *, zoneid_t);
722 static void	icmp_options_update(ipha_t *);
723 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
724 		    ip_stack_t *);
725 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
726 		    zoneid_t zoneid, ip_stack_t *);
727 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
728 static void	icmp_redirect(ill_t *, mblk_t *);
729 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
730 		    ip_stack_t *);
731 
732 static void	ip_arp_news(queue_t *, mblk_t *);
733 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
734 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
735 char		*ip_dot_addr(ipaddr_t, char *);
736 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
737 int		ip_close(queue_t *, int);
738 static char	*ip_dot_saddr(uchar_t *, char *);
739 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
740 		    boolean_t, boolean_t, ill_t *, zoneid_t);
741 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
742 		    boolean_t, boolean_t, zoneid_t);
743 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
744 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
745 static void	ip_lrput(queue_t *, mblk_t *);
746 ipaddr_t	ip_net_mask(ipaddr_t);
747 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
748 		    ip_stack_t *);
749 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
750 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
751 char		*ip_nv_lookup(nv_t *, int);
752 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
753 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
755 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
756     ipndp_t *, size_t);
757 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
758 void	ip_rput(queue_t *, mblk_t *);
759 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
760 		    void *dummy_arg);
761 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
762 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
763     ip_stack_t *);
764 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
765 			    ire_t *, ip_stack_t *);
766 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
767 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
768 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
769     ip_stack_t *);
770 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
771     uint32_t *, uint16_t *);
772 int		ip_snmp_get(queue_t *, mblk_t *, int);
773 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
774 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
776 		    ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
778 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
782 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
783 		    ip_stack_t *ipst);
784 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
785 		    ip_stack_t *ipst);
786 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
787 		    ip_stack_t *ipst);
788 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
789 		    ip_stack_t *ipst);
790 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
791 		    ip_stack_t *ipst);
792 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
793 		    ip_stack_t *ipst);
794 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
795 		    ip_stack_t *ipst);
796 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
797 		    ip_stack_t *ipst);
798 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
799 		    ip_stack_t *ipst);
800 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
801 		    ip_stack_t *ipst);
802 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
803 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
804 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
805 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
806 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
807 static boolean_t	ip_source_route_included(ipha_t *);
808 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
809 
810 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
811 		    zoneid_t, ip_stack_t *, conn_t *);
812 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
813 		    mblk_t *);
814 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
815 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
816 		    zoneid_t, ip_stack_t *);
817 
818 static void	conn_drain_init(ip_stack_t *);
819 static void	conn_drain_fini(ip_stack_t *);
820 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
821 
822 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
823 static void	conn_setqfull(conn_t *);
824 static void	conn_clrqfull(conn_t *);
825 
826 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
827 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
828 static void	ip_stack_fini(netstackid_t stackid, void *arg);
829 
830 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
831     zoneid_t);
832 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
833     void *dummy_arg);
834 
835 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
836 
837 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
838     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
839     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
840 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
841 
842 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
843 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
844     caddr_t, cred_t *);
845 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
846     cred_t *, boolean_t);
847 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
848     caddr_t cp, cred_t *cr);
849 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
850     cred_t *);
851 static int	ip_squeue_switch(int);
852 
853 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
854 static void	ip_kstat_fini(netstackid_t, kstat_t *);
855 static int	ip_kstat_update(kstat_t *kp, int rw);
856 static void	*icmp_kstat_init(netstackid_t);
857 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
858 static int	icmp_kstat_update(kstat_t *kp, int rw);
859 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
860 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
861 
862 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
863     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
864 
865 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
866     ipha_t *, ill_t *, boolean_t, boolean_t);
867 
868 static void ipobs_init(ip_stack_t *);
869 static void ipobs_fini(ip_stack_t *);
870 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
871 
872 /* How long, in seconds, we allow frags to hang around. */
873 #define	IP_FRAG_TIMEOUT		15
874 #define	IPV6_FRAG_TIMEOUT	60
875 
876 /*
877  * Threshold which determines whether MDT should be used when
878  * generating IP fragments; payload size must be greater than
879  * this threshold for MDT to take place.
880  */
881 #define	IP_WPUT_FRAG_MDT_MIN	32768
882 
883 /* Setable in /etc/system only */
884 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
885 
886 static long ip_rput_pullups;
887 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
888 
889 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
890 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
891 
892 int	ip_debug;
893 
894 #ifdef DEBUG
895 uint32_t ipsechw_debug = 0;
896 #endif
897 
898 /*
899  * Multirouting/CGTP stuff
900  */
901 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
902 
903 /*
904  * XXX following really should only be in a header. Would need more
905  * header and .c clean up first.
906  */
907 extern optdb_obj_t	ip_opt_obj;
908 
909 ulong_t ip_squeue_enter_unbound = 0;
910 
911 /*
912  * Named Dispatch Parameter Table.
913  * All of these are alterable, within the min/max values given, at run time.
914  */
915 static ipparam_t	lcl_param_arr[] = {
916 	/* min	max	value	name */
917 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
918 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
919 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
920 	{  0,	1,	0,	"ip_respond_to_timestamp"},
921 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
922 	{  0,	1,	1,	"ip_send_redirects"},
923 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
924 	{  0,	10,	0,	"ip_mrtdebug"},
925 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
926 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
927 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
928 	{  1,	255,	255,	"ip_def_ttl" },
929 	{  0,	1,	0,	"ip_forward_src_routed"},
930 	{  0,	256,	32,	"ip_wroff_extra" },
931 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
932 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
933 	{  0,	1,	1,	"ip_path_mtu_discovery" },
934 	{  0,	240,	30,	"ip_ignore_delete_time" },
935 	{  0,	1,	0,	"ip_ignore_redirect" },
936 	{  0,	1,	1,	"ip_output_queue" },
937 	{  1,	254,	1,	"ip_broadcast_ttl" },
938 	{  0,	99999,	100,	"ip_icmp_err_interval" },
939 	{  1,	99999,	10,	"ip_icmp_err_burst" },
940 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
941 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
942 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
943 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
944 	{  0,	1,	1,	"icmp_accept_clear_messages" },
945 	{  0,	1,	1,	"igmp_accept_clear_messages" },
946 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
947 				"ip_ndp_delay_first_probe_time"},
948 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
949 				"ip_ndp_max_unicast_solicit"},
950 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
951 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
952 	{  0,	1,	0,	"ip6_forward_src_routed"},
953 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
954 	{  0,	1,	1,	"ip6_send_redirects"},
955 	{  0,	1,	0,	"ip6_ignore_redirect" },
956 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
957 
958 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
959 
960 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
961 
962 	{  0,	1,	1,	"pim_accept_clear_messages" },
963 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
964 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
965 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
966 	{  0,	15,	0,	"ip_policy_mask" },
967 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
968 	{  0,	255,	1,	"ip_multirt_ttl" },
969 	{  0,	1,	1,	"ip_multidata_outbound" },
970 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
971 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
972 	{  0,	1000,	1,	"ip_max_temp_defend" },
973 	{  0,	1000,	3,	"ip_max_defend" },
974 	{  0,	999999,	30,	"ip_defend_interval" },
975 	{  0,	3600000, 300000, "ip_dup_recovery" },
976 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
977 	{  0,	1,	1,	"ip_lso_outbound" },
978 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
979 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
980 	{ 68,	65535,	576,	"ip_pmtu_min" },
981 #ifdef DEBUG
982 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
983 #else
984 	{  0,	0,	0,	"" },
985 #endif
986 };
987 
988 /*
989  * Extended NDP table
990  * The addresses for the first two are filled in to be ips_ip_g_forward
991  * and ips_ipv6_forward at init time.
992  */
993 static ipndp_t	lcl_ndp_arr[] = {
994 	/* getf			setf		data			name */
995 #define	IPNDP_IP_FORWARDING_OFFSET	0
996 	{  ip_param_generic_get,	ip_forward_set,	NULL,
997 	    "ip_forwarding" },
998 #define	IPNDP_IP6_FORWARDING_OFFSET	1
999 	{  ip_param_generic_get,	ip_forward_set,	NULL,
1000 	    "ip6_forwarding" },
1001 	{ ip_param_generic_get, ip_input_proc_set,
1002 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1003 	{ ip_param_generic_get, ip_int_set,
1004 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1005 #define	IPNDP_CGTP_FILTER_OFFSET	4
1006 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1007 	    "ip_cgtp_filter" },
1008 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1009 	    "ip_debug" },
1010 };
1011 
1012 /*
1013  * Table of IP ioctls encoding the various properties of the ioctl and
1014  * indexed based on the last byte of the ioctl command. Occasionally there
1015  * is a clash, and there is more than 1 ioctl with the same last byte.
1016  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1017  * ioctls are encoded in the misc table. An entry in the ndx table is
1018  * retrieved by indexing on the last byte of the ioctl command and comparing
1019  * the ioctl command with the value in the ndx table. In the event of a
1020  * mismatch the misc table is then searched sequentially for the desired
1021  * ioctl command.
1022  *
1023  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1024  */
1025 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1026 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 
1037 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1038 			MISC_CMD, ip_siocaddrt, NULL },
1039 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1040 			MISC_CMD, ip_siocdelrt, NULL },
1041 
1042 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1043 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1044 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1045 			IF_CMD, ip_sioctl_get_addr, NULL },
1046 
1047 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1048 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1049 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1050 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1051 
1052 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1053 			IPI_PRIV | IPI_WR,
1054 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1055 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1056 			IPI_MODOK | IPI_GET_CMD,
1057 			IF_CMD, ip_sioctl_get_flags, NULL },
1058 
1059 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 
1062 	/* copyin size cannot be coded for SIOCGIFCONF */
1063 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1064 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1065 
1066 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1067 			IF_CMD, ip_sioctl_mtu, NULL },
1068 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1069 			IF_CMD, ip_sioctl_get_mtu, NULL },
1070 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1071 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1072 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1073 			IF_CMD, ip_sioctl_brdaddr, NULL },
1074 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1075 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1076 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1077 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1078 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1079 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1080 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1081 			IF_CMD, ip_sioctl_metric, NULL },
1082 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 
1084 	/* See 166-168 below for extended SIOC*XARP ioctls */
1085 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1086 			ARP_CMD, ip_sioctl_arp, NULL },
1087 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1088 			ARP_CMD, ip_sioctl_arp, NULL },
1089 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1090 			ARP_CMD, ip_sioctl_arp, NULL },
1091 
1092 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 
1114 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1115 			MISC_CMD, if_unitsel, if_unitsel_restart },
1116 
1117 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 
1136 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1137 			IPI_PRIV | IPI_WR | IPI_MODOK,
1138 			IF_CMD, ip_sioctl_sifname, NULL },
1139 
1140 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 
1154 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1155 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1156 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1157 			IF_CMD, ip_sioctl_get_muxid, NULL },
1158 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1159 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1160 
1161 	/* Both if and lif variants share same func */
1162 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1163 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1164 	/* Both if and lif variants share same func */
1165 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1166 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1167 
1168 	/* copyin size cannot be coded for SIOCGIFCONF */
1169 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1170 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1171 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 
1189 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1190 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1191 			ip_sioctl_removeif_restart },
1192 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1193 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1194 			LIF_CMD, ip_sioctl_addif, NULL },
1195 #define	SIOCLIFADDR_NDX 112
1196 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1197 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1198 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1199 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1200 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1201 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1202 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1203 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1204 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1205 			IPI_PRIV | IPI_WR,
1206 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1207 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1208 			IPI_GET_CMD | IPI_MODOK,
1209 			LIF_CMD, ip_sioctl_get_flags, NULL },
1210 
1211 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1213 
1214 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1215 			ip_sioctl_get_lifconf, NULL },
1216 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1217 			LIF_CMD, ip_sioctl_mtu, NULL },
1218 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1219 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1220 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1221 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1222 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1223 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1224 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1225 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1226 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1227 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1228 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1229 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1230 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1231 			LIF_CMD, ip_sioctl_metric, NULL },
1232 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1233 			IPI_PRIV | IPI_WR | IPI_MODOK,
1234 			LIF_CMD, ip_sioctl_slifname,
1235 			ip_sioctl_slifname_restart },
1236 
1237 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1238 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1239 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1240 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1241 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1242 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1243 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1244 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1245 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1246 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1247 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1248 			LIF_CMD, ip_sioctl_token, NULL },
1249 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1250 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1251 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1252 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1253 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1254 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1255 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1256 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1257 
1258 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1259 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1260 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1261 			LIF_CMD, ip_siocdelndp_v6, NULL },
1262 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1263 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1264 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1265 			LIF_CMD, ip_siocsetndp_v6, NULL },
1266 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1267 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1268 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1269 			MISC_CMD, ip_sioctl_tonlink, NULL },
1270 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1271 			MISC_CMD, ip_sioctl_tmysite, NULL },
1272 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1273 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1274 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1275 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1276 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1277 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1278 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1279 
1280 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1281 
1282 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1283 			LIF_CMD, ip_sioctl_get_binding, NULL },
1284 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1285 			IPI_PRIV | IPI_WR,
1286 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1287 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1288 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1289 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1290 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1291 
1292 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1293 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1294 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1295 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1296 
1297 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 
1299 	/* These are handled in ip_sioctl_copyin_setup itself */
1300 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1301 			MISC_CMD, NULL, NULL },
1302 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1303 			MISC_CMD, NULL, NULL },
1304 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1305 
1306 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1307 			ip_sioctl_get_lifconf, NULL },
1308 
1309 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1310 			XARP_CMD, ip_sioctl_arp, NULL },
1311 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1312 			XARP_CMD, ip_sioctl_arp, NULL },
1313 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1314 			XARP_CMD, ip_sioctl_arp, NULL },
1315 
1316 	/* SIOCPOPSOCKFS is not handled by IP */
1317 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1318 
1319 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1320 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1321 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1322 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1323 			ip_sioctl_slifzone_restart },
1324 	/* 172-174 are SCTP ioctls and not handled by IP */
1325 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1326 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1327 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1328 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1329 			IPI_GET_CMD, LIF_CMD,
1330 			ip_sioctl_get_lifusesrc, 0 },
1331 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1332 			IPI_PRIV | IPI_WR,
1333 			LIF_CMD, ip_sioctl_slifusesrc,
1334 			NULL },
1335 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1336 			ip_sioctl_get_lifsrcof, NULL },
1337 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1338 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1339 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1340 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1341 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1342 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1343 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1344 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1345 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1346 	/* SIOCSENABLESDP is handled by SDP */
1347 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1348 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1349 	/* 185 */ { IPI_DONTCARE /* SIOCGIFHWADDR */, 0, 0, 0, NULL, NULL },
1350 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1351 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1352 			ip_sioctl_ilb_cmd, NULL },
1353 };
1354 
1355 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1356 
1357 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1358 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1359 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1360 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1361 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1362 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1363 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1364 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1365 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1366 		MISC_CMD, mrt_ioctl},
1367 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1368 		MISC_CMD, mrt_ioctl},
1369 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1370 		MISC_CMD, mrt_ioctl}
1371 };
1372 
1373 int ip_misc_ioctl_count =
1374     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1375 
1376 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1377 					/* Settable in /etc/system */
1378 /* Defined in ip_ire.c */
1379 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1380 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1381 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1382 
1383 static nv_t	ire_nv_arr[] = {
1384 	{ IRE_BROADCAST, "BROADCAST" },
1385 	{ IRE_LOCAL, "LOCAL" },
1386 	{ IRE_LOOPBACK, "LOOPBACK" },
1387 	{ IRE_CACHE, "CACHE" },
1388 	{ IRE_DEFAULT, "DEFAULT" },
1389 	{ IRE_PREFIX, "PREFIX" },
1390 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1391 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1392 	{ IRE_HOST, "HOST" },
1393 	{ 0 }
1394 };
1395 
1396 nv_t	*ire_nv_tbl = ire_nv_arr;
1397 
1398 /* Simple ICMP IP Header Template */
1399 static ipha_t icmp_ipha = {
1400 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1401 };
1402 
1403 struct module_info ip_mod_info = {
1404 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1405 	IP_MOD_LOWAT
1406 };
1407 
1408 /*
1409  * Duplicate static symbols within a module confuses mdb; so we avoid the
1410  * problem by making the symbols here distinct from those in udp.c.
1411  */
1412 
1413 /*
1414  * Entry points for IP as a device and as a module.
1415  * FIXME: down the road we might want a separate module and driver qinit.
1416  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1417  */
1418 static struct qinit iprinitv4 = {
1419 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1420 	&ip_mod_info
1421 };
1422 
1423 struct qinit iprinitv6 = {
1424 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1425 	&ip_mod_info
1426 };
1427 
1428 static struct qinit ipwinitv4 = {
1429 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1430 	&ip_mod_info
1431 };
1432 
1433 struct qinit ipwinitv6 = {
1434 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1435 	&ip_mod_info
1436 };
1437 
1438 static struct qinit iplrinit = {
1439 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1440 	&ip_mod_info
1441 };
1442 
1443 static struct qinit iplwinit = {
1444 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1445 	&ip_mod_info
1446 };
1447 
1448 /* For AF_INET aka /dev/ip */
1449 struct streamtab ipinfov4 = {
1450 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1451 };
1452 
1453 /* For AF_INET6 aka /dev/ip6 */
1454 struct streamtab ipinfov6 = {
1455 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1456 };
1457 
1458 #ifdef	DEBUG
1459 static boolean_t skip_sctp_cksum = B_FALSE;
1460 #endif
1461 
1462 /*
1463  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1464  * ip_rput_v6(), ip_output(), etc.  If the message
1465  * block already has a M_CTL at the front of it, then simply set the zoneid
1466  * appropriately.
1467  */
1468 mblk_t *
1469 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1470 {
1471 	mblk_t		*first_mp;
1472 	ipsec_out_t	*io;
1473 
1474 	ASSERT(zoneid != ALL_ZONES);
1475 	if (mp->b_datap->db_type == M_CTL) {
1476 		io = (ipsec_out_t *)mp->b_rptr;
1477 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1478 		io->ipsec_out_zoneid = zoneid;
1479 		return (mp);
1480 	}
1481 
1482 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1483 	if (first_mp == NULL)
1484 		return (NULL);
1485 	io = (ipsec_out_t *)first_mp->b_rptr;
1486 	/* This is not a secure packet */
1487 	io->ipsec_out_secure = B_FALSE;
1488 	io->ipsec_out_zoneid = zoneid;
1489 	first_mp->b_cont = mp;
1490 	return (first_mp);
1491 }
1492 
1493 /*
1494  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1495  */
1496 mblk_t *
1497 ip_copymsg(mblk_t *mp)
1498 {
1499 	mblk_t *nmp;
1500 	ipsec_info_t *in;
1501 
1502 	if (mp->b_datap->db_type != M_CTL)
1503 		return (copymsg(mp));
1504 
1505 	in = (ipsec_info_t *)mp->b_rptr;
1506 
1507 	/*
1508 	 * Note that M_CTL is also used for delivering ICMP error messages
1509 	 * upstream to transport layers.
1510 	 */
1511 	if (in->ipsec_info_type != IPSEC_OUT &&
1512 	    in->ipsec_info_type != IPSEC_IN)
1513 		return (copymsg(mp));
1514 
1515 	nmp = copymsg(mp->b_cont);
1516 
1517 	if (in->ipsec_info_type == IPSEC_OUT) {
1518 		return (ipsec_out_tag(mp, nmp,
1519 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1520 	} else {
1521 		return (ipsec_in_tag(mp, nmp,
1522 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1523 	}
1524 }
1525 
1526 /* Generate an ICMP fragmentation needed message. */
1527 static void
1528 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1529     ip_stack_t *ipst)
1530 {
1531 	icmph_t	icmph;
1532 	mblk_t *first_mp;
1533 	boolean_t mctl_present;
1534 
1535 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1536 
1537 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1538 		if (mctl_present)
1539 			freeb(first_mp);
1540 		return;
1541 	}
1542 
1543 	bzero(&icmph, sizeof (icmph_t));
1544 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1545 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1546 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1547 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1548 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1549 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1550 	    ipst);
1551 }
1552 
1553 /*
1554  * icmp_inbound deals with ICMP messages in the following ways.
1555  *
1556  * 1) It needs to send a reply back and possibly delivering it
1557  *    to the "interested" upper clients.
1558  * 2) It needs to send it to the upper clients only.
1559  * 3) It needs to change some values in IP only.
1560  * 4) It needs to change some values in IP and upper layers e.g TCP.
1561  *
1562  * We need to accomodate icmp messages coming in clear until we get
1563  * everything secure from the wire. If icmp_accept_clear_messages
1564  * is zero we check with the global policy and act accordingly. If
1565  * it is non-zero, we accept the message without any checks. But
1566  * *this does not mean* that this will be delivered to the upper
1567  * clients. By accepting we might send replies back, change our MTU
1568  * value etc. but delivery to the ULP/clients depends on their policy
1569  * dispositions.
1570  *
1571  * We handle the above 4 cases in the context of IPsec in the
1572  * following way :
1573  *
1574  * 1) Send the reply back in the same way as the request came in.
1575  *    If it came in encrypted, it goes out encrypted. If it came in
1576  *    clear, it goes out in clear. Thus, this will prevent chosen
1577  *    plain text attack.
1578  * 2) The client may or may not expect things to come in secure.
1579  *    If it comes in secure, the policy constraints are checked
1580  *    before delivering it to the upper layers. If it comes in
1581  *    clear, ipsec_inbound_accept_clear will decide whether to
1582  *    accept this in clear or not. In both the cases, if the returned
1583  *    message (IP header + 8 bytes) that caused the icmp message has
1584  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1585  *    sending up. If there are only 8 bytes of returned message, then
1586  *    upper client will not be notified.
1587  * 3) Check with global policy to see whether it matches the constaints.
1588  *    But this will be done only if icmp_accept_messages_in_clear is
1589  *    zero.
1590  * 4) If we need to change both in IP and ULP, then the decision taken
1591  *    while affecting the values in IP and while delivering up to TCP
1592  *    should be the same.
1593  *
1594  * 	There are two cases.
1595  *
1596  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1597  *	   failed), we will not deliver it to the ULP, even though they
1598  *	   are *willing* to accept in *clear*. This is fine as our global
1599  *	   disposition to icmp messages asks us reject the datagram.
1600  *
1601  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1602  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1603  *	   to deliver it to ULP (policy failed), it can lead to
1604  *	   consistency problems. The cases known at this time are
1605  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1606  *	   values :
1607  *
1608  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1609  *	     and Upper layer rejects. Then the communication will
1610  *	     come to a stop. This is solved by making similar decisions
1611  *	     at both levels. Currently, when we are unable to deliver
1612  *	     to the Upper Layer (due to policy failures) while IP has
1613  *	     adjusted ire_max_frag, the next outbound datagram would
1614  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1615  *	     will be with the right level of protection. Thus the right
1616  *	     value will be communicated even if we are not able to
1617  *	     communicate when we get from the wire initially. But this
1618  *	     assumes there would be at least one outbound datagram after
1619  *	     IP has adjusted its ire_max_frag value. To make things
1620  *	     simpler, we accept in clear after the validation of
1621  *	     AH/ESP headers.
1622  *
1623  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1624  *	     upper layer depending on the level of protection the upper
1625  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1626  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1627  *	     should be accepted in clear when the Upper layer expects secure.
1628  *	     Thus the communication may get aborted by some bad ICMP
1629  *	     packets.
1630  *
1631  * IPQoS Notes:
1632  * The only instance when a packet is sent for processing is when there
1633  * isn't an ICMP client and if we are interested in it.
1634  * If there is a client, IPPF processing will take place in the
1635  * ip_fanout_proto routine.
1636  *
1637  * Zones notes:
1638  * The packet is only processed in the context of the specified zone: typically
1639  * only this zone will reply to an echo request, and only interested clients in
1640  * this zone will receive a copy of the packet. This means that the caller must
1641  * call icmp_inbound() for each relevant zone.
1642  */
1643 static void
1644 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1645     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1646     ill_t *recv_ill, zoneid_t zoneid)
1647 {
1648 	icmph_t	*icmph;
1649 	ipha_t	*ipha;
1650 	int	iph_hdr_length;
1651 	int	hdr_length;
1652 	boolean_t	interested;
1653 	uint32_t	ts;
1654 	uchar_t	*wptr;
1655 	ipif_t	*ipif;
1656 	mblk_t *first_mp;
1657 	ipsec_in_t *ii;
1658 	timestruc_t now;
1659 	uint32_t ill_index;
1660 	ip_stack_t *ipst;
1661 
1662 	ASSERT(ill != NULL);
1663 	ipst = ill->ill_ipst;
1664 
1665 	first_mp = mp;
1666 	if (mctl_present) {
1667 		mp = first_mp->b_cont;
1668 		ASSERT(mp != NULL);
1669 	}
1670 
1671 	ipha = (ipha_t *)mp->b_rptr;
1672 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1673 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1674 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1675 		if (first_mp == NULL)
1676 			return;
1677 	}
1678 
1679 	/*
1680 	 * On a labeled system, we have to check whether the zone itself is
1681 	 * permitted to receive raw traffic.
1682 	 */
1683 	if (is_system_labeled()) {
1684 		if (zoneid == ALL_ZONES)
1685 			zoneid = tsol_packet_to_zoneid(mp);
1686 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1687 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1688 			    zoneid));
1689 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1690 			freemsg(first_mp);
1691 			return;
1692 		}
1693 	}
1694 
1695 	/*
1696 	 * We have accepted the ICMP message. It means that we will
1697 	 * respond to the packet if needed. It may not be delivered
1698 	 * to the upper client depending on the policy constraints
1699 	 * and the disposition in ipsec_inbound_accept_clear.
1700 	 */
1701 
1702 	ASSERT(ill != NULL);
1703 
1704 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1705 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1706 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1707 		/* Last chance to get real. */
1708 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1709 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1710 			freemsg(first_mp);
1711 			return;
1712 		}
1713 		/* Refresh iph following the pullup. */
1714 		ipha = (ipha_t *)mp->b_rptr;
1715 	}
1716 	/* ICMP header checksum, including checksum field, should be zero. */
1717 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1718 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1719 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1720 		freemsg(first_mp);
1721 		return;
1722 	}
1723 	/* The IP header will always be a multiple of four bytes */
1724 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1725 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1726 	    icmph->icmph_code));
1727 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1728 	/* We will set "interested" to "true" if we want a copy */
1729 	interested = B_FALSE;
1730 	switch (icmph->icmph_type) {
1731 	case ICMP_ECHO_REPLY:
1732 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1733 		break;
1734 	case ICMP_DEST_UNREACHABLE:
1735 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1736 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1737 		interested = B_TRUE;	/* Pass up to transport */
1738 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1739 		break;
1740 	case ICMP_SOURCE_QUENCH:
1741 		interested = B_TRUE;	/* Pass up to transport */
1742 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1743 		break;
1744 	case ICMP_REDIRECT:
1745 		if (!ipst->ips_ip_ignore_redirect)
1746 			interested = B_TRUE;
1747 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1748 		break;
1749 	case ICMP_ECHO_REQUEST:
1750 		/*
1751 		 * Whether to respond to echo requests that come in as IP
1752 		 * broadcasts or as IP multicast is subject to debate
1753 		 * (what isn't?).  We aim to please, you pick it.
1754 		 * Default is do it.
1755 		 */
1756 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1757 			/* unicast: always respond */
1758 			interested = B_TRUE;
1759 		} else if (CLASSD(ipha->ipha_dst)) {
1760 			/* multicast: respond based on tunable */
1761 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1762 		} else if (broadcast) {
1763 			/* broadcast: respond based on tunable */
1764 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1765 		}
1766 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1767 		break;
1768 	case ICMP_ROUTER_ADVERTISEMENT:
1769 	case ICMP_ROUTER_SOLICITATION:
1770 		break;
1771 	case ICMP_TIME_EXCEEDED:
1772 		interested = B_TRUE;	/* Pass up to transport */
1773 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1774 		break;
1775 	case ICMP_PARAM_PROBLEM:
1776 		interested = B_TRUE;	/* Pass up to transport */
1777 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1778 		break;
1779 	case ICMP_TIME_STAMP_REQUEST:
1780 		/* Response to Time Stamp Requests is local policy. */
1781 		if (ipst->ips_ip_g_resp_to_timestamp &&
1782 		    /* So is whether to respond if it was an IP broadcast. */
1783 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1784 			int tstamp_len = 3 * sizeof (uint32_t);
1785 
1786 			if (wptr +  tstamp_len > mp->b_wptr) {
1787 				if (!pullupmsg(mp, wptr + tstamp_len -
1788 				    mp->b_rptr)) {
1789 					BUMP_MIB(ill->ill_ip_mib,
1790 					    ipIfStatsInDiscards);
1791 					freemsg(first_mp);
1792 					return;
1793 				}
1794 				/* Refresh ipha following the pullup. */
1795 				ipha = (ipha_t *)mp->b_rptr;
1796 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1797 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1798 			}
1799 			interested = B_TRUE;
1800 		}
1801 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1802 		break;
1803 	case ICMP_TIME_STAMP_REPLY:
1804 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1805 		break;
1806 	case ICMP_INFO_REQUEST:
1807 		/* Per RFC 1122 3.2.2.7, ignore this. */
1808 	case ICMP_INFO_REPLY:
1809 		break;
1810 	case ICMP_ADDRESS_MASK_REQUEST:
1811 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1812 		    !broadcast) &&
1813 		    /* TODO m_pullup of complete header? */
1814 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1815 			interested = B_TRUE;
1816 		}
1817 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1818 		break;
1819 	case ICMP_ADDRESS_MASK_REPLY:
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1821 		break;
1822 	default:
1823 		interested = B_TRUE;	/* Pass up to transport */
1824 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1825 		break;
1826 	}
1827 	/* See if there is an ICMP client. */
1828 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1829 		/* If there is an ICMP client and we want one too, copy it. */
1830 		mblk_t *first_mp1;
1831 
1832 		if (!interested) {
1833 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1834 			    ip_policy, recv_ill, zoneid);
1835 			return;
1836 		}
1837 		first_mp1 = ip_copymsg(first_mp);
1838 		if (first_mp1 != NULL) {
1839 			ip_fanout_proto(q, first_mp1, ill, ipha,
1840 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1841 		}
1842 	} else if (!interested) {
1843 		freemsg(first_mp);
1844 		return;
1845 	} else {
1846 		/*
1847 		 * Initiate policy processing for this packet if ip_policy
1848 		 * is true.
1849 		 */
1850 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1851 			ill_index = ill->ill_phyint->phyint_ifindex;
1852 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1853 			if (mp == NULL) {
1854 				if (mctl_present) {
1855 					freeb(first_mp);
1856 				}
1857 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1858 				return;
1859 			}
1860 		}
1861 	}
1862 	/* We want to do something with it. */
1863 	/* Check db_ref to make sure we can modify the packet. */
1864 	if (mp->b_datap->db_ref > 1) {
1865 		mblk_t	*first_mp1;
1866 
1867 		first_mp1 = ip_copymsg(first_mp);
1868 		freemsg(first_mp);
1869 		if (!first_mp1) {
1870 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1871 			return;
1872 		}
1873 		first_mp = first_mp1;
1874 		if (mctl_present) {
1875 			mp = first_mp->b_cont;
1876 			ASSERT(mp != NULL);
1877 		} else {
1878 			mp = first_mp;
1879 		}
1880 		ipha = (ipha_t *)mp->b_rptr;
1881 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1882 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1883 	}
1884 	switch (icmph->icmph_type) {
1885 	case ICMP_ADDRESS_MASK_REQUEST:
1886 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1887 		if (ipif == NULL) {
1888 			freemsg(first_mp);
1889 			return;
1890 		}
1891 		/*
1892 		 * outging interface must be IPv4
1893 		 */
1894 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1895 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1896 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1897 		ipif_refrele(ipif);
1898 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1899 		break;
1900 	case ICMP_ECHO_REQUEST:
1901 		icmph->icmph_type = ICMP_ECHO_REPLY;
1902 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1903 		break;
1904 	case ICMP_TIME_STAMP_REQUEST: {
1905 		uint32_t *tsp;
1906 
1907 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1908 		tsp = (uint32_t *)wptr;
1909 		tsp++;		/* Skip past 'originate time' */
1910 		/* Compute # of milliseconds since midnight */
1911 		gethrestime(&now);
1912 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1913 		    now.tv_nsec / (NANOSEC / MILLISEC);
1914 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1915 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1916 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1917 		break;
1918 	}
1919 	default:
1920 		ipha = (ipha_t *)&icmph[1];
1921 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1922 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1923 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1924 				freemsg(first_mp);
1925 				return;
1926 			}
1927 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1928 			ipha = (ipha_t *)&icmph[1];
1929 		}
1930 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1931 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1932 			freemsg(first_mp);
1933 			return;
1934 		}
1935 		hdr_length = IPH_HDR_LENGTH(ipha);
1936 		if (hdr_length < sizeof (ipha_t)) {
1937 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1938 			freemsg(first_mp);
1939 			return;
1940 		}
1941 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1942 			if (!pullupmsg(mp,
1943 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1944 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1945 				freemsg(first_mp);
1946 				return;
1947 			}
1948 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1949 			ipha = (ipha_t *)&icmph[1];
1950 		}
1951 		switch (icmph->icmph_type) {
1952 		case ICMP_REDIRECT:
1953 			/*
1954 			 * As there is no upper client to deliver, we don't
1955 			 * need the first_mp any more.
1956 			 */
1957 			if (mctl_present) {
1958 				freeb(first_mp);
1959 			}
1960 			icmp_redirect(ill, mp);
1961 			return;
1962 		case ICMP_DEST_UNREACHABLE:
1963 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1964 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1965 				    zoneid, mp, iph_hdr_length, ipst)) {
1966 					freemsg(first_mp);
1967 					return;
1968 				}
1969 				/*
1970 				 * icmp_inbound_too_big() may alter mp.
1971 				 * Resynch ipha and icmph accordingly.
1972 				 */
1973 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1974 				ipha = (ipha_t *)&icmph[1];
1975 			}
1976 			/* FALLTHRU */
1977 		default :
1978 			/*
1979 			 * IPQoS notes: Since we have already done IPQoS
1980 			 * processing we don't want to do it again in
1981 			 * the fanout routines called by
1982 			 * icmp_inbound_error_fanout, hence the last
1983 			 * argument, ip_policy, is B_FALSE.
1984 			 */
1985 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1986 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1987 			    B_FALSE, recv_ill, zoneid);
1988 		}
1989 		return;
1990 	}
1991 	/* Send out an ICMP packet */
1992 	icmph->icmph_checksum = 0;
1993 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1994 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1995 		ipif_t	*ipif_chosen;
1996 		/*
1997 		 * Make it look like it was directed to us, so we don't look
1998 		 * like a fool with a broadcast or multicast source address.
1999 		 */
2000 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2001 		/*
2002 		 * Make sure that we haven't grabbed an interface that's DOWN.
2003 		 */
2004 		if (ipif != NULL) {
2005 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2006 			    ipha->ipha_src, zoneid);
2007 			if (ipif_chosen != NULL) {
2008 				ipif_refrele(ipif);
2009 				ipif = ipif_chosen;
2010 			}
2011 		}
2012 		if (ipif == NULL) {
2013 			ip0dbg(("icmp_inbound: "
2014 			    "No source for broadcast/multicast:\n"
2015 			    "\tsrc 0x%x dst 0x%x ill %p "
2016 			    "ipif_lcl_addr 0x%x\n",
2017 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2018 			    (void *)ill,
2019 			    ill->ill_ipif->ipif_lcl_addr));
2020 			freemsg(first_mp);
2021 			return;
2022 		}
2023 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2024 		ipha->ipha_dst = ipif->ipif_src_addr;
2025 		ipif_refrele(ipif);
2026 	}
2027 	/* Reset time to live. */
2028 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2029 	{
2030 		/* Swap source and destination addresses */
2031 		ipaddr_t tmp;
2032 
2033 		tmp = ipha->ipha_src;
2034 		ipha->ipha_src = ipha->ipha_dst;
2035 		ipha->ipha_dst = tmp;
2036 	}
2037 	ipha->ipha_ident = 0;
2038 	if (!IS_SIMPLE_IPH(ipha))
2039 		icmp_options_update(ipha);
2040 
2041 	if (!mctl_present) {
2042 		/*
2043 		 * This packet should go out the same way as it
2044 		 * came in i.e in clear. To make sure that global
2045 		 * policy will not be applied to this in ip_wput_ire,
2046 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2047 		 */
2048 		ASSERT(first_mp == mp);
2049 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2050 		if (first_mp == NULL) {
2051 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2052 			freemsg(mp);
2053 			return;
2054 		}
2055 		ii = (ipsec_in_t *)first_mp->b_rptr;
2056 
2057 		/* This is not a secure packet */
2058 		ii->ipsec_in_secure = B_FALSE;
2059 		first_mp->b_cont = mp;
2060 	} else {
2061 		ii = (ipsec_in_t *)first_mp->b_rptr;
2062 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2063 	}
2064 	if (!ipsec_in_to_out(first_mp, ipha, NULL, zoneid)) {
2065 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2066 		return;
2067 	}
2068 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2069 	put(WR(q), first_mp);
2070 }
2071 
2072 static ipaddr_t
2073 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2074 {
2075 	conn_t *connp;
2076 	connf_t *connfp;
2077 	ipaddr_t nexthop_addr = INADDR_ANY;
2078 	int hdr_length = IPH_HDR_LENGTH(ipha);
2079 	uint16_t *up;
2080 	uint32_t ports;
2081 	ip_stack_t *ipst = ill->ill_ipst;
2082 
2083 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2084 	switch (ipha->ipha_protocol) {
2085 		case IPPROTO_TCP:
2086 		{
2087 			tcph_t *tcph;
2088 
2089 			/* do a reverse lookup */
2090 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2091 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2092 			    TCPS_LISTEN, ipst);
2093 			break;
2094 		}
2095 		case IPPROTO_UDP:
2096 		{
2097 			uint32_t dstport, srcport;
2098 
2099 			((uint16_t *)&ports)[0] = up[1];
2100 			((uint16_t *)&ports)[1] = up[0];
2101 
2102 			/* Extract ports in net byte order */
2103 			dstport = htons(ntohl(ports) & 0xFFFF);
2104 			srcport = htons(ntohl(ports) >> 16);
2105 
2106 			connfp = &ipst->ips_ipcl_udp_fanout[
2107 			    IPCL_UDP_HASH(dstport, ipst)];
2108 			mutex_enter(&connfp->connf_lock);
2109 			connp = connfp->connf_head;
2110 
2111 			/* do a reverse lookup */
2112 			while ((connp != NULL) &&
2113 			    (!IPCL_UDP_MATCH(connp, dstport,
2114 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2115 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2116 				connp = connp->conn_next;
2117 			}
2118 			if (connp != NULL)
2119 				CONN_INC_REF(connp);
2120 			mutex_exit(&connfp->connf_lock);
2121 			break;
2122 		}
2123 		case IPPROTO_SCTP:
2124 		{
2125 			in6_addr_t map_src, map_dst;
2126 
2127 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2128 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2129 			((uint16_t *)&ports)[0] = up[1];
2130 			((uint16_t *)&ports)[1] = up[0];
2131 
2132 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2133 			    zoneid, ipst->ips_netstack->netstack_sctp);
2134 			if (connp == NULL) {
2135 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2136 				    zoneid, ports, ipha, ipst);
2137 			} else {
2138 				CONN_INC_REF(connp);
2139 				SCTP_REFRELE(CONN2SCTP(connp));
2140 			}
2141 			break;
2142 		}
2143 		default:
2144 		{
2145 			ipha_t ripha;
2146 
2147 			ripha.ipha_src = ipha->ipha_dst;
2148 			ripha.ipha_dst = ipha->ipha_src;
2149 			ripha.ipha_protocol = ipha->ipha_protocol;
2150 
2151 			connfp = &ipst->ips_ipcl_proto_fanout[
2152 			    ipha->ipha_protocol];
2153 			mutex_enter(&connfp->connf_lock);
2154 			connp = connfp->connf_head;
2155 			for (connp = connfp->connf_head; connp != NULL;
2156 			    connp = connp->conn_next) {
2157 				if (IPCL_PROTO_MATCH(connp,
2158 				    ipha->ipha_protocol, &ripha, ill,
2159 				    0, zoneid)) {
2160 					CONN_INC_REF(connp);
2161 					break;
2162 				}
2163 			}
2164 			mutex_exit(&connfp->connf_lock);
2165 		}
2166 	}
2167 	if (connp != NULL) {
2168 		if (connp->conn_nexthop_set)
2169 			nexthop_addr = connp->conn_nexthop_v4;
2170 		CONN_DEC_REF(connp);
2171 	}
2172 	return (nexthop_addr);
2173 }
2174 
2175 /* Table from RFC 1191 */
2176 static int icmp_frag_size_table[] =
2177 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2178 
2179 /*
2180  * Process received ICMP Packet too big.
2181  * After updating any IRE it does the fanout to any matching transport streams.
2182  * Assumes the message has been pulled up till the IP header that caused
2183  * the error.
2184  *
2185  * Returns B_FALSE on failure and B_TRUE on success.
2186  */
2187 static boolean_t
2188 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2189     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2190     ip_stack_t *ipst)
2191 {
2192 	ire_t	*ire, *first_ire;
2193 	int	mtu, orig_mtu;
2194 	int	hdr_length;
2195 	ipaddr_t nexthop_addr;
2196 	boolean_t disable_pmtud;
2197 
2198 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2199 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2200 	ASSERT(ill != NULL);
2201 
2202 	hdr_length = IPH_HDR_LENGTH(ipha);
2203 
2204 	/* Drop if the original packet contained a source route */
2205 	if (ip_source_route_included(ipha)) {
2206 		return (B_FALSE);
2207 	}
2208 	/*
2209 	 * Verify we have at least ICMP_MIN_TP_HDR_LENGTH bytes of transport
2210 	 * header.
2211 	 */
2212 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2213 	    mp->b_wptr) {
2214 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2215 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2216 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2217 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2218 			return (B_FALSE);
2219 		}
2220 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2221 		ipha = (ipha_t *)&icmph[1];
2222 	}
2223 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2224 	if (nexthop_addr != INADDR_ANY) {
2225 		/* nexthop set */
2226 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2227 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2228 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2229 	} else {
2230 		/* nexthop not set */
2231 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2232 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2233 	}
2234 
2235 	if (!first_ire) {
2236 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2237 		    ntohl(ipha->ipha_dst)));
2238 		return (B_FALSE);
2239 	}
2240 
2241 	/* Check for MTU discovery advice as described in RFC 1191 */
2242 	mtu = ntohs(icmph->icmph_du_mtu);
2243 	orig_mtu = mtu;
2244 	disable_pmtud = B_FALSE;
2245 
2246 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2247 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2248 	    ire = ire->ire_next) {
2249 		/*
2250 		 * Look for the connection to which this ICMP message is
2251 		 * directed. If it has the IP_NEXTHOP option set, then the
2252 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2253 		 * option. Else the search is limited to regular IREs.
2254 		 */
2255 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2256 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2257 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2258 		    (nexthop_addr != INADDR_ANY)))
2259 			continue;
2260 
2261 		mutex_enter(&ire->ire_lock);
2262 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2263 			uint32_t length;
2264 			int	i;
2265 
2266 			/*
2267 			 * Use the table from RFC 1191 to figure out
2268 			 * the next "plateau" based on the length in
2269 			 * the original IP packet.
2270 			 */
2271 			length = ntohs(ipha->ipha_length);
2272 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2273 			    uint32_t, length);
2274 			if (ire->ire_max_frag <= length &&
2275 			    ire->ire_max_frag >= length - hdr_length) {
2276 				/*
2277 				 * Handle broken BSD 4.2 systems that
2278 				 * return the wrong iph_length in ICMP
2279 				 * errors.
2280 				 */
2281 				length -= hdr_length;
2282 			}
2283 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2284 				if (length > icmp_frag_size_table[i])
2285 					break;
2286 			}
2287 			if (i == A_CNT(icmp_frag_size_table)) {
2288 				/* Smaller than 68! */
2289 				disable_pmtud = B_TRUE;
2290 				mtu = ipst->ips_ip_pmtu_min;
2291 			} else {
2292 				mtu = icmp_frag_size_table[i];
2293 				if (mtu < ipst->ips_ip_pmtu_min) {
2294 					mtu = ipst->ips_ip_pmtu_min;
2295 					disable_pmtud = B_TRUE;
2296 				}
2297 			}
2298 			/* Fool the ULP into believing our guessed PMTU. */
2299 			icmph->icmph_du_zero = 0;
2300 			icmph->icmph_du_mtu = htons(mtu);
2301 		}
2302 		if (disable_pmtud)
2303 			ire->ire_frag_flag = 0;
2304 		/* Reduce the IRE max frag value as advised. */
2305 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2306 		if (ire->ire_max_frag == mtu) {
2307 			/* Decreased it */
2308 			ire->ire_marks |= IRE_MARK_PMTU;
2309 		}
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  * Fanout for ICMP errors containing IP-in-IPv4 packets.  Returns B_TRUE if a
2370  * tunnel consumed the message, and B_FALSE otherwise.
2371  */
2372 static boolean_t
2373 icmp_inbound_iptun_fanout(mblk_t *first_mp, ipha_t *ripha, ill_t *ill,
2374     ip_stack_t *ipst)
2375 {
2376 	conn_t	*connp;
2377 
2378 	if ((connp = ipcl_iptun_classify_v4(&ripha->ipha_src, &ripha->ipha_dst,
2379 	    ipst)) == NULL)
2380 		return (B_FALSE);
2381 
2382 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
2383 	connp->conn_recv(connp, first_mp, NULL);
2384 	CONN_DEC_REF(connp);
2385 	return (B_TRUE);
2386 }
2387 
2388 /*
2389  * Try to pass the ICMP message upstream in case the ULP cares.
2390  *
2391  * If the packet that caused the ICMP error is secure, we send
2392  * it to AH/ESP to make sure that the attached packet has a
2393  * valid association. ipha in the code below points to the
2394  * IP header of the packet that caused the error.
2395  *
2396  * For IPsec cases, we let the next-layer-up (which has access to
2397  * cached policy on the conn_t, or can query the SPD directly)
2398  * subtract out any IPsec overhead if they must.  We therefore make no
2399  * adjustments here for IPsec overhead.
2400  *
2401  * IFN could have been generated locally or by some router.
2402  *
2403  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2404  *	    This happens because IP adjusted its value of MTU on an
2405  *	    earlier IFN message and could not tell the upper layer,
2406  *	    the new adjusted value of MTU e.g. Packet was encrypted
2407  *	    or there was not enough information to fanout to upper
2408  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2409  *	    generates the IFN, where IPsec processing has *not* been
2410  *	    done.
2411  *
2412  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2413  *	    could have generated this. This happens because ire_max_frag
2414  *	    value in IP was set to a new value, while the IPsec processing
2415  *	    was being done and after we made the fragmentation check in
2416  *	    ip_wput_ire. Thus on return from IPsec processing,
2417  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2418  *	    and generates the IFN. As IPsec processing is over, we fanout
2419  *	    to AH/ESP to remove the header.
2420  *
2421  *	    In both these cases, ipsec_in_loopback will be set indicating
2422  *	    that IFN was generated locally.
2423  *
2424  * ROUTER : IFN could be secure or non-secure.
2425  *
2426  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2427  *	      packet in error has AH/ESP headers to validate the AH/ESP
2428  *	      headers. AH/ESP will verify whether there is a valid SA or
2429  *	      not and send it back. We will fanout again if we have more
2430  *	      data in the packet.
2431  *
2432  *	      If the packet in error does not have AH/ESP, we handle it
2433  *	      like any other case.
2434  *
2435  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2436  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2437  *	      for validation. AH/ESP will verify whether there is a
2438  *	      valid SA or not and send it back. We will fanout again if
2439  *	      we have more data in the packet.
2440  *
2441  *	      If the packet in error does not have AH/ESP, we handle it
2442  *	      like any other case.
2443  */
2444 static void
2445 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2446     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2447     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2448     zoneid_t zoneid)
2449 {
2450 	uint16_t *up;	/* Pointer to ports in ULP header */
2451 	uint32_t ports;	/* reversed ports for fanout */
2452 	ipha_t ripha;	/* With reversed addresses */
2453 	mblk_t *first_mp;
2454 	ipsec_in_t *ii;
2455 	tcph_t	*tcph;
2456 	conn_t	*connp;
2457 	ip_stack_t *ipst;
2458 
2459 	ASSERT(ill != NULL);
2460 
2461 	ASSERT(recv_ill != NULL);
2462 	ipst = recv_ill->ill_ipst;
2463 
2464 	first_mp = mp;
2465 	if (mctl_present) {
2466 		mp = first_mp->b_cont;
2467 		ASSERT(mp != NULL);
2468 
2469 		ii = (ipsec_in_t *)first_mp->b_rptr;
2470 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2471 	} else {
2472 		ii = NULL;
2473 	}
2474 
2475 	/*
2476 	 * We need a separate IP header with the source and destination
2477 	 * addresses reversed to do fanout/classification because the ipha in
2478 	 * the ICMP error is in the form we sent it out.
2479 	 */
2480 	ripha.ipha_src = ipha->ipha_dst;
2481 	ripha.ipha_dst = ipha->ipha_src;
2482 	ripha.ipha_protocol = ipha->ipha_protocol;
2483 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2484 
2485 	ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2486 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2487 	    ntohl(ipha->ipha_dst),
2488 	    icmph->icmph_type, icmph->icmph_code));
2489 
2490 	switch (ipha->ipha_protocol) {
2491 	case IPPROTO_UDP:
2492 		/*
2493 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2494 		 * transport header.
2495 		 */
2496 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2497 		    mp->b_wptr) {
2498 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2499 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2500 				goto discard_pkt;
2501 			}
2502 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2503 			ipha = (ipha_t *)&icmph[1];
2504 		}
2505 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2506 
2507 		/* Attempt to find a client stream based on port. */
2508 		((uint16_t *)&ports)[0] = up[1];
2509 		((uint16_t *)&ports)[1] = up[0];
2510 		ip2dbg(("icmp_inbound_error: UDP ports %d to %d\n",
2511 		    ntohs(up[0]), ntohs(up[1])));
2512 
2513 		/* Have to change db_type after any pullupmsg */
2514 		DB_TYPE(mp) = M_CTL;
2515 
2516 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2517 		    mctl_present, ip_policy, recv_ill, zoneid);
2518 		return;
2519 
2520 	case IPPROTO_TCP:
2521 		/*
2522 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2523 		 * transport header.
2524 		 */
2525 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2526 		    mp->b_wptr) {
2527 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2528 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2529 				goto discard_pkt;
2530 			}
2531 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2532 			ipha = (ipha_t *)&icmph[1];
2533 		}
2534 		/*
2535 		 * Find a TCP client stream for this packet.
2536 		 * Note that we do a reverse lookup since the header is
2537 		 * in the form we sent it out.
2538 		 */
2539 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2540 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2541 		    ipst);
2542 		if (connp == NULL)
2543 			goto discard_pkt;
2544 
2545 		/* Have to change db_type after any pullupmsg */
2546 		DB_TYPE(mp) = M_CTL;
2547 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2548 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2549 		return;
2550 
2551 	case IPPROTO_SCTP:
2552 		/*
2553 		 * Verify we have at least ICMP_MIN_SCTP_HDR_LEN bytes of
2554 		 * transport header, in the first mp.
2555 		 */
2556 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_SCTP_HDR_LEN >
2557 		    mp->b_wptr) {
2558 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2559 			    ICMP_MIN_SCTP_HDR_LEN - mp->b_rptr)) {
2560 				goto discard_pkt;
2561 			}
2562 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2563 			ipha = (ipha_t *)&icmph[1];
2564 		}
2565 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2566 		/* Find a SCTP client stream for this packet. */
2567 		((uint16_t *)&ports)[0] = up[1];
2568 		((uint16_t *)&ports)[1] = up[0];
2569 
2570 		/* Have to change db_type after any pullupmsg */
2571 		DB_TYPE(mp) = M_CTL;
2572 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2573 		    mctl_present, ip_policy, zoneid);
2574 		return;
2575 
2576 	case IPPROTO_ESP:
2577 	case IPPROTO_AH: {
2578 		int ipsec_rc;
2579 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2580 
2581 		/*
2582 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2583 		 * We will re-use the IPSEC_IN if it is already present as
2584 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2585 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2586 		 * one and attach it in the front.
2587 		 */
2588 		if (ii != NULL) {
2589 			/*
2590 			 * ip_fanout_proto_again converts the ICMP errors
2591 			 * that come back from AH/ESP to M_DATA so that
2592 			 * if it is non-AH/ESP and we do a pullupmsg in
2593 			 * this function, it would work. Convert it back
2594 			 * to M_CTL before we send up as this is a ICMP
2595 			 * error. This could have been generated locally or
2596 			 * by some router. Validate the inner IPsec
2597 			 * headers.
2598 			 *
2599 			 * NOTE : ill_index is used by ip_fanout_proto_again
2600 			 * to locate the ill.
2601 			 */
2602 			ASSERT(ill != NULL);
2603 			ii->ipsec_in_ill_index =
2604 			    ill->ill_phyint->phyint_ifindex;
2605 			ii->ipsec_in_rill_index =
2606 			    recv_ill->ill_phyint->phyint_ifindex;
2607 			DB_TYPE(first_mp->b_cont) = M_CTL;
2608 		} else {
2609 			/*
2610 			 * IPSEC_IN is not present. We attach a ipsec_in
2611 			 * message and send up to IPsec for validating
2612 			 * and removing the IPsec headers. Clear
2613 			 * ipsec_in_secure so that when we return
2614 			 * from IPsec, we don't mistakenly think that this
2615 			 * is a secure packet came from the network.
2616 			 *
2617 			 * NOTE : ill_index is used by ip_fanout_proto_again
2618 			 * to locate the ill.
2619 			 */
2620 			ASSERT(first_mp == mp);
2621 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2622 			if (first_mp == NULL) {
2623 				freemsg(mp);
2624 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2625 				return;
2626 			}
2627 			ii = (ipsec_in_t *)first_mp->b_rptr;
2628 
2629 			/* This is not a secure packet */
2630 			ii->ipsec_in_secure = B_FALSE;
2631 			first_mp->b_cont = mp;
2632 			DB_TYPE(mp) = M_CTL;
2633 			ASSERT(ill != NULL);
2634 			ii->ipsec_in_ill_index =
2635 			    ill->ill_phyint->phyint_ifindex;
2636 			ii->ipsec_in_rill_index =
2637 			    recv_ill->ill_phyint->phyint_ifindex;
2638 		}
2639 
2640 		if (!ipsec_loaded(ipss)) {
2641 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2642 			return;
2643 		}
2644 
2645 		if (ipha->ipha_protocol == IPPROTO_ESP)
2646 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2647 		else
2648 			ipsec_rc = ipsecah_icmp_error(first_mp);
2649 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2650 			return;
2651 
2652 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2653 		return;
2654 	}
2655 	case IPPROTO_ENCAP:
2656 	case IPPROTO_IPV6:
2657 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2658 			ipha_t *in_ipha;
2659 
2660 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2661 			    mp->b_wptr) {
2662 				if (!pullupmsg(mp, (uchar_t *)ipha +
2663 				    hdr_length + sizeof (ipha_t) -
2664 				    mp->b_rptr)) {
2665 					goto discard_pkt;
2666 				}
2667 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2668 				ipha = (ipha_t *)&icmph[1];
2669 			}
2670 			/*
2671 			 * Caller has verified that length has to be
2672 			 * at least the size of IP header.
2673 			 */
2674 			ASSERT(hdr_length >= sizeof (ipha_t));
2675 			/*
2676 			 * Check the sanity of the inner IP header like
2677 			 * we did for the outer header.
2678 			 */
2679 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2680 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION) ||
2681 			    IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t))
2682 				goto discard_pkt;
2683 			/* Check for Self-encapsulated tunnels */
2684 			if (in_ipha->ipha_src == ipha->ipha_src &&
2685 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2686 
2687 				mp = icmp_inbound_self_encap_error(mp,
2688 				    iph_hdr_length, hdr_length);
2689 				if (mp == NULL)
2690 					goto discard_pkt;
2691 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2692 				ipha = (ipha_t *)&icmph[1];
2693 				hdr_length = IPH_HDR_LENGTH(ipha);
2694 				/*
2695 				 * The packet in error is self-encapsualted.
2696 				 * And we are finding it further encapsulated
2697 				 * which we could not have possibly generated.
2698 				 */
2699 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2700 					goto discard_pkt;
2701 				}
2702 				icmp_inbound_error_fanout(q, ill, first_mp,
2703 				    icmph, ipha, iph_hdr_length, hdr_length,
2704 				    mctl_present, ip_policy, recv_ill, zoneid);
2705 				return;
2706 			}
2707 		}
2708 
2709 		DB_TYPE(mp) = M_CTL;
2710 		if (icmp_inbound_iptun_fanout(first_mp, &ripha, ill, ipst))
2711 			return;
2712 		/*
2713 		 * No IP tunnel is interested, fallthrough and see
2714 		 * if a raw socket will want it.
2715 		 */
2716 		/* FALLTHRU */
2717 	default:
2718 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2719 		    ip_policy, recv_ill, zoneid);
2720 		return;
2721 	}
2722 	/* NOTREACHED */
2723 discard_pkt:
2724 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2725 drop_pkt:;
2726 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2727 	freemsg(first_mp);
2728 }
2729 
2730 /*
2731  * Common IP options parser.
2732  *
2733  * Setup routine: fill in *optp with options-parsing state, then
2734  * tail-call ipoptp_next to return the first option.
2735  */
2736 uint8_t
2737 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2738 {
2739 	uint32_t totallen; /* total length of all options */
2740 
2741 	totallen = ipha->ipha_version_and_hdr_length -
2742 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2743 	totallen <<= 2;
2744 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2745 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2746 	optp->ipoptp_flags = 0;
2747 	return (ipoptp_next(optp));
2748 }
2749 
2750 /*
2751  * Common IP options parser: extract next option.
2752  */
2753 uint8_t
2754 ipoptp_next(ipoptp_t *optp)
2755 {
2756 	uint8_t *end = optp->ipoptp_end;
2757 	uint8_t *cur = optp->ipoptp_next;
2758 	uint8_t opt, len, pointer;
2759 
2760 	/*
2761 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2762 	 * has been corrupted.
2763 	 */
2764 	ASSERT(cur <= end);
2765 
2766 	if (cur == end)
2767 		return (IPOPT_EOL);
2768 
2769 	opt = cur[IPOPT_OPTVAL];
2770 
2771 	/*
2772 	 * Skip any NOP options.
2773 	 */
2774 	while (opt == IPOPT_NOP) {
2775 		cur++;
2776 		if (cur == end)
2777 			return (IPOPT_EOL);
2778 		opt = cur[IPOPT_OPTVAL];
2779 	}
2780 
2781 	if (opt == IPOPT_EOL)
2782 		return (IPOPT_EOL);
2783 
2784 	/*
2785 	 * Option requiring a length.
2786 	 */
2787 	if ((cur + 1) >= end) {
2788 		optp->ipoptp_flags |= IPOPTP_ERROR;
2789 		return (IPOPT_EOL);
2790 	}
2791 	len = cur[IPOPT_OLEN];
2792 	if (len < 2) {
2793 		optp->ipoptp_flags |= IPOPTP_ERROR;
2794 		return (IPOPT_EOL);
2795 	}
2796 	optp->ipoptp_cur = cur;
2797 	optp->ipoptp_len = len;
2798 	optp->ipoptp_next = cur + len;
2799 	if (cur + len > end) {
2800 		optp->ipoptp_flags |= IPOPTP_ERROR;
2801 		return (IPOPT_EOL);
2802 	}
2803 
2804 	/*
2805 	 * For the options which require a pointer field, make sure
2806 	 * its there, and make sure it points to either something
2807 	 * inside this option, or the end of the option.
2808 	 */
2809 	switch (opt) {
2810 	case IPOPT_RR:
2811 	case IPOPT_TS:
2812 	case IPOPT_LSRR:
2813 	case IPOPT_SSRR:
2814 		if (len <= IPOPT_OFFSET) {
2815 			optp->ipoptp_flags |= IPOPTP_ERROR;
2816 			return (opt);
2817 		}
2818 		pointer = cur[IPOPT_OFFSET];
2819 		if (pointer - 1 > len) {
2820 			optp->ipoptp_flags |= IPOPTP_ERROR;
2821 			return (opt);
2822 		}
2823 		break;
2824 	}
2825 
2826 	/*
2827 	 * Sanity check the pointer field based on the type of the
2828 	 * option.
2829 	 */
2830 	switch (opt) {
2831 	case IPOPT_RR:
2832 	case IPOPT_SSRR:
2833 	case IPOPT_LSRR:
2834 		if (pointer < IPOPT_MINOFF_SR)
2835 			optp->ipoptp_flags |= IPOPTP_ERROR;
2836 		break;
2837 	case IPOPT_TS:
2838 		if (pointer < IPOPT_MINOFF_IT)
2839 			optp->ipoptp_flags |= IPOPTP_ERROR;
2840 		/*
2841 		 * Note that the Internet Timestamp option also
2842 		 * contains two four bit fields (the Overflow field,
2843 		 * and the Flag field), which follow the pointer
2844 		 * field.  We don't need to check that these fields
2845 		 * fall within the length of the option because this
2846 		 * was implicitely done above.  We've checked that the
2847 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2848 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2849 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2850 		 */
2851 		ASSERT(len > IPOPT_POS_OV_FLG);
2852 		break;
2853 	}
2854 
2855 	return (opt);
2856 }
2857 
2858 /*
2859  * Use the outgoing IP header to create an IP_OPTIONS option the way
2860  * it was passed down from the application.
2861  */
2862 int
2863 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2864 {
2865 	ipoptp_t	opts;
2866 	const uchar_t	*opt;
2867 	uint8_t		optval;
2868 	uint8_t		optlen;
2869 	uint32_t	len = 0;
2870 	uchar_t	*buf1 = buf;
2871 
2872 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2873 	len += IP_ADDR_LEN;
2874 	bzero(buf1, IP_ADDR_LEN);
2875 
2876 	/*
2877 	 * OK to cast away const here, as we don't store through the returned
2878 	 * opts.ipoptp_cur pointer.
2879 	 */
2880 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2881 	    optval != IPOPT_EOL;
2882 	    optval = ipoptp_next(&opts)) {
2883 		int	off;
2884 
2885 		opt = opts.ipoptp_cur;
2886 		optlen = opts.ipoptp_len;
2887 		switch (optval) {
2888 		case IPOPT_SSRR:
2889 		case IPOPT_LSRR:
2890 
2891 			/*
2892 			 * Insert ipha_dst as the first entry in the source
2893 			 * route and move down the entries on step.
2894 			 * The last entry gets placed at buf1.
2895 			 */
2896 			buf[IPOPT_OPTVAL] = optval;
2897 			buf[IPOPT_OLEN] = optlen;
2898 			buf[IPOPT_OFFSET] = optlen;
2899 
2900 			off = optlen - IP_ADDR_LEN;
2901 			if (off < 0) {
2902 				/* No entries in source route */
2903 				break;
2904 			}
2905 			/* Last entry in source route */
2906 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2907 			off -= IP_ADDR_LEN;
2908 
2909 			while (off > 0) {
2910 				bcopy(opt + off,
2911 				    buf + off + IP_ADDR_LEN,
2912 				    IP_ADDR_LEN);
2913 				off -= IP_ADDR_LEN;
2914 			}
2915 			/* ipha_dst into first slot */
2916 			bcopy(&ipha->ipha_dst,
2917 			    buf + off + IP_ADDR_LEN,
2918 			    IP_ADDR_LEN);
2919 			buf += optlen;
2920 			len += optlen;
2921 			break;
2922 
2923 		case IPOPT_COMSEC:
2924 		case IPOPT_SECURITY:
2925 			/* if passing up a label is not ok, then remove */
2926 			if (is_system_labeled())
2927 				break;
2928 			/* FALLTHROUGH */
2929 		default:
2930 			bcopy(opt, buf, optlen);
2931 			buf += optlen;
2932 			len += optlen;
2933 			break;
2934 		}
2935 	}
2936 done:
2937 	/* Pad the resulting options */
2938 	while (len & 0x3) {
2939 		*buf++ = IPOPT_EOL;
2940 		len++;
2941 	}
2942 	return (len);
2943 }
2944 
2945 /*
2946  * Update any record route or timestamp options to include this host.
2947  * Reverse any source route option.
2948  * This routine assumes that the options are well formed i.e. that they
2949  * have already been checked.
2950  */
2951 static void
2952 icmp_options_update(ipha_t *ipha)
2953 {
2954 	ipoptp_t	opts;
2955 	uchar_t		*opt;
2956 	uint8_t		optval;
2957 	ipaddr_t	src;		/* Our local address */
2958 	ipaddr_t	dst;
2959 
2960 	ip2dbg(("icmp_options_update\n"));
2961 	src = ipha->ipha_src;
2962 	dst = ipha->ipha_dst;
2963 
2964 	for (optval = ipoptp_first(&opts, ipha);
2965 	    optval != IPOPT_EOL;
2966 	    optval = ipoptp_next(&opts)) {
2967 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2968 		opt = opts.ipoptp_cur;
2969 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2970 		    optval, opts.ipoptp_len));
2971 		switch (optval) {
2972 			int off1, off2;
2973 		case IPOPT_SSRR:
2974 		case IPOPT_LSRR:
2975 			/*
2976 			 * Reverse the source route.  The first entry
2977 			 * should be the next to last one in the current
2978 			 * source route (the last entry is our address).
2979 			 * The last entry should be the final destination.
2980 			 */
2981 			off1 = IPOPT_MINOFF_SR - 1;
2982 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2983 			if (off2 < 0) {
2984 				/* No entries in source route */
2985 				ip1dbg((
2986 				    "icmp_options_update: bad src route\n"));
2987 				break;
2988 			}
2989 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2990 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2991 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2992 			off2 -= IP_ADDR_LEN;
2993 
2994 			while (off1 < off2) {
2995 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2996 				bcopy((char *)opt + off2, (char *)opt + off1,
2997 				    IP_ADDR_LEN);
2998 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2999 				off1 += IP_ADDR_LEN;
3000 				off2 -= IP_ADDR_LEN;
3001 			}
3002 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3003 			break;
3004 		}
3005 	}
3006 }
3007 
3008 /*
3009  * Process received ICMP Redirect messages.
3010  */
3011 static void
3012 icmp_redirect(ill_t *ill, mblk_t *mp)
3013 {
3014 	ipha_t	*ipha;
3015 	int	iph_hdr_length;
3016 	icmph_t	*icmph;
3017 	ipha_t	*ipha_err;
3018 	ire_t	*ire;
3019 	ire_t	*prev_ire;
3020 	ire_t	*save_ire;
3021 	ipaddr_t  src, dst, gateway;
3022 	iulp_t	ulp_info = { 0 };
3023 	int	error;
3024 	ip_stack_t *ipst;
3025 
3026 	ASSERT(ill != NULL);
3027 	ipst = ill->ill_ipst;
3028 
3029 	ipha = (ipha_t *)mp->b_rptr;
3030 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3031 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3032 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3033 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3034 		freemsg(mp);
3035 		return;
3036 	}
3037 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3038 	ipha_err = (ipha_t *)&icmph[1];
3039 	src = ipha->ipha_src;
3040 	dst = ipha_err->ipha_dst;
3041 	gateway = icmph->icmph_rd_gateway;
3042 	/* Make sure the new gateway is reachable somehow. */
3043 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3044 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3045 	/*
3046 	 * Make sure we had a route for the dest in question and that
3047 	 * that route was pointing to the old gateway (the source of the
3048 	 * redirect packet.)
3049 	 */
3050 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3051 	    NULL, MATCH_IRE_GW, ipst);
3052 	/*
3053 	 * Check that
3054 	 *	the redirect was not from ourselves
3055 	 *	the new gateway and the old gateway are directly reachable
3056 	 */
3057 	if (!prev_ire ||
3058 	    !ire ||
3059 	    ire->ire_type == IRE_LOCAL) {
3060 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3061 		freemsg(mp);
3062 		if (ire != NULL)
3063 			ire_refrele(ire);
3064 		if (prev_ire != NULL)
3065 			ire_refrele(prev_ire);
3066 		return;
3067 	}
3068 
3069 	/*
3070 	 * Should we use the old ULP info to create the new gateway?  From
3071 	 * a user's perspective, we should inherit the info so that it
3072 	 * is a "smooth" transition.  If we do not do that, then new
3073 	 * connections going thru the new gateway will have no route metrics,
3074 	 * which is counter-intuitive to user.  From a network point of
3075 	 * view, this may or may not make sense even though the new gateway
3076 	 * is still directly connected to us so the route metrics should not
3077 	 * change much.
3078 	 *
3079 	 * But if the old ire_uinfo is not initialized, we do another
3080 	 * recursive lookup on the dest using the new gateway.  There may
3081 	 * be a route to that.  If so, use it to initialize the redirect
3082 	 * route.
3083 	 */
3084 	if (prev_ire->ire_uinfo.iulp_set) {
3085 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3086 	} else {
3087 		ire_t *tmp_ire;
3088 		ire_t *sire;
3089 
3090 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3091 		    ALL_ZONES, 0, NULL,
3092 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3093 		    ipst);
3094 		if (sire != NULL) {
3095 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3096 			/*
3097 			 * If sire != NULL, ire_ftable_lookup() should not
3098 			 * return a NULL value.
3099 			 */
3100 			ASSERT(tmp_ire != NULL);
3101 			ire_refrele(tmp_ire);
3102 			ire_refrele(sire);
3103 		} else if (tmp_ire != NULL) {
3104 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3105 			    sizeof (iulp_t));
3106 			ire_refrele(tmp_ire);
3107 		}
3108 	}
3109 	if (prev_ire->ire_type == IRE_CACHE)
3110 		ire_delete(prev_ire);
3111 	ire_refrele(prev_ire);
3112 	/*
3113 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3114 	 * require TOS routing
3115 	 */
3116 	switch (icmph->icmph_code) {
3117 	case 0:
3118 	case 1:
3119 		/* TODO: TOS specificity for cases 2 and 3 */
3120 	case 2:
3121 	case 3:
3122 		break;
3123 	default:
3124 		freemsg(mp);
3125 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3126 		ire_refrele(ire);
3127 		return;
3128 	}
3129 	/*
3130 	 * Create a Route Association.  This will allow us to remember that
3131 	 * someone we believe told us to use the particular gateway.
3132 	 */
3133 	save_ire = ire;
3134 	ire = ire_create(
3135 	    (uchar_t *)&dst,			/* dest addr */
3136 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3137 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3138 	    (uchar_t *)&gateway,		/* gateway addr */
3139 	    &save_ire->ire_max_frag,		/* max frag */
3140 	    NULL,				/* no src nce */
3141 	    NULL,				/* no rfq */
3142 	    NULL,				/* no stq */
3143 	    IRE_HOST,
3144 	    NULL,				/* ipif */
3145 	    0,					/* cmask */
3146 	    0,					/* phandle */
3147 	    0,					/* ihandle */
3148 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3149 	    &ulp_info,
3150 	    NULL,				/* tsol_gc_t */
3151 	    NULL,				/* gcgrp */
3152 	    ipst);
3153 
3154 	if (ire == NULL) {
3155 		freemsg(mp);
3156 		ire_refrele(save_ire);
3157 		return;
3158 	}
3159 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3160 	ire_refrele(save_ire);
3161 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3162 
3163 	if (error == 0) {
3164 		ire_refrele(ire);		/* Held in ire_add_v4 */
3165 		/* tell routing sockets that we received a redirect */
3166 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3167 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3168 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3169 	}
3170 
3171 	/*
3172 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3173 	 * This together with the added IRE has the effect of
3174 	 * modifying an existing redirect.
3175 	 */
3176 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3177 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3178 	if (prev_ire != NULL) {
3179 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3180 			ire_delete(prev_ire);
3181 		ire_refrele(prev_ire);
3182 	}
3183 
3184 	freemsg(mp);
3185 }
3186 
3187 /*
3188  * Generate an ICMP parameter problem message.
3189  */
3190 static void
3191 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3192 	ip_stack_t *ipst)
3193 {
3194 	icmph_t	icmph;
3195 	boolean_t mctl_present;
3196 	mblk_t *first_mp;
3197 
3198 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3199 
3200 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3201 		if (mctl_present)
3202 			freeb(first_mp);
3203 		return;
3204 	}
3205 
3206 	bzero(&icmph, sizeof (icmph_t));
3207 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3208 	icmph.icmph_pp_ptr = ptr;
3209 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3210 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3211 	    ipst);
3212 }
3213 
3214 /*
3215  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3216  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3217  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3218  * an icmp error packet can be sent.
3219  * Assigns an appropriate source address to the packet. If ipha_dst is
3220  * one of our addresses use it for source. Otherwise pick a source based
3221  * on a route lookup back to ipha_src.
3222  * Note that ipha_src must be set here since the
3223  * packet is likely to arrive on an ill queue in ip_wput() which will
3224  * not set a source address.
3225  */
3226 static void
3227 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3228     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3229 {
3230 	ipaddr_t dst;
3231 	icmph_t	*icmph;
3232 	ipha_t	*ipha;
3233 	uint_t	len_needed;
3234 	size_t	msg_len;
3235 	mblk_t	*mp1;
3236 	ipaddr_t src;
3237 	ire_t	*ire;
3238 	mblk_t *ipsec_mp;
3239 	ipsec_out_t	*io = NULL;
3240 
3241 	if (mctl_present) {
3242 		/*
3243 		 * If it is :
3244 		 *
3245 		 * 1) a IPSEC_OUT, then this is caused by outbound
3246 		 *    datagram originating on this host. IPsec processing
3247 		 *    may or may not have been done. Refer to comments above
3248 		 *    icmp_inbound_error_fanout for details.
3249 		 *
3250 		 * 2) a IPSEC_IN if we are generating a icmp_message
3251 		 *    for an incoming datagram destined for us i.e called
3252 		 *    from ip_fanout_send_icmp.
3253 		 */
3254 		ipsec_info_t *in;
3255 		ipsec_mp = mp;
3256 		mp = ipsec_mp->b_cont;
3257 
3258 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3259 		ipha = (ipha_t *)mp->b_rptr;
3260 
3261 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3262 		    in->ipsec_info_type == IPSEC_IN);
3263 
3264 		if (in->ipsec_info_type == IPSEC_IN) {
3265 			/*
3266 			 * Convert the IPSEC_IN to IPSEC_OUT.
3267 			 */
3268 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL, zoneid)) {
3269 				BUMP_MIB(&ipst->ips_ip_mib,
3270 				    ipIfStatsOutDiscards);
3271 				return;
3272 			}
3273 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3274 		} else {
3275 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3276 			io = (ipsec_out_t *)in;
3277 			/*
3278 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3279 			 * ire lookup.
3280 			 */
3281 			io->ipsec_out_proc_begin = B_FALSE;
3282 		}
3283 		ASSERT(zoneid != ALL_ZONES);
3284 		/*
3285 		 * The IPSEC_IN (now an IPSEC_OUT) didn't have its zoneid
3286 		 * initialized.  We need to do that now.
3287 		 */
3288 		io->ipsec_out_zoneid = zoneid;
3289 	} else {
3290 		/*
3291 		 * This is in clear. The icmp message we are building
3292 		 * here should go out in clear.
3293 		 *
3294 		 * Pardon the convolution of it all, but it's easier to
3295 		 * allocate a "use cleartext" IPSEC_IN message and convert
3296 		 * it than it is to allocate a new one.
3297 		 */
3298 		ipsec_in_t *ii;
3299 		ASSERT(DB_TYPE(mp) == M_DATA);
3300 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3301 		if (ipsec_mp == NULL) {
3302 			freemsg(mp);
3303 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3304 			return;
3305 		}
3306 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3307 
3308 		/* This is not a secure packet */
3309 		ii->ipsec_in_secure = B_FALSE;
3310 		ipsec_mp->b_cont = mp;
3311 		ipha = (ipha_t *)mp->b_rptr;
3312 		/*
3313 		 * Convert the IPSEC_IN to IPSEC_OUT.
3314 		 */
3315 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL, zoneid)) {
3316 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3317 			return;
3318 		}
3319 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3320 	}
3321 
3322 	/* Remember our eventual destination */
3323 	dst = ipha->ipha_src;
3324 
3325 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3326 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3327 	if (ire != NULL &&
3328 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3329 		src = ipha->ipha_dst;
3330 	} else {
3331 		if (ire != NULL)
3332 			ire_refrele(ire);
3333 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3334 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3335 		    ipst);
3336 		if (ire == NULL) {
3337 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3338 			freemsg(ipsec_mp);
3339 			return;
3340 		}
3341 		src = ire->ire_src_addr;
3342 	}
3343 
3344 	if (ire != NULL)
3345 		ire_refrele(ire);
3346 
3347 	/*
3348 	 * Check if we can send back more then 8 bytes in addition to
3349 	 * the IP header.  We try to send 64 bytes of data and the internal
3350 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3351 	 */
3352 	len_needed = IPH_HDR_LENGTH(ipha);
3353 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3354 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3355 
3356 		if (!pullupmsg(mp, -1)) {
3357 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3358 			freemsg(ipsec_mp);
3359 			return;
3360 		}
3361 		ipha = (ipha_t *)mp->b_rptr;
3362 
3363 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3364 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3365 			    len_needed));
3366 		} else {
3367 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3368 
3369 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3370 			len_needed += ip_hdr_length_v6(mp, ip6h);
3371 		}
3372 	}
3373 	len_needed += ipst->ips_ip_icmp_return;
3374 	msg_len = msgdsize(mp);
3375 	if (msg_len > len_needed) {
3376 		(void) adjmsg(mp, len_needed - msg_len);
3377 		msg_len = len_needed;
3378 	}
3379 	/* Make sure we propagate the cred/label for TX */
3380 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3381 	if (mp1 == NULL) {
3382 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3383 		freemsg(ipsec_mp);
3384 		return;
3385 	}
3386 	mp1->b_cont = mp;
3387 	mp = mp1;
3388 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3389 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3390 	    io->ipsec_out_type == IPSEC_OUT);
3391 	ipsec_mp->b_cont = mp;
3392 
3393 	/*
3394 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3395 	 * node generates be accepted in peace by all on-host destinations.
3396 	 * If we do NOT assume that all on-host destinations trust
3397 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3398 	 * (Look for ipsec_out_icmp_loopback).
3399 	 */
3400 	io->ipsec_out_icmp_loopback = B_TRUE;
3401 
3402 	ipha = (ipha_t *)mp->b_rptr;
3403 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3404 	*ipha = icmp_ipha;
3405 	ipha->ipha_src = src;
3406 	ipha->ipha_dst = dst;
3407 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3408 	msg_len += sizeof (icmp_ipha) + len;
3409 	if (msg_len > IP_MAXPACKET) {
3410 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3411 		msg_len = IP_MAXPACKET;
3412 	}
3413 	ipha->ipha_length = htons((uint16_t)msg_len);
3414 	icmph = (icmph_t *)&ipha[1];
3415 	bcopy(stuff, icmph, len);
3416 	icmph->icmph_checksum = 0;
3417 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3418 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3419 	put(q, ipsec_mp);
3420 }
3421 
3422 /*
3423  * Determine if an ICMP error packet can be sent given the rate limit.
3424  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3425  * in milliseconds) and a burst size. Burst size number of packets can
3426  * be sent arbitrarely closely spaced.
3427  * The state is tracked using two variables to implement an approximate
3428  * token bucket filter:
3429  *	icmp_pkt_err_last - lbolt value when the last burst started
3430  *	icmp_pkt_err_sent - number of packets sent in current burst
3431  */
3432 boolean_t
3433 icmp_err_rate_limit(ip_stack_t *ipst)
3434 {
3435 	clock_t now = TICK_TO_MSEC(lbolt);
3436 	uint_t refilled; /* Number of packets refilled in tbf since last */
3437 	/* Guard against changes by loading into local variable */
3438 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3439 
3440 	if (err_interval == 0)
3441 		return (B_FALSE);
3442 
3443 	if (ipst->ips_icmp_pkt_err_last > now) {
3444 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3445 		ipst->ips_icmp_pkt_err_last = 0;
3446 		ipst->ips_icmp_pkt_err_sent = 0;
3447 	}
3448 	/*
3449 	 * If we are in a burst update the token bucket filter.
3450 	 * Update the "last" time to be close to "now" but make sure
3451 	 * we don't loose precision.
3452 	 */
3453 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3454 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3455 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3456 			ipst->ips_icmp_pkt_err_sent = 0;
3457 		} else {
3458 			ipst->ips_icmp_pkt_err_sent -= refilled;
3459 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3460 		}
3461 	}
3462 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3463 		/* Start of new burst */
3464 		ipst->ips_icmp_pkt_err_last = now;
3465 	}
3466 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3467 		ipst->ips_icmp_pkt_err_sent++;
3468 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3469 		    ipst->ips_icmp_pkt_err_sent));
3470 		return (B_FALSE);
3471 	}
3472 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3473 	return (B_TRUE);
3474 }
3475 
3476 /*
3477  * Check if it is ok to send an IPv4 ICMP error packet in
3478  * response to the IPv4 packet in mp.
3479  * Free the message and return null if no
3480  * ICMP error packet should be sent.
3481  */
3482 static mblk_t *
3483 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3484 {
3485 	icmph_t	*icmph;
3486 	ipha_t	*ipha;
3487 	uint_t	len_needed;
3488 	ire_t	*src_ire;
3489 	ire_t	*dst_ire;
3490 
3491 	if (!mp)
3492 		return (NULL);
3493 	ipha = (ipha_t *)mp->b_rptr;
3494 	if (ip_csum_hdr(ipha)) {
3495 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3496 		freemsg(mp);
3497 		return (NULL);
3498 	}
3499 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3500 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3501 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3502 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3503 	if (src_ire != NULL || dst_ire != NULL ||
3504 	    CLASSD(ipha->ipha_dst) ||
3505 	    CLASSD(ipha->ipha_src) ||
3506 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3507 		/* Note: only errors to the fragment with offset 0 */
3508 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3509 		freemsg(mp);
3510 		if (src_ire != NULL)
3511 			ire_refrele(src_ire);
3512 		if (dst_ire != NULL)
3513 			ire_refrele(dst_ire);
3514 		return (NULL);
3515 	}
3516 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3517 		/*
3518 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3519 		 * errors in response to any ICMP errors.
3520 		 */
3521 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3522 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3523 			if (!pullupmsg(mp, len_needed)) {
3524 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3525 				freemsg(mp);
3526 				return (NULL);
3527 			}
3528 			ipha = (ipha_t *)mp->b_rptr;
3529 		}
3530 		icmph = (icmph_t *)
3531 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3532 		switch (icmph->icmph_type) {
3533 		case ICMP_DEST_UNREACHABLE:
3534 		case ICMP_SOURCE_QUENCH:
3535 		case ICMP_TIME_EXCEEDED:
3536 		case ICMP_PARAM_PROBLEM:
3537 		case ICMP_REDIRECT:
3538 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3539 			freemsg(mp);
3540 			return (NULL);
3541 		default:
3542 			break;
3543 		}
3544 	}
3545 	/*
3546 	 * If this is a labeled system, then check to see if we're allowed to
3547 	 * send a response to this particular sender.  If not, then just drop.
3548 	 */
3549 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3550 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3551 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3552 		freemsg(mp);
3553 		return (NULL);
3554 	}
3555 	if (icmp_err_rate_limit(ipst)) {
3556 		/*
3557 		 * Only send ICMP error packets every so often.
3558 		 * This should be done on a per port/source basis,
3559 		 * but for now this will suffice.
3560 		 */
3561 		freemsg(mp);
3562 		return (NULL);
3563 	}
3564 	return (mp);
3565 }
3566 
3567 /*
3568  * Generate an ICMP redirect message.
3569  */
3570 static void
3571 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3572 {
3573 	icmph_t	icmph;
3574 
3575 	/*
3576 	 * We are called from ip_rput where we could
3577 	 * not have attached an IPSEC_IN.
3578 	 */
3579 	ASSERT(mp->b_datap->db_type == M_DATA);
3580 
3581 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3582 		return;
3583 	}
3584 
3585 	bzero(&icmph, sizeof (icmph_t));
3586 	icmph.icmph_type = ICMP_REDIRECT;
3587 	icmph.icmph_code = 1;
3588 	icmph.icmph_rd_gateway = gateway;
3589 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3590 	/* Redirects sent by router, and router is global zone */
3591 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3592 }
3593 
3594 /*
3595  * Generate an ICMP time exceeded message.
3596  */
3597 void
3598 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3599     ip_stack_t *ipst)
3600 {
3601 	icmph_t	icmph;
3602 	boolean_t mctl_present;
3603 	mblk_t *first_mp;
3604 
3605 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3606 
3607 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3608 		if (mctl_present)
3609 			freeb(first_mp);
3610 		return;
3611 	}
3612 
3613 	bzero(&icmph, sizeof (icmph_t));
3614 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3615 	icmph.icmph_code = code;
3616 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3617 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3618 	    ipst);
3619 }
3620 
3621 /*
3622  * Generate an ICMP unreachable message.
3623  */
3624 void
3625 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3626     ip_stack_t *ipst)
3627 {
3628 	icmph_t	icmph;
3629 	mblk_t *first_mp;
3630 	boolean_t mctl_present;
3631 
3632 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3633 
3634 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3635 		if (mctl_present)
3636 			freeb(first_mp);
3637 		return;
3638 	}
3639 
3640 	bzero(&icmph, sizeof (icmph_t));
3641 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3642 	icmph.icmph_code = code;
3643 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3644 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3645 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3646 	    zoneid, ipst);
3647 }
3648 
3649 /*
3650  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3651  * duplicate.  As long as someone else holds the address, the interface will
3652  * stay down.  When that conflict goes away, the interface is brought back up.
3653  * This is done so that accidental shutdowns of addresses aren't made
3654  * permanent.  Your server will recover from a failure.
3655  *
3656  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3657  * user space process (dhcpagent).
3658  *
3659  * Recovery completes if ARP reports that the address is now ours (via
3660  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3661  *
3662  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3663  */
3664 static void
3665 ipif_dup_recovery(void *arg)
3666 {
3667 	ipif_t *ipif = arg;
3668 	ill_t *ill = ipif->ipif_ill;
3669 	mblk_t *arp_add_mp;
3670 	mblk_t *arp_del_mp;
3671 	ip_stack_t *ipst = ill->ill_ipst;
3672 
3673 	ipif->ipif_recovery_id = 0;
3674 
3675 	/*
3676 	 * No lock needed for moving or condemned check, as this is just an
3677 	 * optimization.
3678 	 */
3679 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3680 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3681 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3682 		/* No reason to try to bring this address back. */
3683 		return;
3684 	}
3685 
3686 	/* ACE_F_UNVERIFIED restarts DAD */
3687 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3688 		goto alloc_fail;
3689 
3690 	if (ipif->ipif_arp_del_mp == NULL) {
3691 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3692 			goto alloc_fail;
3693 		ipif->ipif_arp_del_mp = arp_del_mp;
3694 	}
3695 
3696 	putnext(ill->ill_rq, arp_add_mp);
3697 	return;
3698 
3699 alloc_fail:
3700 	/*
3701 	 * On allocation failure, just restart the timer.  Note that the ipif
3702 	 * is down here, so no other thread could be trying to start a recovery
3703 	 * timer.  The ill_lock protects the condemned flag and the recovery
3704 	 * timer ID.
3705 	 */
3706 	freemsg(arp_add_mp);
3707 	mutex_enter(&ill->ill_lock);
3708 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3709 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3710 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3711 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3712 	}
3713 	mutex_exit(&ill->ill_lock);
3714 }
3715 
3716 /*
3717  * This is for exclusive changes due to ARP.  Either tear down an interface due
3718  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3719  */
3720 /* ARGSUSED */
3721 static void
3722 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3723 {
3724 	ill_t	*ill = rq->q_ptr;
3725 	arh_t *arh;
3726 	ipaddr_t src;
3727 	ipif_t	*ipif;
3728 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3729 	char hbuf[MAC_STR_LEN];
3730 	char sbuf[INET_ADDRSTRLEN];
3731 	const char *failtype;
3732 	boolean_t bring_up;
3733 	ip_stack_t *ipst = ill->ill_ipst;
3734 
3735 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3736 	case AR_CN_READY:
3737 		failtype = NULL;
3738 		bring_up = B_TRUE;
3739 		break;
3740 	case AR_CN_FAILED:
3741 		failtype = "in use";
3742 		bring_up = B_FALSE;
3743 		break;
3744 	default:
3745 		failtype = "claimed";
3746 		bring_up = B_FALSE;
3747 		break;
3748 	}
3749 
3750 	arh = (arh_t *)mp->b_cont->b_rptr;
3751 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3752 
3753 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3754 	    sizeof (hbuf));
3755 	(void) ip_dot_addr(src, sbuf);
3756 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3757 
3758 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3759 		    ipif->ipif_lcl_addr != src) {
3760 			continue;
3761 		}
3762 
3763 		/*
3764 		 * If we failed on a recovery probe, then restart the timer to
3765 		 * try again later.
3766 		 */
3767 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3768 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3769 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3770 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3771 		    ipst->ips_ip_dup_recovery > 0 &&
3772 		    ipif->ipif_recovery_id == 0) {
3773 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3774 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3775 			continue;
3776 		}
3777 
3778 		/*
3779 		 * If what we're trying to do has already been done, then do
3780 		 * nothing.
3781 		 */
3782 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3783 			continue;
3784 
3785 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3786 
3787 		if (failtype == NULL) {
3788 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3789 			    ibuf);
3790 		} else {
3791 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3792 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3793 		}
3794 
3795 		if (bring_up) {
3796 			ASSERT(ill->ill_dl_up);
3797 			/*
3798 			 * Free up the ARP delete message so we can allocate
3799 			 * a fresh one through the normal path.
3800 			 */
3801 			freemsg(ipif->ipif_arp_del_mp);
3802 			ipif->ipif_arp_del_mp = NULL;
3803 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3804 			    EINPROGRESS) {
3805 				ipif->ipif_addr_ready = 1;
3806 				(void) ipif_up_done(ipif);
3807 				ASSERT(ill->ill_move_ipif == NULL);
3808 			}
3809 			continue;
3810 		}
3811 
3812 		mutex_enter(&ill->ill_lock);
3813 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3814 		ipif->ipif_flags |= IPIF_DUPLICATE;
3815 		ill->ill_ipif_dup_count++;
3816 		mutex_exit(&ill->ill_lock);
3817 		/*
3818 		 * Already exclusive on the ill; no need to handle deferred
3819 		 * processing here.
3820 		 */
3821 		(void) ipif_down(ipif, NULL, NULL);
3822 		ipif_down_tail(ipif);
3823 		mutex_enter(&ill->ill_lock);
3824 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3825 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3826 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3827 		    ipst->ips_ip_dup_recovery > 0) {
3828 			ASSERT(ipif->ipif_recovery_id == 0);
3829 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3830 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3831 		}
3832 		mutex_exit(&ill->ill_lock);
3833 	}
3834 	freemsg(mp);
3835 }
3836 
3837 /* ARGSUSED */
3838 static void
3839 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3840 {
3841 	ill_t	*ill = rq->q_ptr;
3842 	arh_t *arh;
3843 	ipaddr_t src;
3844 	ipif_t	*ipif;
3845 
3846 	arh = (arh_t *)mp->b_cont->b_rptr;
3847 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3848 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3849 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3850 			(void) ipif_resolver_up(ipif, Res_act_defend);
3851 	}
3852 	freemsg(mp);
3853 }
3854 
3855 /*
3856  * News from ARP.  ARP sends notification of interesting events down
3857  * to its clients using M_CTL messages with the interesting ARP packet
3858  * attached via b_cont.
3859  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3860  * queue as opposed to ARP sending the message to all the clients, i.e. all
3861  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3862  * table if a cache IRE is found to delete all the entries for the address in
3863  * the packet.
3864  */
3865 static void
3866 ip_arp_news(queue_t *q, mblk_t *mp)
3867 {
3868 	arcn_t		*arcn;
3869 	arh_t		*arh;
3870 	ire_t		*ire = NULL;
3871 	char		hbuf[MAC_STR_LEN];
3872 	char		sbuf[INET_ADDRSTRLEN];
3873 	ipaddr_t	src;
3874 	in6_addr_t	v6src;
3875 	boolean_t	isv6 = B_FALSE;
3876 	ipif_t		*ipif;
3877 	ill_t		*ill;
3878 	ip_stack_t	*ipst;
3879 
3880 	if (CONN_Q(q)) {
3881 		conn_t *connp = Q_TO_CONN(q);
3882 
3883 		ipst = connp->conn_netstack->netstack_ip;
3884 	} else {
3885 		ill_t *ill = (ill_t *)q->q_ptr;
3886 
3887 		ipst = ill->ill_ipst;
3888 	}
3889 
3890 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3891 		if (q->q_next) {
3892 			putnext(q, mp);
3893 		} else
3894 			freemsg(mp);
3895 		return;
3896 	}
3897 	arh = (arh_t *)mp->b_cont->b_rptr;
3898 	/* Is it one we are interested in? */
3899 	if (BE16_TO_U16(arh->arh_proto) == ETHERTYPE_IPV6) {
3900 		isv6 = B_TRUE;
3901 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3902 		    IPV6_ADDR_LEN);
3903 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3904 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3905 		    IP_ADDR_LEN);
3906 	} else {
3907 		freemsg(mp);
3908 		return;
3909 	}
3910 
3911 	ill = q->q_ptr;
3912 
3913 	arcn = (arcn_t *)mp->b_rptr;
3914 	switch (arcn->arcn_code) {
3915 	case AR_CN_BOGON:
3916 		/*
3917 		 * Someone is sending ARP packets with a source protocol
3918 		 * address that we have published and for which we believe our
3919 		 * entry is authoritative and (when ill_arp_extend is set)
3920 		 * verified to be unique on the network.
3921 		 *
3922 		 * The ARP module internally handles the cases where the sender
3923 		 * is just probing (for DAD) and where the hardware address of
3924 		 * a non-authoritative entry has changed.  Thus, these are the
3925 		 * real conflicts, and we have to do resolution.
3926 		 *
3927 		 * We back away quickly from the address if it's from DHCP or
3928 		 * otherwise temporary and hasn't been used recently (or at
3929 		 * all).  We'd like to include "deprecated" addresses here as
3930 		 * well (as there's no real reason to defend something we're
3931 		 * discarding), but IPMP "reuses" this flag to mean something
3932 		 * other than the standard meaning.
3933 		 *
3934 		 * If the ARP module above is not extended (meaning that it
3935 		 * doesn't know how to defend the address), then we just log
3936 		 * the problem as we always did and continue on.  It's not
3937 		 * right, but there's little else we can do, and those old ATM
3938 		 * users are going away anyway.
3939 		 */
3940 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3941 		    hbuf, sizeof (hbuf));
3942 		(void) ip_dot_addr(src, sbuf);
3943 		if (isv6) {
3944 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3945 			    ipst);
3946 		} else {
3947 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3948 		}
3949 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3950 			uint32_t now;
3951 			uint32_t maxage;
3952 			clock_t lused;
3953 			uint_t maxdefense;
3954 			uint_t defs;
3955 
3956 			/*
3957 			 * First, figure out if this address hasn't been used
3958 			 * in a while.  If it hasn't, then it's a better
3959 			 * candidate for abandoning.
3960 			 */
3961 			ipif = ire->ire_ipif;
3962 			ASSERT(ipif != NULL);
3963 			now = gethrestime_sec();
3964 			maxage = now - ire->ire_create_time;
3965 			if (maxage > ipst->ips_ip_max_temp_idle)
3966 				maxage = ipst->ips_ip_max_temp_idle;
3967 			lused = drv_hztousec(ddi_get_lbolt() -
3968 			    ire->ire_last_used_time) / MICROSEC + 1;
3969 			if (lused >= maxage && (ipif->ipif_flags &
3970 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3971 				maxdefense = ipst->ips_ip_max_temp_defend;
3972 			else
3973 				maxdefense = ipst->ips_ip_max_defend;
3974 
3975 			/*
3976 			 * Now figure out how many times we've defended
3977 			 * ourselves.  Ignore defenses that happened long in
3978 			 * the past.
3979 			 */
3980 			mutex_enter(&ire->ire_lock);
3981 			if ((defs = ire->ire_defense_count) > 0 &&
3982 			    now - ire->ire_defense_time >
3983 			    ipst->ips_ip_defend_interval) {
3984 				ire->ire_defense_count = defs = 0;
3985 			}
3986 			ire->ire_defense_count++;
3987 			ire->ire_defense_time = now;
3988 			mutex_exit(&ire->ire_lock);
3989 			ill_refhold(ill);
3990 			ire_refrele(ire);
3991 
3992 			/*
3993 			 * If we've defended ourselves too many times already,
3994 			 * then give up and tear down the interface(s) using
3995 			 * this address.  Otherwise, defend by sending out a
3996 			 * gratuitous ARP.
3997 			 */
3998 			if (defs >= maxdefense && ill->ill_arp_extend) {
3999 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4000 				    B_FALSE);
4001 			} else {
4002 				cmn_err(CE_WARN,
4003 				    "node %s is using our IP address %s on %s",
4004 				    hbuf, sbuf, ill->ill_name);
4005 				/*
4006 				 * If this is an old (ATM) ARP module, then
4007 				 * don't try to defend the address.  Remain
4008 				 * compatible with the old behavior.  Defend
4009 				 * only with new ARP.
4010 				 */
4011 				if (ill->ill_arp_extend) {
4012 					qwriter_ip(ill, q, mp, ip_arp_defend,
4013 					    NEW_OP, B_FALSE);
4014 				} else {
4015 					ill_refrele(ill);
4016 				}
4017 			}
4018 			return;
4019 		}
4020 		cmn_err(CE_WARN,
4021 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4022 		    hbuf, sbuf, ill->ill_name);
4023 		if (ire != NULL)
4024 			ire_refrele(ire);
4025 		break;
4026 	case AR_CN_ANNOUNCE:
4027 		if (isv6) {
4028 			/*
4029 			 * For XRESOLV interfaces.
4030 			 * Delete the IRE cache entry and NCE for this
4031 			 * v6 address
4032 			 */
4033 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4034 			/*
4035 			 * If v6src is a non-zero, it's a router address
4036 			 * as below. Do the same sort of thing to clean
4037 			 * out off-net IRE_CACHE entries that go through
4038 			 * the router.
4039 			 */
4040 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4041 				ire_walk_v6(ire_delete_cache_gw_v6,
4042 				    (char *)&v6src, ALL_ZONES, ipst);
4043 			}
4044 		} else {
4045 			nce_hw_map_t hwm;
4046 
4047 			/*
4048 			 * ARP gives us a copy of any packet where it thinks
4049 			 * the address has changed, so that we can update our
4050 			 * caches.  We're responsible for caching known answers
4051 			 * in the current design.  We check whether the
4052 			 * hardware address really has changed in all of our
4053 			 * entries that have cached this mapping, and if so, we
4054 			 * blow them away.  This way we will immediately pick
4055 			 * up the rare case of a host changing hardware
4056 			 * address.
4057 			 */
4058 			if (src == 0)
4059 				break;
4060 			hwm.hwm_addr = src;
4061 			hwm.hwm_hwlen = arh->arh_hlen;
4062 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4063 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4064 			ndp_walk_common(ipst->ips_ndp4, NULL,
4065 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4066 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4067 		}
4068 		break;
4069 	case AR_CN_READY:
4070 		/* No external v6 resolver has a contract to use this */
4071 		if (isv6)
4072 			break;
4073 		/* If the link is down, we'll retry this later */
4074 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4075 			break;
4076 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4077 		    NULL, NULL, ipst);
4078 		if (ipif != NULL) {
4079 			/*
4080 			 * If this is a duplicate recovery, then we now need to
4081 			 * go exclusive to bring this thing back up.
4082 			 */
4083 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4084 			    IPIF_DUPLICATE) {
4085 				ipif_refrele(ipif);
4086 				ill_refhold(ill);
4087 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4088 				    B_FALSE);
4089 				return;
4090 			}
4091 			/*
4092 			 * If this is the first notice that this address is
4093 			 * ready, then let the user know now.
4094 			 */
4095 			if ((ipif->ipif_flags & IPIF_UP) &&
4096 			    !ipif->ipif_addr_ready) {
4097 				ipif_mask_reply(ipif);
4098 				ipif_up_notify(ipif);
4099 			}
4100 			ipif->ipif_addr_ready = 1;
4101 			ipif_refrele(ipif);
4102 		}
4103 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4104 		if (ire != NULL) {
4105 			ire->ire_defense_count = 0;
4106 			ire_refrele(ire);
4107 		}
4108 		break;
4109 	case AR_CN_FAILED:
4110 		/* No external v6 resolver has a contract to use this */
4111 		if (isv6)
4112 			break;
4113 		if (!ill->ill_arp_extend) {
4114 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4115 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4116 			(void) ip_dot_addr(src, sbuf);
4117 
4118 			cmn_err(CE_WARN,
4119 			    "node %s is using our IP address %s on %s",
4120 			    hbuf, sbuf, ill->ill_name);
4121 			break;
4122 		}
4123 		ill_refhold(ill);
4124 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4125 		return;
4126 	}
4127 	freemsg(mp);
4128 }
4129 
4130 /*
4131  * Create a mblk suitable for carrying the interface index and/or source link
4132  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4133  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4134  * application.
4135  */
4136 mblk_t *
4137 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4138     ip_stack_t *ipst)
4139 {
4140 	mblk_t		*mp;
4141 	ip_pktinfo_t	*pinfo;
4142 	ipha_t 		*ipha;
4143 	struct ether_header *pether;
4144 	boolean_t	ipmp_ill_held = B_FALSE;
4145 
4146 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4147 	if (mp == NULL) {
4148 		ip1dbg(("ip_add_info: allocation failure.\n"));
4149 		return (data_mp);
4150 	}
4151 
4152 	ipha = (ipha_t *)data_mp->b_rptr;
4153 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4154 	bzero(pinfo, sizeof (ip_pktinfo_t));
4155 	pinfo->ip_pkt_flags = (uchar_t)flags;
4156 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4157 
4158 	pether = (struct ether_header *)((char *)ipha
4159 	    - sizeof (struct ether_header));
4160 
4161 	/*
4162 	 * Make sure the interface is an ethernet type, since this option
4163 	 * is currently supported only on this type of interface. Also make
4164 	 * sure we are pointing correctly above db_base.
4165 	 */
4166 	if ((flags & IPF_RECVSLLA) &&
4167 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4168 	    (ill->ill_type == IFT_ETHER) &&
4169 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4170 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4171 		bcopy(pether->ether_shost.ether_addr_octet,
4172 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4173 	} else {
4174 		/*
4175 		 * Clear the bit. Indicate to upper layer that IP is not
4176 		 * sending this ancillary info.
4177 		 */
4178 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4179 	}
4180 
4181 	/*
4182 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4183 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4184 	 * IPF_RECVADDR support on test addresses is not needed.)
4185 	 *
4186 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4187 	 * processing a packet looped back to an IPMP data address
4188 	 * (since those IRE_LOCALs are tied to IPMP ills).
4189 	 */
4190 	if (IS_UNDER_IPMP(ill)) {
4191 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4192 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4193 			freemsg(mp);
4194 			return (data_mp);
4195 		}
4196 		ipmp_ill_held = B_TRUE;
4197 	}
4198 
4199 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4200 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4201 	if (flags & IPF_RECVADDR) {
4202 		ipif_t	*ipif;
4203 		ire_t	*ire;
4204 
4205 		/*
4206 		 * Only valid for V4
4207 		 */
4208 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4209 		    (IPV4_VERSION << 4));
4210 
4211 		ipif = ipif_get_next_ipif(NULL, ill);
4212 		if (ipif != NULL) {
4213 			/*
4214 			 * Since a decision has already been made to deliver the
4215 			 * packet, there is no need to test for SECATTR and
4216 			 * ZONEONLY.
4217 			 * When a multicast packet is transmitted
4218 			 * a cache entry is created for the multicast address.
4219 			 * When delivering a copy of the packet or when new
4220 			 * packets are received we do not want to match on the
4221 			 * cached entry so explicitly match on
4222 			 * IRE_LOCAL and IRE_LOOPBACK
4223 			 */
4224 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4225 			    IRE_LOCAL | IRE_LOOPBACK,
4226 			    ipif, zoneid, NULL,
4227 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4228 			if (ire == NULL) {
4229 				/*
4230 				 * packet must have come on a different
4231 				 * interface.
4232 				 * Since a decision has already been made to
4233 				 * deliver the packet, there is no need to test
4234 				 * for SECATTR and ZONEONLY.
4235 				 * Only match on local and broadcast ire's.
4236 				 * See detailed comment above.
4237 				 */
4238 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4239 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4240 				    NULL, MATCH_IRE_TYPE, ipst);
4241 			}
4242 
4243 			if (ire == NULL) {
4244 				/*
4245 				 * This is either a multicast packet or
4246 				 * the address has been removed since
4247 				 * the packet was received.
4248 				 * Return INADDR_ANY so that normal source
4249 				 * selection occurs for the response.
4250 				 */
4251 
4252 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4253 			} else {
4254 				pinfo->ip_pkt_match_addr.s_addr =
4255 				    ire->ire_src_addr;
4256 				ire_refrele(ire);
4257 			}
4258 			ipif_refrele(ipif);
4259 		} else {
4260 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4261 		}
4262 	}
4263 
4264 	if (ipmp_ill_held)
4265 		ill_refrele(ill);
4266 
4267 	mp->b_datap->db_type = M_CTL;
4268 	mp->b_wptr += sizeof (ip_pktinfo_t);
4269 	mp->b_cont = data_mp;
4270 
4271 	return (mp);
4272 }
4273 
4274 /*
4275  * Used to determine the most accurate cred_t to use for TX.
4276  * First priority is SCM_UCRED having set the label in the message,
4277  * which is used for MLP on UDP. Second priority is the open credentials
4278  * with the peer's label (aka conn_effective_cred), which is needed for
4279  * MLP on TCP/SCTP and for MAC-Exempt. Last priority is the open credentials.
4280  */
4281 cred_t *
4282 ip_best_cred(mblk_t *mp, conn_t *connp, pid_t *pidp)
4283 {
4284 	cred_t *cr;
4285 
4286 	cr = msg_getcred(mp, pidp);
4287 	if (cr != NULL && crgetlabel(cr) != NULL)
4288 		return (cr);
4289 	*pidp = NOPID;
4290 	return (CONN_CRED(connp));
4291 }
4292 
4293 /*
4294  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4295  * part of the bind request.
4296  */
4297 
4298 boolean_t
4299 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4300 {
4301 	ipsec_in_t *ii;
4302 
4303 	ASSERT(policy_mp != NULL);
4304 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4305 
4306 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4307 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4308 
4309 	connp->conn_policy = ii->ipsec_in_policy;
4310 	ii->ipsec_in_policy = NULL;
4311 
4312 	if (ii->ipsec_in_action != NULL) {
4313 		if (connp->conn_latch == NULL) {
4314 			connp->conn_latch = iplatch_create();
4315 			if (connp->conn_latch == NULL)
4316 				return (B_FALSE);
4317 		}
4318 		ipsec_latch_inbound(connp->conn_latch, ii);
4319 	}
4320 	return (B_TRUE);
4321 }
4322 
4323 /*
4324  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4325  * and to arrange for power-fanout assist.  The ULP is identified by
4326  * adding a single byte at the end of the original bind message.
4327  * A ULP other than UDP or TCP that wishes to be recognized passes
4328  * down a bind with a zero length address.
4329  *
4330  * The binding works as follows:
4331  * - A zero byte address means just bind to the protocol.
4332  * - A four byte address is treated as a request to validate
4333  *   that the address is a valid local address, appropriate for
4334  *   an application to bind to. This does not affect any fanout
4335  *   information in IP.
4336  * - A sizeof sin_t byte address is used to bind to only the local address
4337  *   and port.
4338  * - A sizeof ipa_conn_t byte address contains complete fanout information
4339  *   consisting of local and remote addresses and ports.  In
4340  *   this case, the addresses are both validated as appropriate
4341  *   for this operation, and, if so, the information is retained
4342  *   for use in the inbound fanout.
4343  *
4344  * The ULP (except in the zero-length bind) can append an
4345  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4346  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4347  * a copy of the source or destination IRE (source for local bind;
4348  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4349  * policy information contained should be copied on to the conn.
4350  *
4351  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4352  */
4353 mblk_t *
4354 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4355 {
4356 	ssize_t		len;
4357 	struct T_bind_req	*tbr;
4358 	sin_t		*sin;
4359 	ipa_conn_t	*ac;
4360 	uchar_t		*ucp;
4361 	int		error = 0;
4362 	int		protocol;
4363 	ipa_conn_x_t	*acx;
4364 	cred_t		*cr;
4365 
4366 	/*
4367 	 * All Solaris components should pass a db_credp
4368 	 * for this TPI message, hence we ASSERT.
4369 	 * But in case there is some other M_PROTO that looks
4370 	 * like a TPI message sent by some other kernel
4371 	 * component, we check and return an error.
4372 	 */
4373 	cr = msg_getcred(mp, NULL);
4374 	ASSERT(cr != NULL);
4375 	if (cr == NULL) {
4376 		error = EINVAL;
4377 		goto bad_addr;
4378 	}
4379 
4380 	ASSERT(!connp->conn_af_isv6);
4381 	connp->conn_pkt_isv6 = B_FALSE;
4382 
4383 	len = MBLKL(mp);
4384 	if (len < (sizeof (*tbr) + 1)) {
4385 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4386 		    "ip_bind: bogus msg, len %ld", len);
4387 		/* XXX: Need to return something better */
4388 		goto bad_addr;
4389 	}
4390 	/* Back up and extract the protocol identifier. */
4391 	mp->b_wptr--;
4392 	protocol = *mp->b_wptr & 0xFF;
4393 	tbr = (struct T_bind_req *)mp->b_rptr;
4394 	/* Reset the message type in preparation for shipping it back. */
4395 	DB_TYPE(mp) = M_PCPROTO;
4396 
4397 	connp->conn_ulp = (uint8_t)protocol;
4398 
4399 	/*
4400 	 * Check for a zero length address.  This is from a protocol that
4401 	 * wants to register to receive all packets of its type.
4402 	 */
4403 	if (tbr->ADDR_length == 0) {
4404 		/*
4405 		 * These protocols are now intercepted in ip_bind_v6().
4406 		 * Reject protocol-level binds here for now.
4407 		 *
4408 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4409 		 * so that the protocol type cannot be SCTP.
4410 		 */
4411 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4412 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4413 			goto bad_addr;
4414 		}
4415 
4416 		/*
4417 		 *
4418 		 * The udp module never sends down a zero-length address,
4419 		 * and allowing this on a labeled system will break MLP
4420 		 * functionality.
4421 		 */
4422 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4423 			goto bad_addr;
4424 
4425 		if (connp->conn_mac_mode != CONN_MAC_DEFAULT)
4426 			goto bad_addr;
4427 
4428 		/* No hash here really.  The table is big enough. */
4429 		connp->conn_srcv6 = ipv6_all_zeros;
4430 
4431 		ipcl_proto_insert(connp, protocol);
4432 
4433 		tbr->PRIM_type = T_BIND_ACK;
4434 		return (mp);
4435 	}
4436 
4437 	/* Extract the address pointer from the message. */
4438 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4439 	    tbr->ADDR_length);
4440 	if (ucp == NULL) {
4441 		ip1dbg(("ip_bind: no address\n"));
4442 		goto bad_addr;
4443 	}
4444 	if (!OK_32PTR(ucp)) {
4445 		ip1dbg(("ip_bind: unaligned address\n"));
4446 		goto bad_addr;
4447 	}
4448 
4449 	switch (tbr->ADDR_length) {
4450 	default:
4451 		ip1dbg(("ip_bind: bad address length %d\n",
4452 		    (int)tbr->ADDR_length));
4453 		goto bad_addr;
4454 
4455 	case IP_ADDR_LEN:
4456 		/* Verification of local address only */
4457 		error = ip_bind_laddr_v4(connp, &mp->b_cont, protocol,
4458 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4459 		break;
4460 
4461 	case sizeof (sin_t):
4462 		sin = (sin_t *)ucp;
4463 		error = ip_bind_laddr_v4(connp, &mp->b_cont, protocol,
4464 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4465 		break;
4466 
4467 	case sizeof (ipa_conn_t):
4468 		ac = (ipa_conn_t *)ucp;
4469 		/* For raw socket, the local port is not set. */
4470 		if (ac->ac_lport == 0)
4471 			ac->ac_lport = connp->conn_lport;
4472 		/* Always verify destination reachability. */
4473 		error = ip_bind_connected_v4(connp, &mp->b_cont, protocol,
4474 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4475 		    B_TRUE, B_TRUE, cr);
4476 		break;
4477 
4478 	case sizeof (ipa_conn_x_t):
4479 		acx = (ipa_conn_x_t *)ucp;
4480 		/*
4481 		 * Whether or not to verify destination reachability depends
4482 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4483 		 */
4484 		error = ip_bind_connected_v4(connp, &mp->b_cont, protocol,
4485 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4486 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4487 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4488 		break;
4489 	}
4490 	ASSERT(error != EINPROGRESS);
4491 	if (error != 0)
4492 		goto bad_addr;
4493 
4494 	/* Send it home. */
4495 	mp->b_datap->db_type = M_PCPROTO;
4496 	tbr->PRIM_type = T_BIND_ACK;
4497 	return (mp);
4498 
4499 bad_addr:
4500 	/*
4501 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4502 	 * a unix errno.
4503 	 */
4504 	if (error > 0)
4505 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4506 	else
4507 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4508 	return (mp);
4509 }
4510 
4511 /*
4512  * Here address is verified to be a valid local address.
4513  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4514  * address is also considered a valid local address.
4515  * In the case of a broadcast/multicast address, however, the
4516  * upper protocol is expected to reset the src address
4517  * to 0 if it sees a IRE_BROADCAST type returned so that
4518  * no packets are emitted with broadcast/multicast address as
4519  * source address (that violates hosts requirements RFC 1122)
4520  * The addresses valid for bind are:
4521  *	(1) - INADDR_ANY (0)
4522  *	(2) - IP address of an UP interface
4523  *	(3) - IP address of a DOWN interface
4524  *	(4) - valid local IP broadcast addresses. In this case
4525  *	the conn will only receive packets destined to
4526  *	the specified broadcast address.
4527  *	(5) - a multicast address. In this case
4528  *	the conn will only receive packets destined to
4529  *	the specified multicast address. Note: the
4530  *	application still has to issue an
4531  *	IP_ADD_MEMBERSHIP socket option.
4532  *
4533  * On error, return -1 for TBADADDR otherwise pass the
4534  * errno with TSYSERR reply.
4535  *
4536  * In all the above cases, the bound address must be valid in the current zone.
4537  * When the address is loopback, multicast or broadcast, there might be many
4538  * matching IREs so bind has to look up based on the zone.
4539  *
4540  * Note: lport is in network byte order.
4541  *
4542  */
4543 int
4544 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4545     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4546 {
4547 	int		error = 0;
4548 	ire_t		*src_ire;
4549 	zoneid_t	zoneid;
4550 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4551 	mblk_t		*mp = NULL;
4552 	boolean_t	ire_requested = B_FALSE;
4553 	boolean_t	ipsec_policy_set = B_FALSE;
4554 
4555 	if (mpp)
4556 		mp = *mpp;
4557 
4558 	if (mp != NULL) {
4559 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4560 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4561 	}
4562 
4563 	/*
4564 	 * If it was previously connected, conn_fully_bound would have
4565 	 * been set.
4566 	 */
4567 	connp->conn_fully_bound = B_FALSE;
4568 
4569 	src_ire = NULL;
4570 
4571 	zoneid = IPCL_ZONEID(connp);
4572 
4573 	if (src_addr) {
4574 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4575 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4576 		/*
4577 		 * If an address other than 0.0.0.0 is requested,
4578 		 * we verify that it is a valid address for bind
4579 		 * Note: Following code is in if-else-if form for
4580 		 * readability compared to a condition check.
4581 		 */
4582 		/* LINTED - statement has no consequence */
4583 		if (IRE_IS_LOCAL(src_ire)) {
4584 			/*
4585 			 * (2) Bind to address of local UP interface
4586 			 */
4587 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4588 			/*
4589 			 * (4) Bind to broadcast address
4590 			 * Note: permitted only from transports that
4591 			 * request IRE
4592 			 */
4593 			if (!ire_requested)
4594 				error = EADDRNOTAVAIL;
4595 		} else {
4596 			/*
4597 			 * (3) Bind to address of local DOWN interface
4598 			 * (ipif_lookup_addr() looks up all interfaces
4599 			 * but we do not get here for UP interfaces
4600 			 * - case (2) above)
4601 			 */
4602 			/* LINTED - statement has no consequent */
4603 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4604 				/* The address exists */
4605 			} else if (CLASSD(src_addr)) {
4606 				error = 0;
4607 				if (src_ire != NULL)
4608 					ire_refrele(src_ire);
4609 				/*
4610 				 * (5) bind to multicast address.
4611 				 * Fake out the IRE returned to upper
4612 				 * layer to be a broadcast IRE.
4613 				 */
4614 				src_ire = ire_ctable_lookup(
4615 				    INADDR_BROADCAST, INADDR_ANY,
4616 				    IRE_BROADCAST, NULL, zoneid, NULL,
4617 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4618 				    ipst);
4619 				if (src_ire == NULL || !ire_requested)
4620 					error = EADDRNOTAVAIL;
4621 			} else {
4622 				/*
4623 				 * Not a valid address for bind
4624 				 */
4625 				error = EADDRNOTAVAIL;
4626 			}
4627 		}
4628 		if (error) {
4629 			/* Red Alert!  Attempting to be a bogon! */
4630 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4631 			    ntohl(src_addr)));
4632 			goto bad_addr;
4633 		}
4634 	}
4635 
4636 	/*
4637 	 * Allow setting new policies. For example, disconnects come
4638 	 * down as ipa_t bind. As we would have set conn_policy_cached
4639 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4640 	 * can change after the disconnect.
4641 	 */
4642 	connp->conn_policy_cached = B_FALSE;
4643 
4644 	/*
4645 	 * If not fanout_insert this was just an address verification
4646 	 */
4647 	if (fanout_insert) {
4648 		/*
4649 		 * The addresses have been verified. Time to insert in
4650 		 * the correct fanout list.
4651 		 */
4652 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4653 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4654 		connp->conn_lport = lport;
4655 		connp->conn_fport = 0;
4656 		/*
4657 		 * Do we need to add a check to reject Multicast packets
4658 		 */
4659 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4660 	}
4661 
4662 	if (error == 0) {
4663 		if (ire_requested) {
4664 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4665 				error = -1;
4666 				/* Falls through to bad_addr */
4667 			}
4668 		} else if (ipsec_policy_set) {
4669 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4670 				error = -1;
4671 				/* Falls through to bad_addr */
4672 			}
4673 		}
4674 	}
4675 bad_addr:
4676 	if (error != 0) {
4677 		if (connp->conn_anon_port) {
4678 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4679 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4680 			    B_FALSE);
4681 		}
4682 		connp->conn_mlp_type = mlptSingle;
4683 	}
4684 	if (src_ire != NULL)
4685 		IRE_REFRELE(src_ire);
4686 	return (error);
4687 }
4688 
4689 int
4690 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4691     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4692 {
4693 	int error;
4694 
4695 	ASSERT(!connp->conn_af_isv6);
4696 	connp->conn_pkt_isv6 = B_FALSE;
4697 	connp->conn_ulp = protocol;
4698 
4699 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4700 	    fanout_insert);
4701 	if (error < 0)
4702 		error = -TBADADDR;
4703 	return (error);
4704 }
4705 
4706 /*
4707  * Verify that both the source and destination addresses
4708  * are valid.  If verify_dst is false, then the destination address may be
4709  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4710  * destination reachability, while tunnels do not.
4711  * Note that we allow connect to broadcast and multicast
4712  * addresses when ire_requested is set. Thus the ULP
4713  * has to check for IRE_BROADCAST and multicast.
4714  *
4715  * Returns zero if ok.
4716  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4717  * (for use with TSYSERR reply).
4718  *
4719  * Note: lport and fport are in network byte order.
4720  */
4721 int
4722 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4723     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4724     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4725 {
4726 
4727 	ire_t		*src_ire;
4728 	ire_t		*dst_ire;
4729 	int		error = 0;
4730 	ire_t		*sire = NULL;
4731 	ire_t		*md_dst_ire = NULL;
4732 	ire_t		*lso_dst_ire = NULL;
4733 	ill_t		*ill = NULL;
4734 	zoneid_t	zoneid;
4735 	ipaddr_t	src_addr = *src_addrp;
4736 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4737 	mblk_t		*mp = NULL;
4738 	boolean_t	ire_requested = B_FALSE;
4739 	boolean_t	ipsec_policy_set = B_FALSE;
4740 	ts_label_t	*tsl = NULL;
4741 	cred_t		*effective_cred = NULL;
4742 
4743 	if (mpp)
4744 		mp = *mpp;
4745 
4746 	if (mp != NULL) {
4747 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4748 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4749 	}
4750 
4751 	src_ire = dst_ire = NULL;
4752 
4753 	/*
4754 	 * If we never got a disconnect before, clear it now.
4755 	 */
4756 	connp->conn_fully_bound = B_FALSE;
4757 
4758 	zoneid = IPCL_ZONEID(connp);
4759 
4760 	/*
4761 	 * Check whether Trusted Solaris policy allows communication with this
4762 	 * host, and pretend that the destination is unreachable if not.
4763 	 *
4764 	 * This is never a problem for TCP, since that transport is known to
4765 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4766 	 * handling.  If the remote is unreachable, it will be detected at that
4767 	 * point, so there's no reason to check it here.
4768 	 *
4769 	 * Note that for sendto (and other datagram-oriented friends), this
4770 	 * check is done as part of the data path label computation instead.
4771 	 * The check here is just to make non-TCP connect() report the right
4772 	 * error.
4773 	 */
4774 	if (is_system_labeled() && !IPCL_IS_TCP(connp)) {
4775 		if ((error = tsol_check_dest(cr, &dst_addr, IPV4_VERSION,
4776 		    connp->conn_mac_mode, &effective_cred)) != 0) {
4777 			if (ip_debug > 2) {
4778 				pr_addr_dbg(
4779 				    "ip_bind_connected_v4:"
4780 				    " no label for dst %s\n",
4781 				    AF_INET, &dst_addr);
4782 			}
4783 			goto bad_addr;
4784 		}
4785 
4786 		/*
4787 		 * tsol_check_dest() may have created a new cred with
4788 		 * a modified security label. Use that cred if it exists
4789 		 * for ire lookups.
4790 		 */
4791 		if (effective_cred == NULL) {
4792 			tsl = crgetlabel(cr);
4793 		} else {
4794 			tsl = crgetlabel(effective_cred);
4795 		}
4796 	}
4797 
4798 	if (CLASSD(dst_addr)) {
4799 		/* Pick up an IRE_BROADCAST */
4800 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4801 		    NULL, zoneid, tsl,
4802 		    (MATCH_IRE_RECURSIVE |
4803 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4804 		    MATCH_IRE_SECATTR), ipst);
4805 	} else {
4806 		/*
4807 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4808 		 * and onlink ipif is not found set ENETUNREACH error.
4809 		 */
4810 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4811 			ipif_t *ipif;
4812 
4813 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4814 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4815 			if (ipif == NULL) {
4816 				error = ENETUNREACH;
4817 				goto bad_addr;
4818 			}
4819 			ipif_refrele(ipif);
4820 		}
4821 
4822 		if (connp->conn_nexthop_set) {
4823 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4824 			    0, 0, NULL, NULL, zoneid, tsl,
4825 			    MATCH_IRE_SECATTR, ipst);
4826 		} else {
4827 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4828 			    &sire, zoneid, tsl,
4829 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4830 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4831 			    MATCH_IRE_SECATTR), ipst);
4832 		}
4833 	}
4834 	/*
4835 	 * dst_ire can't be a broadcast when not ire_requested.
4836 	 * We also prevent ire's with src address INADDR_ANY to
4837 	 * be used, which are created temporarily for
4838 	 * sending out packets from endpoints that have
4839 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4840 	 * reachable.  If verify_dst is false, the destination needn't be
4841 	 * reachable.
4842 	 *
4843 	 * If we match on a reject or black hole, then we've got a
4844 	 * local failure.  May as well fail out the connect() attempt,
4845 	 * since it's never going to succeed.
4846 	 */
4847 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4848 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4849 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4850 		/*
4851 		 * If we're verifying destination reachability, we always want
4852 		 * to complain here.
4853 		 *
4854 		 * If we're not verifying destination reachability but the
4855 		 * destination has a route, we still want to fail on the
4856 		 * temporary address and broadcast address tests.
4857 		 */
4858 		if (verify_dst || (dst_ire != NULL)) {
4859 			if (ip_debug > 2) {
4860 				pr_addr_dbg("ip_bind_connected_v4:"
4861 				    "bad connected dst %s\n",
4862 				    AF_INET, &dst_addr);
4863 			}
4864 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4865 				error = ENETUNREACH;
4866 			else
4867 				error = EHOSTUNREACH;
4868 			goto bad_addr;
4869 		}
4870 	}
4871 
4872 	/*
4873 	 * If the app does a connect(), it means that it will most likely
4874 	 * send more than 1 packet to the destination.  It makes sense
4875 	 * to clear the temporary flag.
4876 	 */
4877 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4878 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4879 		irb_t *irb = dst_ire->ire_bucket;
4880 
4881 		rw_enter(&irb->irb_lock, RW_WRITER);
4882 		/*
4883 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4884 		 * the lock to guarantee irb_tmp_ire_cnt.
4885 		 */
4886 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4887 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4888 			irb->irb_tmp_ire_cnt--;
4889 		}
4890 		rw_exit(&irb->irb_lock);
4891 	}
4892 
4893 	/*
4894 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4895 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4896 	 * eligibility tests for passive connects are handled separately
4897 	 * through tcp_adapt_ire().  We do this before the source address
4898 	 * selection, because dst_ire may change after a call to
4899 	 * ipif_select_source().  This is a best-effort check, as the
4900 	 * packet for this connection may not actually go through
4901 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4902 	 * calling ip_newroute().  This is why we further check on the
4903 	 * IRE during LSO/Multidata packet transmission in
4904 	 * tcp_lsosend()/tcp_multisend().
4905 	 */
4906 	if (!ipsec_policy_set && dst_ire != NULL &&
4907 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4908 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4909 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4910 			lso_dst_ire = dst_ire;
4911 			IRE_REFHOLD(lso_dst_ire);
4912 		} else if (ipst->ips_ip_multidata_outbound &&
4913 		    ILL_MDT_CAPABLE(ill)) {
4914 			md_dst_ire = dst_ire;
4915 			IRE_REFHOLD(md_dst_ire);
4916 		}
4917 	}
4918 
4919 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4920 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4921 		/*
4922 		 * If the IRE belongs to a different zone, look for a matching
4923 		 * route in the forwarding table and use the source address from
4924 		 * that route.
4925 		 */
4926 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4927 		    zoneid, 0, NULL,
4928 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4929 		    MATCH_IRE_RJ_BHOLE, ipst);
4930 		if (src_ire == NULL) {
4931 			error = EHOSTUNREACH;
4932 			goto bad_addr;
4933 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4934 			if (!(src_ire->ire_type & IRE_HOST))
4935 				error = ENETUNREACH;
4936 			else
4937 				error = EHOSTUNREACH;
4938 			goto bad_addr;
4939 		}
4940 		if (src_addr == INADDR_ANY)
4941 			src_addr = src_ire->ire_src_addr;
4942 		ire_refrele(src_ire);
4943 		src_ire = NULL;
4944 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4945 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4946 			src_addr = sire->ire_src_addr;
4947 			ire_refrele(dst_ire);
4948 			dst_ire = sire;
4949 			sire = NULL;
4950 		} else {
4951 			/*
4952 			 * Pick a source address so that a proper inbound
4953 			 * load spreading would happen.
4954 			 */
4955 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
4956 			ipif_t *src_ipif = NULL;
4957 			ire_t *ipif_ire;
4958 
4959 			/*
4960 			 * Supply a local source address such that inbound
4961 			 * load spreading happens.
4962 			 *
4963 			 * Determine the best source address on this ill for
4964 			 * the destination.
4965 			 *
4966 			 * 1) For broadcast, we should return a broadcast ire
4967 			 *    found above so that upper layers know that the
4968 			 *    destination address is a broadcast address.
4969 			 *
4970 			 * 2) If the ipif is DEPRECATED, select a better
4971 			 *    source address.  Similarly, if the ipif is on
4972 			 *    the IPMP meta-interface, pick a source address
4973 			 *    at random to improve inbound load spreading.
4974 			 *
4975 			 * 3) If the outgoing interface is part of a usesrc
4976 			 *    group, then try selecting a source address from
4977 			 *    the usesrc ILL.
4978 			 */
4979 			if ((dst_ire->ire_zoneid != zoneid &&
4980 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4981 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4982 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4983 			    (IS_IPMP(ire_ill) ||
4984 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4985 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
4986 				/*
4987 				 * If the destination is reachable via a
4988 				 * given gateway, the selected source address
4989 				 * should be in the same subnet as the gateway.
4990 				 * Otherwise, the destination is not reachable.
4991 				 *
4992 				 * If there are no interfaces on the same subnet
4993 				 * as the destination, ipif_select_source gives
4994 				 * first non-deprecated interface which might be
4995 				 * on a different subnet than the gateway.
4996 				 * This is not desirable. Hence pass the dst_ire
4997 				 * source address to ipif_select_source.
4998 				 * It is sure that the destination is reachable
4999 				 * with the dst_ire source address subnet.
5000 				 * So passing dst_ire source address to
5001 				 * ipif_select_source will make sure that the
5002 				 * selected source will be on the same subnet
5003 				 * as dst_ire source address.
5004 				 */
5005 				ipaddr_t saddr =
5006 				    dst_ire->ire_ipif->ipif_src_addr;
5007 				src_ipif = ipif_select_source(ire_ill,
5008 				    saddr, zoneid);
5009 				if (src_ipif != NULL) {
5010 					if (IS_VNI(src_ipif->ipif_ill)) {
5011 						/*
5012 						 * For VNI there is no
5013 						 * interface route
5014 						 */
5015 						src_addr =
5016 						    src_ipif->ipif_src_addr;
5017 					} else {
5018 						ipif_ire =
5019 						    ipif_to_ire(src_ipif);
5020 						if (ipif_ire != NULL) {
5021 							IRE_REFRELE(dst_ire);
5022 							dst_ire = ipif_ire;
5023 						}
5024 						src_addr =
5025 						    dst_ire->ire_src_addr;
5026 					}
5027 					ipif_refrele(src_ipif);
5028 				} else {
5029 					src_addr = dst_ire->ire_src_addr;
5030 				}
5031 			} else {
5032 				src_addr = dst_ire->ire_src_addr;
5033 			}
5034 		}
5035 	}
5036 
5037 	/*
5038 	 * We do ire_route_lookup() here (and not
5039 	 * interface lookup as we assert that
5040 	 * src_addr should only come from an
5041 	 * UP interface for hard binding.
5042 	 */
5043 	ASSERT(src_ire == NULL);
5044 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5045 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5046 	/* src_ire must be a local|loopback */
5047 	if (!IRE_IS_LOCAL(src_ire)) {
5048 		if (ip_debug > 2) {
5049 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5050 			    "src %s\n", AF_INET, &src_addr);
5051 		}
5052 		error = EADDRNOTAVAIL;
5053 		goto bad_addr;
5054 	}
5055 
5056 	/*
5057 	 * If the source address is a loopback address, the
5058 	 * destination had best be local or multicast.
5059 	 * The transports that can't handle multicast will reject
5060 	 * those addresses.
5061 	 */
5062 	if (src_ire->ire_type == IRE_LOOPBACK &&
5063 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5064 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5065 		error = -1;
5066 		goto bad_addr;
5067 	}
5068 
5069 	/*
5070 	 * Allow setting new policies. For example, disconnects come
5071 	 * down as ipa_t bind. As we would have set conn_policy_cached
5072 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5073 	 * can change after the disconnect.
5074 	 */
5075 	connp->conn_policy_cached = B_FALSE;
5076 
5077 	/*
5078 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5079 	 * can handle their passed-in conn's.
5080 	 */
5081 
5082 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5083 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5084 	connp->conn_lport = lport;
5085 	connp->conn_fport = fport;
5086 	*src_addrp = src_addr;
5087 
5088 	ASSERT(!(ipsec_policy_set && ire_requested));
5089 	if (ire_requested) {
5090 		iulp_t *ulp_info = NULL;
5091 
5092 		/*
5093 		 * Note that sire will not be NULL if this is an off-link
5094 		 * connection and there is not cache for that dest yet.
5095 		 *
5096 		 * XXX Because of an existing bug, if there are multiple
5097 		 * default routes, the IRE returned now may not be the actual
5098 		 * default route used (default routes are chosen in a
5099 		 * round robin fashion).  So if the metrics for different
5100 		 * default routes are different, we may return the wrong
5101 		 * metrics.  This will not be a problem if the existing
5102 		 * bug is fixed.
5103 		 */
5104 		if (sire != NULL) {
5105 			ulp_info = &(sire->ire_uinfo);
5106 		}
5107 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5108 			error = -1;
5109 			goto bad_addr;
5110 		}
5111 		mp = *mpp;
5112 	} else if (ipsec_policy_set) {
5113 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5114 			error = -1;
5115 			goto bad_addr;
5116 		}
5117 	}
5118 
5119 	/*
5120 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5121 	 * we'll cache that.  If we don't, we'll inherit global policy.
5122 	 *
5123 	 * We can't insert until the conn reflects the policy. Note that
5124 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5125 	 * connections where we don't have a policy. This is to prevent
5126 	 * global policy lookups in the inbound path.
5127 	 *
5128 	 * If we insert before we set conn_policy_cached,
5129 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5130 	 * because global policy cound be non-empty. We normally call
5131 	 * ipsec_check_policy() for conn_policy_cached connections only if
5132 	 * ipc_in_enforce_policy is set. But in this case,
5133 	 * conn_policy_cached can get set anytime since we made the
5134 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5135 	 * called, which will make the above assumption false.  Thus, we
5136 	 * need to insert after we set conn_policy_cached.
5137 	 */
5138 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5139 		goto bad_addr;
5140 
5141 	if (fanout_insert) {
5142 		/*
5143 		 * The addresses have been verified. Time to insert in
5144 		 * the correct fanout list.
5145 		 */
5146 		error = ipcl_conn_insert(connp, protocol, src_addr,
5147 		    dst_addr, connp->conn_ports);
5148 	}
5149 
5150 	if (error == 0) {
5151 		connp->conn_fully_bound = B_TRUE;
5152 		/*
5153 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5154 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5155 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5156 		 * ip_xxinfo_return(), which performs further checks
5157 		 * against them and upon success, returns the LSO/MDT info
5158 		 * mblk which we will attach to the bind acknowledgment.
5159 		 */
5160 		if (lso_dst_ire != NULL) {
5161 			mblk_t *lsoinfo_mp;
5162 
5163 			ASSERT(ill->ill_lso_capab != NULL);
5164 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5165 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5166 				if (mp == NULL) {
5167 					*mpp = lsoinfo_mp;
5168 				} else {
5169 					linkb(mp, lsoinfo_mp);
5170 				}
5171 			}
5172 		} else if (md_dst_ire != NULL) {
5173 			mblk_t *mdinfo_mp;
5174 
5175 			ASSERT(ill->ill_mdt_capab != NULL);
5176 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5177 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5178 				if (mp == NULL) {
5179 					*mpp = mdinfo_mp;
5180 				} else {
5181 					linkb(mp, mdinfo_mp);
5182 				}
5183 			}
5184 		}
5185 	}
5186 bad_addr:
5187 	if (ipsec_policy_set) {
5188 		ASSERT(mp != NULL);
5189 		freeb(mp);
5190 		/*
5191 		 * As of now assume that nothing else accompanies
5192 		 * IPSEC_POLICY_SET.
5193 		 */
5194 		*mpp = NULL;
5195 	}
5196 	if (src_ire != NULL)
5197 		IRE_REFRELE(src_ire);
5198 	if (dst_ire != NULL)
5199 		IRE_REFRELE(dst_ire);
5200 	if (sire != NULL)
5201 		IRE_REFRELE(sire);
5202 	if (md_dst_ire != NULL)
5203 		IRE_REFRELE(md_dst_ire);
5204 	if (lso_dst_ire != NULL)
5205 		IRE_REFRELE(lso_dst_ire);
5206 	if (effective_cred != NULL)
5207 		crfree(effective_cred);
5208 	return (error);
5209 }
5210 
5211 int
5212 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5213     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5214     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5215 {
5216 	int error;
5217 
5218 	ASSERT(!connp->conn_af_isv6);
5219 	connp->conn_pkt_isv6 = B_FALSE;
5220 	connp->conn_ulp = protocol;
5221 
5222 	/* For raw socket, the local port is not set. */
5223 	if (lport == 0)
5224 		lport = connp->conn_lport;
5225 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5226 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5227 	if (error < 0)
5228 		error = -TBADADDR;
5229 	return (error);
5230 }
5231 
5232 /*
5233  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5234  * Prefers dst_ire over src_ire.
5235  */
5236 static boolean_t
5237 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5238 {
5239 	mblk_t	*mp = *mpp;
5240 	ire_t	*ret_ire;
5241 
5242 	ASSERT(mp != NULL);
5243 
5244 	if (ire != NULL) {
5245 		/*
5246 		 * mp initialized above to IRE_DB_REQ_TYPE
5247 		 * appended mblk. Its <upper protocol>'s
5248 		 * job to make sure there is room.
5249 		 */
5250 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5251 			return (B_FALSE);
5252 
5253 		mp->b_datap->db_type = IRE_DB_TYPE;
5254 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5255 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5256 		ret_ire = (ire_t *)mp->b_rptr;
5257 		/*
5258 		 * Pass the latest setting of the ip_path_mtu_discovery and
5259 		 * copy the ulp info if any.
5260 		 */
5261 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5262 		    IPH_DF : 0;
5263 		if (ulp_info != NULL) {
5264 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5265 			    sizeof (iulp_t));
5266 		}
5267 		ret_ire->ire_mp = mp;
5268 	} else {
5269 		/*
5270 		 * No IRE was found. Remove IRE mblk.
5271 		 */
5272 		*mpp = mp->b_cont;
5273 		freeb(mp);
5274 	}
5275 	return (B_TRUE);
5276 }
5277 
5278 /*
5279  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5280  * the final piece where we don't.  Return a pointer to the first mblk in the
5281  * result, and update the pointer to the next mblk to chew on.  If anything
5282  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5283  * NULL pointer.
5284  */
5285 mblk_t *
5286 ip_carve_mp(mblk_t **mpp, ssize_t len)
5287 {
5288 	mblk_t	*mp0;
5289 	mblk_t	*mp1;
5290 	mblk_t	*mp2;
5291 
5292 	if (!len || !mpp || !(mp0 = *mpp))
5293 		return (NULL);
5294 	/* If we aren't going to consume the first mblk, we need a dup. */
5295 	if (mp0->b_wptr - mp0->b_rptr > len) {
5296 		mp1 = dupb(mp0);
5297 		if (mp1) {
5298 			/* Partition the data between the two mblks. */
5299 			mp1->b_wptr = mp1->b_rptr + len;
5300 			mp0->b_rptr = mp1->b_wptr;
5301 			/*
5302 			 * after adjustments if mblk not consumed is now
5303 			 * unaligned, try to align it. If this fails free
5304 			 * all messages and let upper layer recover.
5305 			 */
5306 			if (!OK_32PTR(mp0->b_rptr)) {
5307 				if (!pullupmsg(mp0, -1)) {
5308 					freemsg(mp0);
5309 					freemsg(mp1);
5310 					*mpp = NULL;
5311 					return (NULL);
5312 				}
5313 			}
5314 		}
5315 		return (mp1);
5316 	}
5317 	/* Eat through as many mblks as we need to get len bytes. */
5318 	len -= mp0->b_wptr - mp0->b_rptr;
5319 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5320 		if (mp2->b_wptr - mp2->b_rptr > len) {
5321 			/*
5322 			 * We won't consume the entire last mblk.  Like
5323 			 * above, dup and partition it.
5324 			 */
5325 			mp1->b_cont = dupb(mp2);
5326 			mp1 = mp1->b_cont;
5327 			if (!mp1) {
5328 				/*
5329 				 * Trouble.  Rather than go to a lot of
5330 				 * trouble to clean up, we free the messages.
5331 				 * This won't be any worse than losing it on
5332 				 * the wire.
5333 				 */
5334 				freemsg(mp0);
5335 				freemsg(mp2);
5336 				*mpp = NULL;
5337 				return (NULL);
5338 			}
5339 			mp1->b_wptr = mp1->b_rptr + len;
5340 			mp2->b_rptr = mp1->b_wptr;
5341 			/*
5342 			 * after adjustments if mblk not consumed is now
5343 			 * unaligned, try to align it. If this fails free
5344 			 * all messages and let upper layer recover.
5345 			 */
5346 			if (!OK_32PTR(mp2->b_rptr)) {
5347 				if (!pullupmsg(mp2, -1)) {
5348 					freemsg(mp0);
5349 					freemsg(mp2);
5350 					*mpp = NULL;
5351 					return (NULL);
5352 				}
5353 			}
5354 			*mpp = mp2;
5355 			return (mp0);
5356 		}
5357 		/* Decrement len by the amount we just got. */
5358 		len -= mp2->b_wptr - mp2->b_rptr;
5359 	}
5360 	/*
5361 	 * len should be reduced to zero now.  If not our caller has
5362 	 * screwed up.
5363 	 */
5364 	if (len) {
5365 		/* Shouldn't happen! */
5366 		freemsg(mp0);
5367 		*mpp = NULL;
5368 		return (NULL);
5369 	}
5370 	/*
5371 	 * We consumed up to exactly the end of an mblk.  Detach the part
5372 	 * we are returning from the rest of the chain.
5373 	 */
5374 	mp1->b_cont = NULL;
5375 	*mpp = mp2;
5376 	return (mp0);
5377 }
5378 
5379 /* The ill stream is being unplumbed. Called from ip_close */
5380 int
5381 ip_modclose(ill_t *ill)
5382 {
5383 	boolean_t success;
5384 	ipsq_t	*ipsq;
5385 	ipif_t	*ipif;
5386 	queue_t	*q = ill->ill_rq;
5387 	ip_stack_t	*ipst = ill->ill_ipst;
5388 	int	i;
5389 
5390 	/*
5391 	 * The punlink prior to this may have initiated a capability
5392 	 * negotiation. But ipsq_enter will block until that finishes or
5393 	 * times out.
5394 	 */
5395 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5396 
5397 	/*
5398 	 * Open/close/push/pop is guaranteed to be single threaded
5399 	 * per stream by STREAMS. FS guarantees that all references
5400 	 * from top are gone before close is called. So there can't
5401 	 * be another close thread that has set CONDEMNED on this ill.
5402 	 * and cause ipsq_enter to return failure.
5403 	 */
5404 	ASSERT(success);
5405 	ipsq = ill->ill_phyint->phyint_ipsq;
5406 
5407 	/*
5408 	 * Mark it condemned. No new reference will be made to this ill.
5409 	 * Lookup functions will return an error. Threads that try to
5410 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5411 	 * that the refcnt will drop down to zero.
5412 	 */
5413 	mutex_enter(&ill->ill_lock);
5414 	ill->ill_state_flags |= ILL_CONDEMNED;
5415 	for (ipif = ill->ill_ipif; ipif != NULL;
5416 	    ipif = ipif->ipif_next) {
5417 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5418 	}
5419 	/*
5420 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5421 	 * returns  error if ILL_CONDEMNED is set
5422 	 */
5423 	cv_broadcast(&ill->ill_cv);
5424 	mutex_exit(&ill->ill_lock);
5425 
5426 	/*
5427 	 * Send all the deferred DLPI messages downstream which came in
5428 	 * during the small window right before ipsq_enter(). We do this
5429 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5430 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5431 	 */
5432 	ill_dlpi_send_deferred(ill);
5433 
5434 	/*
5435 	 * Shut down fragmentation reassembly.
5436 	 * ill_frag_timer won't start a timer again.
5437 	 * Now cancel any existing timer
5438 	 */
5439 	(void) untimeout(ill->ill_frag_timer_id);
5440 	(void) ill_frag_timeout(ill, 0);
5441 
5442 	/*
5443 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5444 	 * this ill. Then wait for the refcnts to drop to zero.
5445 	 * ill_is_freeable checks whether the ill is really quiescent.
5446 	 * Then make sure that threads that are waiting to enter the
5447 	 * ipsq have seen the error returned by ipsq_enter and have
5448 	 * gone away. Then we call ill_delete_tail which does the
5449 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5450 	 */
5451 	ill_delete(ill);
5452 	mutex_enter(&ill->ill_lock);
5453 	while (!ill_is_freeable(ill))
5454 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5455 	while (ill->ill_waiters)
5456 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5457 
5458 	mutex_exit(&ill->ill_lock);
5459 
5460 	/*
5461 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5462 	 * it held until the end of the function since the cleanup
5463 	 * below needs to be able to use the ip_stack_t.
5464 	 */
5465 	netstack_hold(ipst->ips_netstack);
5466 
5467 	/* qprocsoff is done via ill_delete_tail */
5468 	ill_delete_tail(ill);
5469 	ASSERT(ill->ill_ipst == NULL);
5470 
5471 	/*
5472 	 * Walk through all upper (conn) streams and qenable
5473 	 * those that have queued data.
5474 	 * close synchronization needs this to
5475 	 * be done to ensure that all upper layers blocked
5476 	 * due to flow control to the closing device
5477 	 * get unblocked.
5478 	 */
5479 	ip1dbg(("ip_wsrv: walking\n"));
5480 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5481 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5482 	}
5483 
5484 	mutex_enter(&ipst->ips_ip_mi_lock);
5485 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5486 	mutex_exit(&ipst->ips_ip_mi_lock);
5487 
5488 	/*
5489 	 * credp could be null if the open didn't succeed and ip_modopen
5490 	 * itself calls ip_close.
5491 	 */
5492 	if (ill->ill_credp != NULL)
5493 		crfree(ill->ill_credp);
5494 
5495 	/*
5496 	 * Now we are done with the module close pieces that
5497 	 * need the netstack_t.
5498 	 */
5499 	netstack_rele(ipst->ips_netstack);
5500 
5501 	mi_close_free((IDP)ill);
5502 	q->q_ptr = WR(q)->q_ptr = NULL;
5503 
5504 	ipsq_exit(ipsq);
5505 
5506 	return (0);
5507 }
5508 
5509 /*
5510  * This is called as part of close() for IP, UDP, ICMP, and RTS
5511  * in order to quiesce the conn.
5512  */
5513 void
5514 ip_quiesce_conn(conn_t *connp)
5515 {
5516 	boolean_t	drain_cleanup_reqd = B_FALSE;
5517 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5518 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5519 	ip_stack_t	*ipst;
5520 
5521 	ASSERT(!IPCL_IS_TCP(connp));
5522 	ipst = connp->conn_netstack->netstack_ip;
5523 
5524 	/*
5525 	 * Mark the conn as closing, and this conn must not be
5526 	 * inserted in future into any list. Eg. conn_drain_insert(),
5527 	 * won't insert this conn into the conn_drain_list.
5528 	 * Similarly ill_pending_mp_add() will not add any mp to
5529 	 * the pending mp list, after this conn has started closing.
5530 	 *
5531 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5532 	 * cannot get set henceforth.
5533 	 */
5534 	mutex_enter(&connp->conn_lock);
5535 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5536 	connp->conn_state_flags |= CONN_CLOSING;
5537 	if (connp->conn_idl != NULL)
5538 		drain_cleanup_reqd = B_TRUE;
5539 	if (connp->conn_oper_pending_ill != NULL)
5540 		conn_ioctl_cleanup_reqd = B_TRUE;
5541 	if (connp->conn_dhcpinit_ill != NULL) {
5542 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5543 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5544 		connp->conn_dhcpinit_ill = NULL;
5545 	}
5546 	if (connp->conn_ilg_inuse != 0)
5547 		ilg_cleanup_reqd = B_TRUE;
5548 	mutex_exit(&connp->conn_lock);
5549 
5550 	if (conn_ioctl_cleanup_reqd)
5551 		conn_ioctl_cleanup(connp);
5552 
5553 	if (is_system_labeled() && connp->conn_anon_port) {
5554 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5555 		    connp->conn_mlp_type, connp->conn_ulp,
5556 		    ntohs(connp->conn_lport), B_FALSE);
5557 		connp->conn_anon_port = 0;
5558 	}
5559 	connp->conn_mlp_type = mlptSingle;
5560 
5561 	/*
5562 	 * Remove this conn from any fanout list it is on.
5563 	 * and then wait for any threads currently operating
5564 	 * on this endpoint to finish
5565 	 */
5566 	ipcl_hash_remove(connp);
5567 
5568 	/*
5569 	 * Remove this conn from the drain list, and do
5570 	 * any other cleanup that may be required.
5571 	 * (Only non-tcp streams may have a non-null conn_idl.
5572 	 * TCP streams are never flow controlled, and
5573 	 * conn_idl will be null)
5574 	 */
5575 	if (drain_cleanup_reqd)
5576 		conn_drain_tail(connp, B_TRUE);
5577 
5578 	if (connp == ipst->ips_ip_g_mrouter)
5579 		(void) ip_mrouter_done(NULL, ipst);
5580 
5581 	if (ilg_cleanup_reqd)
5582 		ilg_delete_all(connp);
5583 
5584 	conn_delete_ire(connp, NULL);
5585 
5586 	/*
5587 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5588 	 * callers from write side can't be there now because close
5589 	 * is in progress. The only other caller is ipcl_walk
5590 	 * which checks for the condemned flag.
5591 	 */
5592 	mutex_enter(&connp->conn_lock);
5593 	connp->conn_state_flags |= CONN_CONDEMNED;
5594 	while (connp->conn_ref != 1)
5595 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5596 	connp->conn_state_flags |= CONN_QUIESCED;
5597 	mutex_exit(&connp->conn_lock);
5598 }
5599 
5600 /* ARGSUSED */
5601 int
5602 ip_close(queue_t *q, int flags)
5603 {
5604 	conn_t		*connp;
5605 
5606 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5607 
5608 	/*
5609 	 * Call the appropriate delete routine depending on whether this is
5610 	 * a module or device.
5611 	 */
5612 	if (WR(q)->q_next != NULL) {
5613 		/* This is a module close */
5614 		return (ip_modclose((ill_t *)q->q_ptr));
5615 	}
5616 
5617 	connp = q->q_ptr;
5618 	ip_quiesce_conn(connp);
5619 
5620 	qprocsoff(q);
5621 
5622 	/*
5623 	 * Now we are truly single threaded on this stream, and can
5624 	 * delete the things hanging off the connp, and finally the connp.
5625 	 * We removed this connp from the fanout list, it cannot be
5626 	 * accessed thru the fanouts, and we already waited for the
5627 	 * conn_ref to drop to 0. We are already in close, so
5628 	 * there cannot be any other thread from the top. qprocsoff
5629 	 * has completed, and service has completed or won't run in
5630 	 * future.
5631 	 */
5632 	ASSERT(connp->conn_ref == 1);
5633 
5634 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5635 
5636 	connp->conn_ref--;
5637 	ipcl_conn_destroy(connp);
5638 
5639 	q->q_ptr = WR(q)->q_ptr = NULL;
5640 	return (0);
5641 }
5642 
5643 /*
5644  * Wapper around putnext() so that ip_rts_request can merely use
5645  * conn_recv.
5646  */
5647 /*ARGSUSED2*/
5648 static void
5649 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5650 {
5651 	conn_t *connp = (conn_t *)arg1;
5652 
5653 	putnext(connp->conn_rq, mp);
5654 }
5655 
5656 /*
5657  * Called when the module is about to be unloaded
5658  */
5659 void
5660 ip_ddi_destroy(void)
5661 {
5662 	tnet_fini();
5663 
5664 	icmp_ddi_g_destroy();
5665 	rts_ddi_g_destroy();
5666 	udp_ddi_g_destroy();
5667 	sctp_ddi_g_destroy();
5668 	tcp_ddi_g_destroy();
5669 	ilb_ddi_g_destroy();
5670 	ipsec_policy_g_destroy();
5671 	ipcl_g_destroy();
5672 	ip_net_g_destroy();
5673 	ip_ire_g_fini();
5674 	inet_minor_destroy(ip_minor_arena_sa);
5675 #if defined(_LP64)
5676 	inet_minor_destroy(ip_minor_arena_la);
5677 #endif
5678 
5679 #ifdef DEBUG
5680 	list_destroy(&ip_thread_list);
5681 	rw_destroy(&ip_thread_rwlock);
5682 	tsd_destroy(&ip_thread_data);
5683 #endif
5684 
5685 	netstack_unregister(NS_IP);
5686 }
5687 
5688 /*
5689  * First step in cleanup.
5690  */
5691 /* ARGSUSED */
5692 static void
5693 ip_stack_shutdown(netstackid_t stackid, void *arg)
5694 {
5695 	ip_stack_t *ipst = (ip_stack_t *)arg;
5696 
5697 #ifdef NS_DEBUG
5698 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5699 #endif
5700 
5701 	/*
5702 	 * Perform cleanup for special interfaces (loopback and IPMP).
5703 	 */
5704 	ip_interface_cleanup(ipst);
5705 
5706 	/*
5707 	 * The *_hook_shutdown()s start the process of notifying any
5708 	 * consumers that things are going away.... nothing is destroyed.
5709 	 */
5710 	ipv4_hook_shutdown(ipst);
5711 	ipv6_hook_shutdown(ipst);
5712 
5713 	mutex_enter(&ipst->ips_capab_taskq_lock);
5714 	ipst->ips_capab_taskq_quit = B_TRUE;
5715 	cv_signal(&ipst->ips_capab_taskq_cv);
5716 	mutex_exit(&ipst->ips_capab_taskq_lock);
5717 
5718 	mutex_enter(&ipst->ips_mrt_lock);
5719 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5720 	cv_signal(&ipst->ips_mrt_cv);
5721 	mutex_exit(&ipst->ips_mrt_lock);
5722 }
5723 
5724 /*
5725  * Free the IP stack instance.
5726  */
5727 static void
5728 ip_stack_fini(netstackid_t stackid, void *arg)
5729 {
5730 	ip_stack_t *ipst = (ip_stack_t *)arg;
5731 	int ret;
5732 
5733 #ifdef NS_DEBUG
5734 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5735 #endif
5736 	/*
5737 	 * At this point, all of the notifications that the events and
5738 	 * protocols are going away have been run, meaning that we can
5739 	 * now set about starting to clean things up.
5740 	 */
5741 	ipobs_fini(ipst);
5742 	ipv4_hook_destroy(ipst);
5743 	ipv6_hook_destroy(ipst);
5744 	ip_net_destroy(ipst);
5745 
5746 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5747 	cv_destroy(&ipst->ips_capab_taskq_cv);
5748 
5749 	mutex_enter(&ipst->ips_mrt_lock);
5750 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5751 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5752 	mutex_destroy(&ipst->ips_mrt_lock);
5753 	cv_destroy(&ipst->ips_mrt_cv);
5754 	cv_destroy(&ipst->ips_mrt_done_cv);
5755 
5756 	ipmp_destroy(ipst);
5757 	rw_destroy(&ipst->ips_srcid_lock);
5758 
5759 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5760 	ipst->ips_ip_mibkp = NULL;
5761 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5762 	ipst->ips_icmp_mibkp = NULL;
5763 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5764 	ipst->ips_ip_kstat = NULL;
5765 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5766 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5767 	ipst->ips_ip6_kstat = NULL;
5768 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5769 
5770 	nd_free(&ipst->ips_ip_g_nd);
5771 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5772 	ipst->ips_param_arr = NULL;
5773 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5774 	ipst->ips_ndp_arr = NULL;
5775 
5776 	ip_mrouter_stack_destroy(ipst);
5777 
5778 	mutex_destroy(&ipst->ips_ip_mi_lock);
5779 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5780 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5781 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5782 
5783 	ret = untimeout(ipst->ips_igmp_timeout_id);
5784 	if (ret == -1) {
5785 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5786 	} else {
5787 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5788 		ipst->ips_igmp_timeout_id = 0;
5789 	}
5790 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5791 	if (ret == -1) {
5792 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5793 	} else {
5794 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5795 		ipst->ips_igmp_slowtimeout_id = 0;
5796 	}
5797 	ret = untimeout(ipst->ips_mld_timeout_id);
5798 	if (ret == -1) {
5799 		ASSERT(ipst->ips_mld_timeout_id == 0);
5800 	} else {
5801 		ASSERT(ipst->ips_mld_timeout_id != 0);
5802 		ipst->ips_mld_timeout_id = 0;
5803 	}
5804 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5805 	if (ret == -1) {
5806 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5807 	} else {
5808 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5809 		ipst->ips_mld_slowtimeout_id = 0;
5810 	}
5811 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5812 	if (ret == -1) {
5813 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5814 	} else {
5815 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5816 		ipst->ips_ip_ire_expire_id = 0;
5817 	}
5818 
5819 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5820 	mutex_destroy(&ipst->ips_mld_timer_lock);
5821 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5822 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5823 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5824 	rw_destroy(&ipst->ips_ill_g_lock);
5825 
5826 	ip_ire_fini(ipst);
5827 	ip6_asp_free(ipst);
5828 	conn_drain_fini(ipst);
5829 	ipcl_destroy(ipst);
5830 
5831 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5832 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5833 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5834 	ipst->ips_ndp4 = NULL;
5835 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5836 	ipst->ips_ndp6 = NULL;
5837 
5838 	if (ipst->ips_loopback_ksp != NULL) {
5839 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5840 		ipst->ips_loopback_ksp = NULL;
5841 	}
5842 
5843 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5844 	ipst->ips_phyint_g_list = NULL;
5845 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5846 	ipst->ips_ill_g_heads = NULL;
5847 
5848 	ldi_ident_release(ipst->ips_ldi_ident);
5849 	kmem_free(ipst, sizeof (*ipst));
5850 }
5851 
5852 /*
5853  * This function is called from the TSD destructor, and is used to debug
5854  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5855  * details.
5856  */
5857 static void
5858 ip_thread_exit(void *phash)
5859 {
5860 	th_hash_t *thh = phash;
5861 
5862 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5863 	list_remove(&ip_thread_list, thh);
5864 	rw_exit(&ip_thread_rwlock);
5865 	mod_hash_destroy_hash(thh->thh_hash);
5866 	kmem_free(thh, sizeof (*thh));
5867 }
5868 
5869 /*
5870  * Called when the IP kernel module is loaded into the kernel
5871  */
5872 void
5873 ip_ddi_init(void)
5874 {
5875 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5876 
5877 	/*
5878 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5879 	 * initial devices: ip, ip6, tcp, tcp6.
5880 	 */
5881 	/*
5882 	 * If this is a 64-bit kernel, then create two separate arenas -
5883 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5884 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5885 	 */
5886 	ip_minor_arena_la = NULL;
5887 	ip_minor_arena_sa = NULL;
5888 #if defined(_LP64)
5889 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5890 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5891 		cmn_err(CE_PANIC,
5892 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5893 	}
5894 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5895 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5896 		cmn_err(CE_PANIC,
5897 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5898 	}
5899 #else
5900 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5901 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5902 		cmn_err(CE_PANIC,
5903 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5904 	}
5905 #endif
5906 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5907 
5908 	ipcl_g_init();
5909 	ip_ire_g_init();
5910 	ip_net_g_init();
5911 
5912 #ifdef DEBUG
5913 	tsd_create(&ip_thread_data, ip_thread_exit);
5914 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5915 	list_create(&ip_thread_list, sizeof (th_hash_t),
5916 	    offsetof(th_hash_t, thh_link));
5917 #endif
5918 
5919 	/*
5920 	 * We want to be informed each time a stack is created or
5921 	 * destroyed in the kernel, so we can maintain the
5922 	 * set of udp_stack_t's.
5923 	 */
5924 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5925 	    ip_stack_fini);
5926 
5927 	ipsec_policy_g_init();
5928 	tcp_ddi_g_init();
5929 	sctp_ddi_g_init();
5930 
5931 	tnet_init();
5932 
5933 	udp_ddi_g_init();
5934 	rts_ddi_g_init();
5935 	icmp_ddi_g_init();
5936 	ilb_ddi_g_init();
5937 }
5938 
5939 /*
5940  * Initialize the IP stack instance.
5941  */
5942 static void *
5943 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5944 {
5945 	ip_stack_t	*ipst;
5946 	ipparam_t	*pa;
5947 	ipndp_t		*na;
5948 	major_t		major;
5949 
5950 #ifdef NS_DEBUG
5951 	printf("ip_stack_init(stack %d)\n", stackid);
5952 #endif
5953 
5954 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5955 	ipst->ips_netstack = ns;
5956 
5957 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5958 	    KM_SLEEP);
5959 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5960 	    KM_SLEEP);
5961 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5962 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5963 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5964 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5965 
5966 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5967 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5968 	ipst->ips_igmp_deferred_next = INFINITY;
5969 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5970 	ipst->ips_mld_deferred_next = INFINITY;
5971 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5972 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5973 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5974 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5975 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5976 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5977 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5978 
5979 	ipcl_init(ipst);
5980 	ip_ire_init(ipst);
5981 	ip6_asp_init(ipst);
5982 	ipif_init(ipst);
5983 	conn_drain_init(ipst);
5984 	ip_mrouter_stack_init(ipst);
5985 
5986 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5987 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5988 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
5989 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
5990 
5991 	ipst->ips_ip_multirt_log_interval = 1000;
5992 
5993 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5994 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5995 	ipst->ips_ill_index = 1;
5996 
5997 	ipst->ips_saved_ip_g_forward = -1;
5998 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5999 
6000 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6001 	ipst->ips_param_arr = pa;
6002 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6003 
6004 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6005 	ipst->ips_ndp_arr = na;
6006 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6007 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6008 	    (caddr_t)&ipst->ips_ip_g_forward;
6009 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6010 	    (caddr_t)&ipst->ips_ipv6_forward;
6011 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6012 	    "ip_cgtp_filter") == 0);
6013 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6014 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6015 
6016 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6017 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6018 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6019 
6020 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6021 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6022 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6023 	ipst->ips_ip6_kstat =
6024 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6025 
6026 	ipst->ips_ip_src_id = 1;
6027 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6028 
6029 	ip_net_init(ipst, ns);
6030 	ipv4_hook_init(ipst);
6031 	ipv6_hook_init(ipst);
6032 	ipmp_init(ipst);
6033 	ipobs_init(ipst);
6034 
6035 	/*
6036 	 * Create the taskq dispatcher thread and initialize related stuff.
6037 	 */
6038 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6039 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6040 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6041 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6042 
6043 	/*
6044 	 * Create the mcast_restart_timers_thread() worker thread.
6045 	 */
6046 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6047 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6048 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6049 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6050 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6051 
6052 	major = mod_name_to_major(INET_NAME);
6053 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6054 	return (ipst);
6055 }
6056 
6057 /*
6058  * Allocate and initialize a DLPI template of the specified length.  (May be
6059  * called as writer.)
6060  */
6061 mblk_t *
6062 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6063 {
6064 	mblk_t	*mp;
6065 
6066 	mp = allocb(len, BPRI_MED);
6067 	if (!mp)
6068 		return (NULL);
6069 
6070 	/*
6071 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6072 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6073 	 * that other DLPI are M_PROTO.
6074 	 */
6075 	if (prim == DL_INFO_REQ) {
6076 		mp->b_datap->db_type = M_PCPROTO;
6077 	} else {
6078 		mp->b_datap->db_type = M_PROTO;
6079 	}
6080 
6081 	mp->b_wptr = mp->b_rptr + len;
6082 	bzero(mp->b_rptr, len);
6083 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6084 	return (mp);
6085 }
6086 
6087 /*
6088  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6089  */
6090 mblk_t *
6091 ip_dlnotify_alloc(uint_t notification, uint_t data)
6092 {
6093 	dl_notify_ind_t	*notifyp;
6094 	mblk_t		*mp;
6095 
6096 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6097 		return (NULL);
6098 
6099 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6100 	notifyp->dl_notification = notification;
6101 	notifyp->dl_data = data;
6102 	return (mp);
6103 }
6104 
6105 /*
6106  * Debug formatting routine.  Returns a character string representation of the
6107  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6108  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6109  *
6110  * Once the ndd table-printing interfaces are removed, this can be changed to
6111  * standard dotted-decimal form.
6112  */
6113 char *
6114 ip_dot_addr(ipaddr_t addr, char *buf)
6115 {
6116 	uint8_t *ap = (uint8_t *)&addr;
6117 
6118 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6119 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6120 	return (buf);
6121 }
6122 
6123 /*
6124  * Write the given MAC address as a printable string in the usual colon-
6125  * separated format.
6126  */
6127 const char *
6128 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6129 {
6130 	char *bp;
6131 
6132 	if (alen == 0 || buflen < 4)
6133 		return ("?");
6134 	bp = buf;
6135 	for (;;) {
6136 		/*
6137 		 * If there are more MAC address bytes available, but we won't
6138 		 * have any room to print them, then add "..." to the string
6139 		 * instead.  See below for the 'magic number' explanation.
6140 		 */
6141 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6142 			(void) strcpy(bp, "...");
6143 			break;
6144 		}
6145 		(void) sprintf(bp, "%02x", *addr++);
6146 		bp += 2;
6147 		if (--alen == 0)
6148 			break;
6149 		*bp++ = ':';
6150 		buflen -= 3;
6151 		/*
6152 		 * At this point, based on the first 'if' statement above,
6153 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6154 		 * buflen >= 4.  The first case leaves room for the final "xx"
6155 		 * number and trailing NUL byte.  The second leaves room for at
6156 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6157 		 * that statement.
6158 		 */
6159 	}
6160 	return (buf);
6161 }
6162 
6163 /*
6164  * Send an ICMP error after patching up the packet appropriately.  Returns
6165  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6166  */
6167 static boolean_t
6168 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6169     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6170     zoneid_t zoneid, ip_stack_t *ipst)
6171 {
6172 	ipha_t *ipha;
6173 	mblk_t *first_mp;
6174 	boolean_t secure;
6175 	unsigned char db_type;
6176 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6177 
6178 	first_mp = mp;
6179 	if (mctl_present) {
6180 		mp = mp->b_cont;
6181 		secure = ipsec_in_is_secure(first_mp);
6182 		ASSERT(mp != NULL);
6183 	} else {
6184 		/*
6185 		 * If this is an ICMP error being reported - which goes
6186 		 * up as M_CTLs, we need to convert them to M_DATA till
6187 		 * we finish checking with global policy because
6188 		 * ipsec_check_global_policy() assumes M_DATA as clear
6189 		 * and M_CTL as secure.
6190 		 */
6191 		db_type = DB_TYPE(mp);
6192 		DB_TYPE(mp) = M_DATA;
6193 		secure = B_FALSE;
6194 	}
6195 	/*
6196 	 * We are generating an icmp error for some inbound packet.
6197 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6198 	 * Before we generate an error, check with global policy
6199 	 * to see whether this is allowed to enter the system. As
6200 	 * there is no "conn", we are checking with global policy.
6201 	 */
6202 	ipha = (ipha_t *)mp->b_rptr;
6203 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6204 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6205 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6206 		if (first_mp == NULL)
6207 			return (B_FALSE);
6208 	}
6209 
6210 	if (!mctl_present)
6211 		DB_TYPE(mp) = db_type;
6212 
6213 	if (flags & IP_FF_SEND_ICMP) {
6214 		if (flags & IP_FF_HDR_COMPLETE) {
6215 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6216 				freemsg(first_mp);
6217 				return (B_TRUE);
6218 			}
6219 		}
6220 		if (flags & IP_FF_CKSUM) {
6221 			/*
6222 			 * Have to correct checksum since
6223 			 * the packet might have been
6224 			 * fragmented and the reassembly code in ip_rput
6225 			 * does not restore the IP checksum.
6226 			 */
6227 			ipha->ipha_hdr_checksum = 0;
6228 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6229 		}
6230 		switch (icmp_type) {
6231 		case ICMP_DEST_UNREACHABLE:
6232 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6233 			    ipst);
6234 			break;
6235 		default:
6236 			freemsg(first_mp);
6237 			break;
6238 		}
6239 	} else {
6240 		freemsg(first_mp);
6241 		return (B_FALSE);
6242 	}
6243 
6244 	return (B_TRUE);
6245 }
6246 
6247 /*
6248  * Used to send an ICMP error message when a packet is received for
6249  * a protocol that is not supported. The mblk passed as argument
6250  * is consumed by this function.
6251  */
6252 void
6253 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6254     ip_stack_t *ipst)
6255 {
6256 	mblk_t *mp;
6257 	ipha_t *ipha;
6258 	ill_t *ill;
6259 	ipsec_in_t *ii;
6260 
6261 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6262 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6263 
6264 	mp = ipsec_mp->b_cont;
6265 	ipsec_mp->b_cont = NULL;
6266 	ipha = (ipha_t *)mp->b_rptr;
6267 	/* Get ill from index in ipsec_in_t. */
6268 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6269 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6270 	    ipst);
6271 	if (ill != NULL) {
6272 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6273 			if (ip_fanout_send_icmp(q, mp, flags,
6274 			    ICMP_DEST_UNREACHABLE,
6275 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6276 				BUMP_MIB(ill->ill_ip_mib,
6277 				    ipIfStatsInUnknownProtos);
6278 			}
6279 		} else {
6280 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6281 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6282 			    0, B_FALSE, zoneid, ipst)) {
6283 				BUMP_MIB(ill->ill_ip_mib,
6284 				    ipIfStatsInUnknownProtos);
6285 			}
6286 		}
6287 		ill_refrele(ill);
6288 	} else { /* re-link for the freemsg() below. */
6289 		ipsec_mp->b_cont = mp;
6290 	}
6291 
6292 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6293 	freemsg(ipsec_mp);
6294 }
6295 
6296 /*
6297  * See if the inbound datagram has had IPsec processing applied to it.
6298  */
6299 boolean_t
6300 ipsec_in_is_secure(mblk_t *ipsec_mp)
6301 {
6302 	ipsec_in_t *ii;
6303 
6304 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6305 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6306 
6307 	if (ii->ipsec_in_loopback) {
6308 		return (ii->ipsec_in_secure);
6309 	} else {
6310 		return (ii->ipsec_in_ah_sa != NULL ||
6311 		    ii->ipsec_in_esp_sa != NULL ||
6312 		    ii->ipsec_in_decaps);
6313 	}
6314 }
6315 
6316 /*
6317  * Handle protocols with which IP is less intimate.  There
6318  * can be more than one stream bound to a particular
6319  * protocol.  When this is the case, normally each one gets a copy
6320  * of any incoming packets.
6321  *
6322  * IPsec NOTE :
6323  *
6324  * Don't allow a secure packet going up a non-secure connection.
6325  * We don't allow this because
6326  *
6327  * 1) Reply might go out in clear which will be dropped at
6328  *    the sending side.
6329  * 2) If the reply goes out in clear it will give the
6330  *    adversary enough information for getting the key in
6331  *    most of the cases.
6332  *
6333  * Moreover getting a secure packet when we expect clear
6334  * implies that SA's were added without checking for
6335  * policy on both ends. This should not happen once ISAKMP
6336  * is used to negotiate SAs as SAs will be added only after
6337  * verifying the policy.
6338  *
6339  * IPQoS Notes:
6340  * Once we have determined the client, invoke IPPF processing.
6341  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6342  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6343  * ip_policy will be false.
6344  *
6345  * Zones notes:
6346  * Currently only applications in the global zone can create raw sockets for
6347  * protocols other than ICMP. So unlike the broadcast / multicast case of
6348  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6349  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6350  */
6351 static void
6352 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6353     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6354     zoneid_t zoneid)
6355 {
6356 	queue_t	*rq;
6357 	mblk_t	*mp1, *first_mp1;
6358 	uint_t	protocol = ipha->ipha_protocol;
6359 	ipaddr_t dst;
6360 	mblk_t *first_mp = mp;
6361 	boolean_t secure;
6362 	uint32_t ill_index;
6363 	conn_t	*connp, *first_connp, *next_connp;
6364 	connf_t	*connfp;
6365 	boolean_t shared_addr;
6366 	mib2_ipIfStatsEntry_t *mibptr;
6367 	ip_stack_t *ipst = recv_ill->ill_ipst;
6368 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6369 
6370 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6371 	if (mctl_present) {
6372 		mp = first_mp->b_cont;
6373 		secure = ipsec_in_is_secure(first_mp);
6374 		ASSERT(mp != NULL);
6375 	} else {
6376 		secure = B_FALSE;
6377 	}
6378 	dst = ipha->ipha_dst;
6379 	shared_addr = (zoneid == ALL_ZONES);
6380 	if (shared_addr) {
6381 		/*
6382 		 * We don't allow multilevel ports for raw IP, so no need to
6383 		 * check for that here.
6384 		 */
6385 		zoneid = tsol_packet_to_zoneid(mp);
6386 	}
6387 
6388 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6389 	mutex_enter(&connfp->connf_lock);
6390 	connp = connfp->connf_head;
6391 	for (connp = connfp->connf_head; connp != NULL;
6392 	    connp = connp->conn_next) {
6393 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6394 		    zoneid) &&
6395 		    (!is_system_labeled() ||
6396 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6397 		    connp))) {
6398 			break;
6399 		}
6400 	}
6401 
6402 	if (connp == NULL) {
6403 		/*
6404 		 * No one bound to these addresses.  Is
6405 		 * there a client that wants all
6406 		 * unclaimed datagrams?
6407 		 */
6408 		mutex_exit(&connfp->connf_lock);
6409 		/*
6410 		 * Check for IPPROTO_ENCAP...
6411 		 */
6412 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6413 			/*
6414 			 * If an IPsec mblk is here on a multicast
6415 			 * tunnel (using ip_mroute stuff), check policy here,
6416 			 * THEN ship off to ip_mroute_decap().
6417 			 *
6418 			 * BTW,  If I match a configured IP-in-IP
6419 			 * tunnel, this path will not be reached, and
6420 			 * ip_mroute_decap will never be called.
6421 			 */
6422 			first_mp = ipsec_check_global_policy(first_mp, connp,
6423 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6424 			if (first_mp != NULL) {
6425 				if (mctl_present)
6426 					freeb(first_mp);
6427 				ip_mroute_decap(q, mp, ill);
6428 			} /* Else we already freed everything! */
6429 		} else {
6430 			/*
6431 			 * Otherwise send an ICMP protocol unreachable.
6432 			 */
6433 			if (ip_fanout_send_icmp(q, first_mp, flags,
6434 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6435 			    mctl_present, zoneid, ipst)) {
6436 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6437 			}
6438 		}
6439 		return;
6440 	}
6441 
6442 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6443 
6444 	CONN_INC_REF(connp);
6445 	first_connp = connp;
6446 	connp = connp->conn_next;
6447 
6448 	for (;;) {
6449 		while (connp != NULL) {
6450 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6451 			    flags, zoneid) &&
6452 			    (!is_system_labeled() ||
6453 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6454 			    shared_addr, connp)))
6455 				break;
6456 			connp = connp->conn_next;
6457 		}
6458 
6459 		/*
6460 		 * Copy the packet.
6461 		 */
6462 		if (connp == NULL ||
6463 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6464 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6465 			/*
6466 			 * No more interested clients or memory
6467 			 * allocation failed
6468 			 */
6469 			connp = first_connp;
6470 			break;
6471 		}
6472 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6473 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6474 		CONN_INC_REF(connp);
6475 		mutex_exit(&connfp->connf_lock);
6476 		rq = connp->conn_rq;
6477 
6478 		/*
6479 		 * Check flow control
6480 		 */
6481 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6482 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6483 			if (flags & IP_FF_RAWIP) {
6484 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6485 			} else {
6486 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6487 			}
6488 
6489 			freemsg(first_mp1);
6490 		} else {
6491 			/*
6492 			 * Enforce policy like any other conn_t.  Note that
6493 			 * IP-in-IP packets don't come through here, but
6494 			 * through ip_iptun_input() or
6495 			 * icmp_inbound_iptun_fanout().  IPsec policy for such
6496 			 * packets is enforced in the iptun module.
6497 			 */
6498 			if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6499 			    secure) {
6500 				first_mp1 = ipsec_check_inbound_policy
6501 				    (first_mp1, connp, ipha, NULL,
6502 				    mctl_present);
6503 			}
6504 			if (first_mp1 != NULL) {
6505 				int in_flags = 0;
6506 				/*
6507 				 * ip_fanout_proto also gets called from
6508 				 * icmp_inbound_error_fanout, in which case
6509 				 * the msg type is M_CTL.  Don't add info
6510 				 * in this case for the time being. In future
6511 				 * when there is a need for knowing the
6512 				 * inbound iface index for ICMP error msgs,
6513 				 * then this can be changed.
6514 				 */
6515 				if (connp->conn_recvif)
6516 					in_flags = IPF_RECVIF;
6517 				/*
6518 				 * The ULP may support IP_RECVPKTINFO for both
6519 				 * IP v4 and v6 so pass the appropriate argument
6520 				 * based on conn IP version.
6521 				 */
6522 				if (connp->conn_ip_recvpktinfo) {
6523 					if (connp->conn_af_isv6) {
6524 						/*
6525 						 * V6 only needs index
6526 						 */
6527 						in_flags |= IPF_RECVIF;
6528 					} else {
6529 						/*
6530 						 * V4 needs index +
6531 						 * matching address.
6532 						 */
6533 						in_flags |= IPF_RECVADDR;
6534 					}
6535 				}
6536 				if ((in_flags != 0) &&
6537 				    (mp->b_datap->db_type != M_CTL)) {
6538 					/*
6539 					 * the actual data will be
6540 					 * contained in b_cont upon
6541 					 * successful return of the
6542 					 * following call else
6543 					 * original mblk is returned
6544 					 */
6545 					ASSERT(recv_ill != NULL);
6546 					mp1 = ip_add_info(mp1, recv_ill,
6547 					    in_flags, IPCL_ZONEID(connp), ipst);
6548 				}
6549 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6550 				if (mctl_present)
6551 					freeb(first_mp1);
6552 				(connp->conn_recv)(connp, mp1, NULL);
6553 			}
6554 		}
6555 		mutex_enter(&connfp->connf_lock);
6556 		/* Follow the next pointer before releasing the conn. */
6557 		next_connp = connp->conn_next;
6558 		CONN_DEC_REF(connp);
6559 		connp = next_connp;
6560 	}
6561 
6562 	/* Last one.  Send it upstream. */
6563 	mutex_exit(&connfp->connf_lock);
6564 
6565 	/*
6566 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6567 	 * will be set to false.
6568 	 */
6569 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6570 		ill_index = ill->ill_phyint->phyint_ifindex;
6571 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6572 		if (mp == NULL) {
6573 			CONN_DEC_REF(connp);
6574 			if (mctl_present) {
6575 				freeb(first_mp);
6576 			}
6577 			return;
6578 		}
6579 	}
6580 
6581 	rq = connp->conn_rq;
6582 	/*
6583 	 * Check flow control
6584 	 */
6585 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6586 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6587 		if (flags & IP_FF_RAWIP) {
6588 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6589 		} else {
6590 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6591 		}
6592 
6593 		freemsg(first_mp);
6594 	} else {
6595 		ASSERT(!IPCL_IS_IPTUN(connp));
6596 
6597 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6598 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6599 			    ipha, NULL, mctl_present);
6600 		}
6601 
6602 		if (first_mp != NULL) {
6603 			int in_flags = 0;
6604 
6605 			/*
6606 			 * ip_fanout_proto also gets called
6607 			 * from icmp_inbound_error_fanout, in
6608 			 * which case the msg type is M_CTL.
6609 			 * Don't add info in this case for time
6610 			 * being. In future when there is a
6611 			 * need for knowing the inbound iface
6612 			 * index for ICMP error msgs, then this
6613 			 * can be changed
6614 			 */
6615 			if (connp->conn_recvif)
6616 				in_flags = IPF_RECVIF;
6617 			if (connp->conn_ip_recvpktinfo) {
6618 				if (connp->conn_af_isv6) {
6619 					/*
6620 					 * V6 only needs index
6621 					 */
6622 					in_flags |= IPF_RECVIF;
6623 				} else {
6624 					/*
6625 					 * V4 needs index +
6626 					 * matching address.
6627 					 */
6628 					in_flags |= IPF_RECVADDR;
6629 				}
6630 			}
6631 			if ((in_flags != 0) &&
6632 			    (mp->b_datap->db_type != M_CTL)) {
6633 
6634 				/*
6635 				 * the actual data will be contained in
6636 				 * b_cont upon successful return
6637 				 * of the following call else original
6638 				 * mblk is returned
6639 				 */
6640 				ASSERT(recv_ill != NULL);
6641 				mp = ip_add_info(mp, recv_ill,
6642 				    in_flags, IPCL_ZONEID(connp), ipst);
6643 			}
6644 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6645 			(connp->conn_recv)(connp, mp, NULL);
6646 			if (mctl_present)
6647 				freeb(first_mp);
6648 		}
6649 	}
6650 	CONN_DEC_REF(connp);
6651 }
6652 
6653 /*
6654  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6655  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6656  * the correct squeue, in this case the same squeue as a valid listener with
6657  * no current connection state for the packet we are processing. The function
6658  * is called for synchronizing both IPv4 and IPv6.
6659  */
6660 void
6661 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6662     tcp_stack_t *tcps, conn_t *connp)
6663 {
6664 	mblk_t *rst_mp;
6665 	tcp_xmit_reset_event_t *eventp;
6666 
6667 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6668 
6669 	if (rst_mp == NULL) {
6670 		freemsg(mp);
6671 		return;
6672 	}
6673 
6674 	rst_mp->b_datap->db_type = M_PROTO;
6675 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6676 
6677 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6678 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6679 	eventp->tcp_xre_iphdrlen = hdrlen;
6680 	eventp->tcp_xre_zoneid = zoneid;
6681 	eventp->tcp_xre_tcps = tcps;
6682 
6683 	rst_mp->b_cont = mp;
6684 	mp = rst_mp;
6685 
6686 	/*
6687 	 * Increment the connref, this ref will be released by the squeue
6688 	 * framework.
6689 	 */
6690 	CONN_INC_REF(connp);
6691 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6692 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6693 }
6694 
6695 /*
6696  * Fanout for TCP packets
6697  * The caller puts <fport, lport> in the ports parameter.
6698  *
6699  * IPQoS Notes
6700  * Before sending it to the client, invoke IPPF processing.
6701  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6702  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6703  * ip_policy is false.
6704  */
6705 static void
6706 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6707     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6708 {
6709 	mblk_t  *first_mp;
6710 	boolean_t secure;
6711 	uint32_t ill_index;
6712 	int	ip_hdr_len;
6713 	tcph_t	*tcph;
6714 	boolean_t syn_present = B_FALSE;
6715 	conn_t	*connp;
6716 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6717 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6718 
6719 	ASSERT(recv_ill != NULL);
6720 
6721 	first_mp = mp;
6722 	if (mctl_present) {
6723 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6724 		mp = first_mp->b_cont;
6725 		secure = ipsec_in_is_secure(first_mp);
6726 		ASSERT(mp != NULL);
6727 	} else {
6728 		secure = B_FALSE;
6729 	}
6730 
6731 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6732 
6733 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6734 	    zoneid, ipst)) == NULL) {
6735 		/*
6736 		 * No connected connection or listener. Send a
6737 		 * TH_RST via tcp_xmit_listeners_reset.
6738 		 */
6739 
6740 		/* Initiate IPPf processing, if needed. */
6741 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6742 			uint32_t ill_index;
6743 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6744 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6745 			if (first_mp == NULL)
6746 				return;
6747 		}
6748 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6749 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6750 		    zoneid));
6751 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6752 		    ipst->ips_netstack->netstack_tcp, NULL);
6753 		return;
6754 	}
6755 
6756 	/*
6757 	 * Allocate the SYN for the TCP connection here itself
6758 	 */
6759 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6760 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6761 		if (IPCL_IS_TCP(connp)) {
6762 			squeue_t *sqp;
6763 
6764 			/*
6765 			 * If the queue belongs to a conn, and fused tcp
6766 			 * loopback is enabled, assign the eager's squeue
6767 			 * to be that of the active connect's. Note that
6768 			 * we don't check for IP_FF_LOOPBACK here since this
6769 			 * routine gets called only for loopback (unlike the
6770 			 * IPv6 counterpart).
6771 			 */
6772 			if (do_tcp_fusion &&
6773 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6774 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6775 			    !secure &&
6776 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6777 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6778 				sqp = Q_TO_CONN(q)->conn_sqp;
6779 			} else {
6780 				sqp = IP_SQUEUE_GET(lbolt);
6781 			}
6782 
6783 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6784 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6785 			syn_present = B_TRUE;
6786 		}
6787 	}
6788 
6789 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6790 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6791 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6792 		if ((flags & TH_RST) || (flags & TH_URG)) {
6793 			CONN_DEC_REF(connp);
6794 			freemsg(first_mp);
6795 			return;
6796 		}
6797 		if (flags & TH_ACK) {
6798 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6799 			    ipst->ips_netstack->netstack_tcp, connp);
6800 			CONN_DEC_REF(connp);
6801 			return;
6802 		}
6803 
6804 		CONN_DEC_REF(connp);
6805 		freemsg(first_mp);
6806 		return;
6807 	}
6808 
6809 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6810 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6811 		    NULL, mctl_present);
6812 		if (first_mp == NULL) {
6813 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6814 			CONN_DEC_REF(connp);
6815 			return;
6816 		}
6817 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6818 			ASSERT(syn_present);
6819 			if (mctl_present) {
6820 				ASSERT(first_mp != mp);
6821 				first_mp->b_datap->db_struioflag |=
6822 				    STRUIO_POLICY;
6823 			} else {
6824 				ASSERT(first_mp == mp);
6825 				mp->b_datap->db_struioflag &=
6826 				    ~STRUIO_EAGER;
6827 				mp->b_datap->db_struioflag |=
6828 				    STRUIO_POLICY;
6829 			}
6830 		} else {
6831 			/*
6832 			 * Discard first_mp early since we're dealing with a
6833 			 * fully-connected conn_t and tcp doesn't do policy in
6834 			 * this case.
6835 			 */
6836 			if (mctl_present) {
6837 				freeb(first_mp);
6838 				mctl_present = B_FALSE;
6839 			}
6840 			first_mp = mp;
6841 		}
6842 	}
6843 
6844 	/*
6845 	 * Initiate policy processing here if needed. If we get here from
6846 	 * icmp_inbound_error_fanout, ip_policy is false.
6847 	 */
6848 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6849 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6850 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6851 		if (mp == NULL) {
6852 			CONN_DEC_REF(connp);
6853 			if (mctl_present)
6854 				freeb(first_mp);
6855 			return;
6856 		} else if (mctl_present) {
6857 			ASSERT(first_mp != mp);
6858 			first_mp->b_cont = mp;
6859 		} else {
6860 			first_mp = mp;
6861 		}
6862 	}
6863 
6864 	/* Handle socket options. */
6865 	if (!syn_present &&
6866 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6867 		/* Add header */
6868 		ASSERT(recv_ill != NULL);
6869 		/*
6870 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6871 		 * IPF_RECVIF.
6872 		 */
6873 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6874 		    ipst);
6875 		if (mp == NULL) {
6876 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6877 			CONN_DEC_REF(connp);
6878 			if (mctl_present)
6879 				freeb(first_mp);
6880 			return;
6881 		} else if (mctl_present) {
6882 			/*
6883 			 * ip_add_info might return a new mp.
6884 			 */
6885 			ASSERT(first_mp != mp);
6886 			first_mp->b_cont = mp;
6887 		} else {
6888 			first_mp = mp;
6889 		}
6890 	}
6891 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6892 	if (IPCL_IS_TCP(connp)) {
6893 		/* do not drain, certain use cases can blow the stack */
6894 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6895 		    connp, SQ_NODRAIN, SQTAG_IP_FANOUT_TCP);
6896 	} else {
6897 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6898 		(connp->conn_recv)(connp, first_mp, NULL);
6899 		CONN_DEC_REF(connp);
6900 	}
6901 }
6902 
6903 /*
6904  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6905  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6906  * is not consumed.
6907  *
6908  * One of four things can happen, all of which affect the passed-in mblk:
6909  *
6910  * 1.) ICMP messages that go through here just get returned TRUE.
6911  *
6912  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6913  *
6914  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6915  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6916  *
6917  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6918  */
6919 static boolean_t
6920 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6921     ipsec_stack_t *ipss)
6922 {
6923 	int shift, plen, iph_len;
6924 	ipha_t *ipha;
6925 	udpha_t *udpha;
6926 	uint32_t *spi;
6927 	uint32_t esp_ports;
6928 	uint8_t *orptr;
6929 	boolean_t free_ire;
6930 
6931 	if (DB_TYPE(mp) == M_CTL) {
6932 		/*
6933 		 * ICMP message with UDP inside.  Don't bother stripping, just
6934 		 * send it up.
6935 		 *
6936 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6937 		 * to ignore errors set by ICMP anyway ('cause they might be
6938 		 * forged), but that's the app's decision, not ours.
6939 		 */
6940 
6941 		/* Bunch of reality checks for DEBUG kernels... */
6942 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6943 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6944 
6945 		return (B_TRUE);
6946 	}
6947 
6948 	ipha = (ipha_t *)mp->b_rptr;
6949 	iph_len = IPH_HDR_LENGTH(ipha);
6950 	plen = ntohs(ipha->ipha_length);
6951 
6952 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6953 		/*
6954 		 * Most likely a keepalive for the benefit of an intervening
6955 		 * NAT.  These aren't for us, per se, so drop it.
6956 		 *
6957 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6958 		 * byte packets (keepalives are 1-byte), but we'll drop them
6959 		 * also.
6960 		 */
6961 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6962 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6963 		return (B_FALSE);
6964 	}
6965 
6966 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6967 		/* might as well pull it all up - it might be ESP. */
6968 		if (!pullupmsg(mp, -1)) {
6969 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6970 			    DROPPER(ipss, ipds_esp_nomem),
6971 			    &ipss->ipsec_dropper);
6972 			return (B_FALSE);
6973 		}
6974 
6975 		ipha = (ipha_t *)mp->b_rptr;
6976 	}
6977 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6978 	if (*spi == 0) {
6979 		/* UDP packet - remove 0-spi. */
6980 		shift = sizeof (uint32_t);
6981 	} else {
6982 		/* ESP-in-UDP packet - reduce to ESP. */
6983 		ipha->ipha_protocol = IPPROTO_ESP;
6984 		shift = sizeof (udpha_t);
6985 	}
6986 
6987 	/* Fix IP header */
6988 	ipha->ipha_length = htons(plen - shift);
6989 	ipha->ipha_hdr_checksum = 0;
6990 
6991 	orptr = mp->b_rptr;
6992 	mp->b_rptr += shift;
6993 
6994 	udpha = (udpha_t *)(orptr + iph_len);
6995 	if (*spi == 0) {
6996 		ASSERT((uint8_t *)ipha == orptr);
6997 		udpha->uha_length = htons(plen - shift - iph_len);
6998 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6999 		esp_ports = 0;
7000 	} else {
7001 		esp_ports = *((uint32_t *)udpha);
7002 		ASSERT(esp_ports != 0);
7003 	}
7004 	ovbcopy(orptr, orptr + shift, iph_len);
7005 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7006 		ipha = (ipha_t *)(orptr + shift);
7007 
7008 		free_ire = (ire == NULL);
7009 		if (free_ire) {
7010 			/* Re-acquire ire. */
7011 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7012 			    ipss->ipsec_netstack->netstack_ip);
7013 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7014 				if (ire != NULL)
7015 					ire_refrele(ire);
7016 				/*
7017 				 * Do a regular freemsg(), as this is an IP
7018 				 * error (no local route) not an IPsec one.
7019 				 */
7020 				freemsg(mp);
7021 			}
7022 		}
7023 
7024 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7025 		if (free_ire)
7026 			ire_refrele(ire);
7027 	}
7028 
7029 	return (esp_ports == 0);
7030 }
7031 
7032 /*
7033  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7034  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7035  * Caller is responsible for dropping references to the conn, and freeing
7036  * first_mp.
7037  *
7038  * IPQoS Notes
7039  * Before sending it to the client, invoke IPPF processing. Policy processing
7040  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7041  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7042  * ip_wput_local, ip_policy is false.
7043  */
7044 static void
7045 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7046     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7047     boolean_t ip_policy)
7048 {
7049 	boolean_t	mctl_present = (first_mp != NULL);
7050 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7051 	uint32_t	ill_index;
7052 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7053 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7054 
7055 	ASSERT(ill != NULL);
7056 
7057 	if (mctl_present)
7058 		first_mp->b_cont = mp;
7059 	else
7060 		first_mp = mp;
7061 
7062 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7063 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7064 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7065 		freemsg(first_mp);
7066 		return;
7067 	}
7068 
7069 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7070 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7071 		    NULL, mctl_present);
7072 		/* Freed by ipsec_check_inbound_policy(). */
7073 		if (first_mp == NULL) {
7074 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7075 			return;
7076 		}
7077 	}
7078 	if (mctl_present)
7079 		freeb(first_mp);
7080 
7081 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7082 	if (connp->conn_udp->udp_nat_t_endpoint) {
7083 		if (mctl_present) {
7084 			/* mctl_present *shouldn't* happen. */
7085 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7086 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7087 			    &ipss->ipsec_dropper);
7088 			return;
7089 		}
7090 
7091 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7092 			return;
7093 	}
7094 
7095 	/* Handle options. */
7096 	if (connp->conn_recvif)
7097 		in_flags = IPF_RECVIF;
7098 	/*
7099 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7100 	 * passed to ip_add_info is based on IP version of connp.
7101 	 */
7102 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7103 		if (connp->conn_af_isv6) {
7104 			/*
7105 			 * V6 only needs index
7106 			 */
7107 			in_flags |= IPF_RECVIF;
7108 		} else {
7109 			/*
7110 			 * V4 needs index + matching address.
7111 			 */
7112 			in_flags |= IPF_RECVADDR;
7113 		}
7114 	}
7115 
7116 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7117 		in_flags |= IPF_RECVSLLA;
7118 
7119 	/*
7120 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7121 	 * freed if the packet is dropped. The caller will do so.
7122 	 */
7123 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7124 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7125 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7126 		if (mp == NULL) {
7127 			return;
7128 		}
7129 	}
7130 	if ((in_flags != 0) &&
7131 	    (mp->b_datap->db_type != M_CTL)) {
7132 		/*
7133 		 * The actual data will be contained in b_cont
7134 		 * upon successful return of the following call
7135 		 * else original mblk is returned
7136 		 */
7137 		ASSERT(recv_ill != NULL);
7138 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7139 		    ipst);
7140 	}
7141 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7142 	/* Send it upstream */
7143 	(connp->conn_recv)(connp, mp, NULL);
7144 }
7145 
7146 /*
7147  * Fanout for UDP packets.
7148  * The caller puts <fport, lport> in the ports parameter.
7149  *
7150  * If SO_REUSEADDR is set all multicast and broadcast packets
7151  * will be delivered to all streams bound to the same port.
7152  *
7153  * Zones notes:
7154  * Multicast and broadcast packets will be distributed to streams in all zones.
7155  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7156  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7157  * packets. To maintain this behavior with multiple zones, the conns are grouped
7158  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7159  * each zone. If unset, all the following conns in the same zone are skipped.
7160  */
7161 static void
7162 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7163     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7164     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7165 {
7166 	uint32_t	dstport, srcport;
7167 	ipaddr_t	dst;
7168 	mblk_t		*first_mp;
7169 	boolean_t	secure;
7170 	in6_addr_t	v6src;
7171 	conn_t		*connp;
7172 	connf_t		*connfp;
7173 	conn_t		*first_connp;
7174 	conn_t		*next_connp;
7175 	mblk_t		*mp1, *first_mp1;
7176 	ipaddr_t	src;
7177 	zoneid_t	last_zoneid;
7178 	boolean_t	reuseaddr;
7179 	boolean_t	shared_addr;
7180 	boolean_t	unlabeled;
7181 	ip_stack_t	*ipst;
7182 
7183 	ASSERT(recv_ill != NULL);
7184 	ipst = recv_ill->ill_ipst;
7185 
7186 	first_mp = mp;
7187 	if (mctl_present) {
7188 		mp = first_mp->b_cont;
7189 		first_mp->b_cont = NULL;
7190 		secure = ipsec_in_is_secure(first_mp);
7191 		ASSERT(mp != NULL);
7192 	} else {
7193 		first_mp = NULL;
7194 		secure = B_FALSE;
7195 	}
7196 
7197 	/* Extract ports in net byte order */
7198 	dstport = htons(ntohl(ports) & 0xFFFF);
7199 	srcport = htons(ntohl(ports) >> 16);
7200 	dst = ipha->ipha_dst;
7201 	src = ipha->ipha_src;
7202 
7203 	unlabeled = B_FALSE;
7204 	if (is_system_labeled())
7205 		/* Cred cannot be null on IPv4 */
7206 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7207 		    TSLF_UNLABELED) != 0;
7208 	shared_addr = (zoneid == ALL_ZONES);
7209 	if (shared_addr) {
7210 		/*
7211 		 * No need to handle exclusive-stack zones since ALL_ZONES
7212 		 * only applies to the shared stack.
7213 		 */
7214 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7215 		/*
7216 		 * If no shared MLP is found, tsol_mlp_findzone returns
7217 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7218 		 * search for the zone based on the packet label.
7219 		 *
7220 		 * If there is such a zone, we prefer to find a
7221 		 * connection in it.  Otherwise, we look for a
7222 		 * MAC-exempt connection in any zone whose label
7223 		 * dominates the default label on the packet.
7224 		 */
7225 		if (zoneid == ALL_ZONES)
7226 			zoneid = tsol_packet_to_zoneid(mp);
7227 		else
7228 			unlabeled = B_FALSE;
7229 	}
7230 
7231 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7232 	mutex_enter(&connfp->connf_lock);
7233 	connp = connfp->connf_head;
7234 	if (!broadcast && !CLASSD(dst)) {
7235 		/*
7236 		 * Not broadcast or multicast. Send to the one (first)
7237 		 * client we find. No need to check conn_wantpacket()
7238 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7239 		 * IPv4 unicast packets.
7240 		 */
7241 		while ((connp != NULL) &&
7242 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7243 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7244 		    !(unlabeled && (connp->conn_mac_mode != CONN_MAC_DEFAULT) &&
7245 		    shared_addr)))) {
7246 			/*
7247 			 * We keep searching since the conn did not match,
7248 			 * or its zone did not match and it is not either
7249 			 * an allzones conn or a mac exempt conn (if the
7250 			 * sender is unlabeled.)
7251 			 */
7252 			connp = connp->conn_next;
7253 		}
7254 
7255 		if (connp == NULL ||
7256 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7257 			goto notfound;
7258 
7259 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7260 
7261 		if (is_system_labeled() &&
7262 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7263 		    connp))
7264 			goto notfound;
7265 
7266 		CONN_INC_REF(connp);
7267 		mutex_exit(&connfp->connf_lock);
7268 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7269 		    flags, recv_ill, ip_policy);
7270 		IP_STAT(ipst, ip_udp_fannorm);
7271 		CONN_DEC_REF(connp);
7272 		return;
7273 	}
7274 
7275 	/*
7276 	 * Broadcast and multicast case
7277 	 *
7278 	 * Need to check conn_wantpacket().
7279 	 * If SO_REUSEADDR has been set on the first we send the
7280 	 * packet to all clients that have joined the group and
7281 	 * match the port.
7282 	 */
7283 
7284 	while (connp != NULL) {
7285 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7286 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7287 		    (!is_system_labeled() ||
7288 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7289 		    connp)))
7290 			break;
7291 		connp = connp->conn_next;
7292 	}
7293 
7294 	if (connp == NULL ||
7295 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7296 		goto notfound;
7297 
7298 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7299 
7300 	first_connp = connp;
7301 	/*
7302 	 * When SO_REUSEADDR is not set, send the packet only to the first
7303 	 * matching connection in its zone by keeping track of the zoneid.
7304 	 */
7305 	reuseaddr = first_connp->conn_reuseaddr;
7306 	last_zoneid = first_connp->conn_zoneid;
7307 
7308 	CONN_INC_REF(connp);
7309 	connp = connp->conn_next;
7310 	for (;;) {
7311 		while (connp != NULL) {
7312 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7313 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7314 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7315 			    (!is_system_labeled() ||
7316 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7317 			    shared_addr, connp)))
7318 				break;
7319 			connp = connp->conn_next;
7320 		}
7321 		/*
7322 		 * Just copy the data part alone. The mctl part is
7323 		 * needed just for verifying policy and it is never
7324 		 * sent up.
7325 		 */
7326 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7327 		    ((mp1 = copymsg(mp)) == NULL))) {
7328 			/*
7329 			 * No more interested clients or memory
7330 			 * allocation failed
7331 			 */
7332 			connp = first_connp;
7333 			break;
7334 		}
7335 		if (connp->conn_zoneid != last_zoneid) {
7336 			/*
7337 			 * Update the zoneid so that the packet isn't sent to
7338 			 * any more conns in the same zone unless SO_REUSEADDR
7339 			 * is set.
7340 			 */
7341 			reuseaddr = connp->conn_reuseaddr;
7342 			last_zoneid = connp->conn_zoneid;
7343 		}
7344 		if (first_mp != NULL) {
7345 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7346 			    ipsec_info_type == IPSEC_IN);
7347 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7348 			    ipst->ips_netstack);
7349 			if (first_mp1 == NULL) {
7350 				freemsg(mp1);
7351 				connp = first_connp;
7352 				break;
7353 			}
7354 		} else {
7355 			first_mp1 = NULL;
7356 		}
7357 		CONN_INC_REF(connp);
7358 		mutex_exit(&connfp->connf_lock);
7359 		/*
7360 		 * IPQoS notes: We don't send the packet for policy
7361 		 * processing here, will do it for the last one (below).
7362 		 * i.e. we do it per-packet now, but if we do policy
7363 		 * processing per-conn, then we would need to do it
7364 		 * here too.
7365 		 */
7366 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7367 		    ipha, flags, recv_ill, B_FALSE);
7368 		mutex_enter(&connfp->connf_lock);
7369 		/* Follow the next pointer before releasing the conn. */
7370 		next_connp = connp->conn_next;
7371 		IP_STAT(ipst, ip_udp_fanmb);
7372 		CONN_DEC_REF(connp);
7373 		connp = next_connp;
7374 	}
7375 
7376 	/* Last one.  Send it upstream. */
7377 	mutex_exit(&connfp->connf_lock);
7378 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7379 	    recv_ill, ip_policy);
7380 	IP_STAT(ipst, ip_udp_fanmb);
7381 	CONN_DEC_REF(connp);
7382 	return;
7383 
7384 notfound:
7385 
7386 	mutex_exit(&connfp->connf_lock);
7387 	IP_STAT(ipst, ip_udp_fanothers);
7388 	/*
7389 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7390 	 * have already been matched above, since they live in the IPv4
7391 	 * fanout tables. This implies we only need to
7392 	 * check for IPv6 in6addr_any endpoints here.
7393 	 * Thus we compare using ipv6_all_zeros instead of the destination
7394 	 * address, except for the multicast group membership lookup which
7395 	 * uses the IPv4 destination.
7396 	 */
7397 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7398 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7399 	mutex_enter(&connfp->connf_lock);
7400 	connp = connfp->connf_head;
7401 	if (!broadcast && !CLASSD(dst)) {
7402 		while (connp != NULL) {
7403 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7404 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7405 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7406 			    !connp->conn_ipv6_v6only)
7407 				break;
7408 			connp = connp->conn_next;
7409 		}
7410 
7411 		if (connp != NULL && is_system_labeled() &&
7412 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7413 		    connp))
7414 			connp = NULL;
7415 
7416 		if (connp == NULL ||
7417 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7418 			/*
7419 			 * No one bound to this port.  Is
7420 			 * there a client that wants all
7421 			 * unclaimed datagrams?
7422 			 */
7423 			mutex_exit(&connfp->connf_lock);
7424 
7425 			if (mctl_present)
7426 				first_mp->b_cont = mp;
7427 			else
7428 				first_mp = mp;
7429 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7430 			    connf_head != NULL) {
7431 				ip_fanout_proto(q, first_mp, ill, ipha,
7432 				    flags | IP_FF_RAWIP, mctl_present,
7433 				    ip_policy, recv_ill, zoneid);
7434 			} else {
7435 				if (ip_fanout_send_icmp(q, first_mp, flags,
7436 				    ICMP_DEST_UNREACHABLE,
7437 				    ICMP_PORT_UNREACHABLE,
7438 				    mctl_present, zoneid, ipst)) {
7439 					BUMP_MIB(ill->ill_ip_mib,
7440 					    udpIfStatsNoPorts);
7441 				}
7442 			}
7443 			return;
7444 		}
7445 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7446 
7447 		CONN_INC_REF(connp);
7448 		mutex_exit(&connfp->connf_lock);
7449 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7450 		    flags, recv_ill, ip_policy);
7451 		CONN_DEC_REF(connp);
7452 		return;
7453 	}
7454 	/*
7455 	 * IPv4 multicast packet being delivered to an AF_INET6
7456 	 * in6addr_any endpoint.
7457 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7458 	 * and not conn_wantpacket_v6() since any multicast membership is
7459 	 * for an IPv4-mapped multicast address.
7460 	 * The packet is sent to all clients in all zones that have joined the
7461 	 * group and match the port.
7462 	 */
7463 	while (connp != NULL) {
7464 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7465 		    srcport, v6src) &&
7466 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7467 		    (!is_system_labeled() ||
7468 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7469 		    connp)))
7470 			break;
7471 		connp = connp->conn_next;
7472 	}
7473 
7474 	if (connp == NULL ||
7475 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7476 		/*
7477 		 * No one bound to this port.  Is
7478 		 * there a client that wants all
7479 		 * unclaimed datagrams?
7480 		 */
7481 		mutex_exit(&connfp->connf_lock);
7482 
7483 		if (mctl_present)
7484 			first_mp->b_cont = mp;
7485 		else
7486 			first_mp = mp;
7487 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7488 		    NULL) {
7489 			ip_fanout_proto(q, first_mp, ill, ipha,
7490 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7491 			    recv_ill, zoneid);
7492 		} else {
7493 			/*
7494 			 * We used to attempt to send an icmp error here, but
7495 			 * since this is known to be a multicast packet
7496 			 * and we don't send icmp errors in response to
7497 			 * multicast, just drop the packet and give up sooner.
7498 			 */
7499 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7500 			freemsg(first_mp);
7501 		}
7502 		return;
7503 	}
7504 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7505 
7506 	first_connp = connp;
7507 
7508 	CONN_INC_REF(connp);
7509 	connp = connp->conn_next;
7510 	for (;;) {
7511 		while (connp != NULL) {
7512 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7513 			    ipv6_all_zeros, srcport, v6src) &&
7514 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7515 			    (!is_system_labeled() ||
7516 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7517 			    shared_addr, connp)))
7518 				break;
7519 			connp = connp->conn_next;
7520 		}
7521 		/*
7522 		 * Just copy the data part alone. The mctl part is
7523 		 * needed just for verifying policy and it is never
7524 		 * sent up.
7525 		 */
7526 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7527 		    ((mp1 = copymsg(mp)) == NULL))) {
7528 			/*
7529 			 * No more intested clients or memory
7530 			 * allocation failed
7531 			 */
7532 			connp = first_connp;
7533 			break;
7534 		}
7535 		if (first_mp != NULL) {
7536 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7537 			    ipsec_info_type == IPSEC_IN);
7538 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7539 			    ipst->ips_netstack);
7540 			if (first_mp1 == NULL) {
7541 				freemsg(mp1);
7542 				connp = first_connp;
7543 				break;
7544 			}
7545 		} else {
7546 			first_mp1 = NULL;
7547 		}
7548 		CONN_INC_REF(connp);
7549 		mutex_exit(&connfp->connf_lock);
7550 		/*
7551 		 * IPQoS notes: We don't send the packet for policy
7552 		 * processing here, will do it for the last one (below).
7553 		 * i.e. we do it per-packet now, but if we do policy
7554 		 * processing per-conn, then we would need to do it
7555 		 * here too.
7556 		 */
7557 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7558 		    ipha, flags, recv_ill, B_FALSE);
7559 		mutex_enter(&connfp->connf_lock);
7560 		/* Follow the next pointer before releasing the conn. */
7561 		next_connp = connp->conn_next;
7562 		CONN_DEC_REF(connp);
7563 		connp = next_connp;
7564 	}
7565 
7566 	/* Last one.  Send it upstream. */
7567 	mutex_exit(&connfp->connf_lock);
7568 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7569 	    recv_ill, ip_policy);
7570 	CONN_DEC_REF(connp);
7571 }
7572 
7573 /*
7574  * Complete the ip_wput header so that it
7575  * is possible to generate ICMP
7576  * errors.
7577  */
7578 int
7579 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7580 {
7581 	ire_t *ire;
7582 
7583 	if (ipha->ipha_src == INADDR_ANY) {
7584 		ire = ire_lookup_local(zoneid, ipst);
7585 		if (ire == NULL) {
7586 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7587 			return (1);
7588 		}
7589 		ipha->ipha_src = ire->ire_addr;
7590 		ire_refrele(ire);
7591 	}
7592 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7593 	ipha->ipha_hdr_checksum = 0;
7594 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7595 	return (0);
7596 }
7597 
7598 /*
7599  * Nobody should be sending
7600  * packets up this stream
7601  */
7602 static void
7603 ip_lrput(queue_t *q, mblk_t *mp)
7604 {
7605 	mblk_t *mp1;
7606 
7607 	switch (mp->b_datap->db_type) {
7608 	case M_FLUSH:
7609 		/* Turn around */
7610 		if (*mp->b_rptr & FLUSHW) {
7611 			*mp->b_rptr &= ~FLUSHR;
7612 			qreply(q, mp);
7613 			return;
7614 		}
7615 		break;
7616 	}
7617 	/* Could receive messages that passed through ar_rput */
7618 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7619 		mp1->b_prev = mp1->b_next = NULL;
7620 	freemsg(mp);
7621 }
7622 
7623 /* Nobody should be sending packets down this stream */
7624 /* ARGSUSED */
7625 void
7626 ip_lwput(queue_t *q, mblk_t *mp)
7627 {
7628 	freemsg(mp);
7629 }
7630 
7631 /*
7632  * Move the first hop in any source route to ipha_dst and remove that part of
7633  * the source route.  Called by other protocols.  Errors in option formatting
7634  * are ignored - will be handled by ip_wput_options Return the final
7635  * destination (either ipha_dst or the last entry in a source route.)
7636  */
7637 ipaddr_t
7638 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7639 {
7640 	ipoptp_t	opts;
7641 	uchar_t		*opt;
7642 	uint8_t		optval;
7643 	uint8_t		optlen;
7644 	ipaddr_t	dst;
7645 	int		i;
7646 	ire_t		*ire;
7647 	ip_stack_t	*ipst = ns->netstack_ip;
7648 
7649 	ip2dbg(("ip_massage_options\n"));
7650 	dst = ipha->ipha_dst;
7651 	for (optval = ipoptp_first(&opts, ipha);
7652 	    optval != IPOPT_EOL;
7653 	    optval = ipoptp_next(&opts)) {
7654 		opt = opts.ipoptp_cur;
7655 		switch (optval) {
7656 			uint8_t off;
7657 		case IPOPT_SSRR:
7658 		case IPOPT_LSRR:
7659 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7660 				ip1dbg(("ip_massage_options: bad src route\n"));
7661 				break;
7662 			}
7663 			optlen = opts.ipoptp_len;
7664 			off = opt[IPOPT_OFFSET];
7665 			off--;
7666 		redo_srr:
7667 			if (optlen < IP_ADDR_LEN ||
7668 			    off > optlen - IP_ADDR_LEN) {
7669 				/* End of source route */
7670 				ip1dbg(("ip_massage_options: end of SR\n"));
7671 				break;
7672 			}
7673 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7674 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7675 			    ntohl(dst)));
7676 			/*
7677 			 * Check if our address is present more than
7678 			 * once as consecutive hops in source route.
7679 			 * XXX verify per-interface ip_forwarding
7680 			 * for source route?
7681 			 */
7682 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7683 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7684 			if (ire != NULL) {
7685 				ire_refrele(ire);
7686 				off += IP_ADDR_LEN;
7687 				goto redo_srr;
7688 			}
7689 			if (dst == htonl(INADDR_LOOPBACK)) {
7690 				ip1dbg(("ip_massage_options: loopback addr in "
7691 				    "source route!\n"));
7692 				break;
7693 			}
7694 			/*
7695 			 * Update ipha_dst to be the first hop and remove the
7696 			 * first hop from the source route (by overwriting
7697 			 * part of the option with NOP options).
7698 			 */
7699 			ipha->ipha_dst = dst;
7700 			/* Put the last entry in dst */
7701 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7702 			    3;
7703 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7704 
7705 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7706 			    ntohl(dst)));
7707 			/* Move down and overwrite */
7708 			opt[IP_ADDR_LEN] = opt[0];
7709 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7710 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7711 			for (i = 0; i < IP_ADDR_LEN; i++)
7712 				opt[i] = IPOPT_NOP;
7713 			break;
7714 		}
7715 	}
7716 	return (dst);
7717 }
7718 
7719 /*
7720  * Return the network mask
7721  * associated with the specified address.
7722  */
7723 ipaddr_t
7724 ip_net_mask(ipaddr_t addr)
7725 {
7726 	uchar_t	*up = (uchar_t *)&addr;
7727 	ipaddr_t mask = 0;
7728 	uchar_t	*maskp = (uchar_t *)&mask;
7729 
7730 #if defined(__i386) || defined(__amd64)
7731 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7732 #endif
7733 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7734 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7735 #endif
7736 	if (CLASSD(addr)) {
7737 		maskp[0] = 0xF0;
7738 		return (mask);
7739 	}
7740 
7741 	/* We assume Class E default netmask to be 32 */
7742 	if (CLASSE(addr))
7743 		return (0xffffffffU);
7744 
7745 	if (addr == 0)
7746 		return (0);
7747 	maskp[0] = 0xFF;
7748 	if ((up[0] & 0x80) == 0)
7749 		return (mask);
7750 
7751 	maskp[1] = 0xFF;
7752 	if ((up[0] & 0xC0) == 0x80)
7753 		return (mask);
7754 
7755 	maskp[2] = 0xFF;
7756 	if ((up[0] & 0xE0) == 0xC0)
7757 		return (mask);
7758 
7759 	/* Otherwise return no mask */
7760 	return ((ipaddr_t)0);
7761 }
7762 
7763 /*
7764  * Helper ill lookup function used by IPsec.
7765  */
7766 ill_t *
7767 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7768 {
7769 	ill_t *ret_ill;
7770 
7771 	ASSERT(ifindex != 0);
7772 
7773 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7774 	    ipst);
7775 	if (ret_ill == NULL) {
7776 		if (isv6) {
7777 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7778 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7779 			    ifindex));
7780 		} else {
7781 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7782 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7783 			    ifindex));
7784 		}
7785 		freemsg(first_mp);
7786 		return (NULL);
7787 	}
7788 	return (ret_ill);
7789 }
7790 
7791 /*
7792  * IPv4 -
7793  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7794  * out a packet to a destination address for which we do not have specific
7795  * (or sufficient) routing information.
7796  *
7797  * NOTE : These are the scopes of some of the variables that point at IRE,
7798  *	  which needs to be followed while making any future modifications
7799  *	  to avoid memory leaks.
7800  *
7801  *	- ire and sire are the entries looked up initially by
7802  *	  ire_ftable_lookup.
7803  *	- ipif_ire is used to hold the interface ire associated with
7804  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7805  *	  it before branching out to error paths.
7806  *	- save_ire is initialized before ire_create, so that ire returned
7807  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7808  *	  before breaking out of the switch.
7809  *
7810  *	Thus on failures, we have to REFRELE only ire and sire, if they
7811  *	are not NULL.
7812  */
7813 void
7814 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7815     zoneid_t zoneid, ip_stack_t *ipst)
7816 {
7817 	areq_t	*areq;
7818 	ipaddr_t gw = 0;
7819 	ire_t	*ire = NULL;
7820 	mblk_t	*res_mp;
7821 	ipaddr_t *addrp;
7822 	ipaddr_t nexthop_addr;
7823 	ipif_t  *src_ipif = NULL;
7824 	ill_t	*dst_ill = NULL;
7825 	ipha_t  *ipha;
7826 	ire_t	*sire = NULL;
7827 	mblk_t	*first_mp;
7828 	ire_t	*save_ire;
7829 	ushort_t ire_marks = 0;
7830 	boolean_t mctl_present;
7831 	ipsec_out_t *io;
7832 	mblk_t	*saved_mp;
7833 	mblk_t	*copy_mp = NULL;
7834 	mblk_t	*xmit_mp = NULL;
7835 	ipaddr_t save_dst;
7836 	uint32_t multirt_flags =
7837 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7838 	boolean_t multirt_is_resolvable;
7839 	boolean_t multirt_resolve_next;
7840 	boolean_t unspec_src;
7841 	boolean_t ip_nexthop = B_FALSE;
7842 	tsol_ire_gw_secattr_t *attrp = NULL;
7843 	tsol_gcgrp_t *gcgrp = NULL;
7844 	tsol_gcgrp_addr_t ga;
7845 	int multirt_res_failures = 0;
7846 	int multirt_res_attempts = 0;
7847 	int multirt_already_resolved = 0;
7848 	boolean_t multirt_no_icmp_error = B_FALSE;
7849 
7850 	if (ip_debug > 2) {
7851 		/* ip1dbg */
7852 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7853 	}
7854 
7855 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7856 	if (mctl_present) {
7857 		io = (ipsec_out_t *)first_mp->b_rptr;
7858 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7859 		ASSERT(zoneid == io->ipsec_out_zoneid);
7860 		ASSERT(zoneid != ALL_ZONES);
7861 	}
7862 
7863 	ipha = (ipha_t *)mp->b_rptr;
7864 
7865 	/* All multicast lookups come through ip_newroute_ipif() */
7866 	if (CLASSD(dst)) {
7867 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7868 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7869 		freemsg(first_mp);
7870 		return;
7871 	}
7872 
7873 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7874 		ip_nexthop = B_TRUE;
7875 		nexthop_addr = io->ipsec_out_nexthop_addr;
7876 	}
7877 	/*
7878 	 * If this IRE is created for forwarding or it is not for
7879 	 * traffic for congestion controlled protocols, mark it as temporary.
7880 	 */
7881 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7882 		ire_marks |= IRE_MARK_TEMPORARY;
7883 
7884 	/*
7885 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7886 	 * chain until it gets the most specific information available.
7887 	 * For example, we know that there is no IRE_CACHE for this dest,
7888 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7889 	 * ire_ftable_lookup will look up the gateway, etc.
7890 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7891 	 * to the destination, of equal netmask length in the forward table,
7892 	 * will be recursively explored. If no information is available
7893 	 * for the final gateway of that route, we force the returned ire
7894 	 * to be equal to sire using MATCH_IRE_PARENT.
7895 	 * At least, in this case we have a starting point (in the buckets)
7896 	 * to look for other routes to the destination in the forward table.
7897 	 * This is actually used only for multirouting, where a list
7898 	 * of routes has to be processed in sequence.
7899 	 *
7900 	 * In the process of coming up with the most specific information,
7901 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7902 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7903 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7904 	 * Two caveats when handling incomplete ire's in ip_newroute:
7905 	 * - we should be careful when accessing its ire_nce (specifically
7906 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7907 	 * - not all legacy code path callers are prepared to handle
7908 	 *   incomplete ire's, so we should not create/add incomplete
7909 	 *   ire_cache entries here. (See discussion about temporary solution
7910 	 *   further below).
7911 	 *
7912 	 * In order to minimize packet dropping, and to preserve existing
7913 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7914 	 * gateway, and instead use the IF_RESOLVER ire to send out
7915 	 * another request to ARP (this is achieved by passing the
7916 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7917 	 * arp response comes back in ip_wput_nondata, we will create
7918 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7919 	 *
7920 	 * Note that this is a temporary solution; the correct solution is
7921 	 * to create an incomplete  per-dst ire_cache entry, and send the
7922 	 * packet out when the gw's nce is resolved. In order to achieve this,
7923 	 * all packet processing must have been completed prior to calling
7924 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7925 	 * to be modified to accomodate this solution.
7926 	 */
7927 	if (ip_nexthop) {
7928 		/*
7929 		 * The first time we come here, we look for an IRE_INTERFACE
7930 		 * entry for the specified nexthop, set the dst to be the
7931 		 * nexthop address and create an IRE_CACHE entry for the
7932 		 * nexthop. The next time around, we are able to find an
7933 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7934 		 * nexthop address and create an IRE_CACHE entry for the
7935 		 * destination address via the specified nexthop.
7936 		 */
7937 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7938 		    msg_getlabel(mp), ipst);
7939 		if (ire != NULL) {
7940 			gw = nexthop_addr;
7941 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7942 		} else {
7943 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7944 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7945 			    msg_getlabel(mp),
7946 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7947 			    ipst);
7948 			if (ire != NULL) {
7949 				dst = nexthop_addr;
7950 			}
7951 		}
7952 	} else {
7953 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7954 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
7955 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7956 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7957 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7958 		    ipst);
7959 	}
7960 
7961 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7962 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7963 
7964 	/*
7965 	 * This loop is run only once in most cases.
7966 	 * We loop to resolve further routes only when the destination
7967 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7968 	 */
7969 	do {
7970 		/* Clear the previous iteration's values */
7971 		if (src_ipif != NULL) {
7972 			ipif_refrele(src_ipif);
7973 			src_ipif = NULL;
7974 		}
7975 		if (dst_ill != NULL) {
7976 			ill_refrele(dst_ill);
7977 			dst_ill = NULL;
7978 		}
7979 
7980 		multirt_resolve_next = B_FALSE;
7981 		/*
7982 		 * We check if packets have to be multirouted.
7983 		 * In this case, given the current <ire, sire> couple,
7984 		 * we look for the next suitable <ire, sire>.
7985 		 * This check is done in ire_multirt_lookup(),
7986 		 * which applies various criteria to find the next route
7987 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7988 		 * unchanged if it detects it has not been tried yet.
7989 		 */
7990 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7991 			ip3dbg(("ip_newroute: starting next_resolution "
7992 			    "with first_mp %p, tag %d\n",
7993 			    (void *)first_mp,
7994 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7995 
7996 			ASSERT(sire != NULL);
7997 			multirt_is_resolvable =
7998 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7999 			    &multirt_already_resolved, msg_getlabel(mp), ipst);
8000 
8001 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8002 			    "multirt_already_resolved %d, "
8003 			    "multirt_res_attempts %d, multirt_res_failures %d, "
8004 			    "ire %p, sire %p\n", multirt_is_resolvable,
8005 			    multirt_already_resolved, multirt_res_attempts,
8006 			    multirt_res_failures, (void *)ire, (void *)sire));
8007 
8008 			if (!multirt_is_resolvable) {
8009 				/*
8010 				 * No more multirt route to resolve; give up
8011 				 * (all routes resolved or no more
8012 				 * resolvable routes).
8013 				 */
8014 				if (ire != NULL) {
8015 					ire_refrele(ire);
8016 					ire = NULL;
8017 				}
8018 				/*
8019 				 * Generate ICMP error only if all attempts to
8020 				 * resolve multirt route failed and there is no
8021 				 * already resolved one.  Don't generate ICMP
8022 				 * error when:
8023 				 *
8024 				 *  1) there was no attempt to resolve
8025 				 *  2) at least one attempt passed
8026 				 *  3) a multirt route is already resolved
8027 				 *
8028 				 *  Case 1) may occur due to multiple
8029 				 *    resolution attempts during single
8030 				 *    ip_multirt_resolution_interval.
8031 				 *
8032 				 *  Case 2-3) means that CGTP destination is
8033 				 *    reachable via one link so we don't want to
8034 				 *    generate ICMP host unreachable error.
8035 				 */
8036 				if (multirt_res_attempts == 0 ||
8037 				    multirt_res_failures <
8038 				    multirt_res_attempts ||
8039 				    multirt_already_resolved > 0)
8040 					multirt_no_icmp_error = B_TRUE;
8041 			} else {
8042 				ASSERT(sire != NULL);
8043 				ASSERT(ire != NULL);
8044 
8045 				multirt_res_attempts++;
8046 			}
8047 		}
8048 
8049 		if (ire == NULL) {
8050 			if (ip_debug > 3) {
8051 				/* ip2dbg */
8052 				pr_addr_dbg("ip_newroute: "
8053 				    "can't resolve %s\n", AF_INET, &dst);
8054 			}
8055 			ip3dbg(("ip_newroute: "
8056 			    "ire %p, sire %p, multirt_no_icmp_error %d\n",
8057 			    (void *)ire, (void *)sire,
8058 			    (int)multirt_no_icmp_error));
8059 
8060 			if (sire != NULL) {
8061 				ire_refrele(sire);
8062 				sire = NULL;
8063 			}
8064 
8065 			if (multirt_no_icmp_error) {
8066 				/* There is no need to report an ICMP error. */
8067 				MULTIRT_DEBUG_UNTAG(first_mp);
8068 				freemsg(first_mp);
8069 				return;
8070 			}
8071 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8072 			    RTA_DST, ipst);
8073 			goto icmp_err_ret;
8074 		}
8075 
8076 		/*
8077 		 * Verify that the returned IRE does not have either
8078 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8079 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8080 		 */
8081 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8082 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8083 			goto icmp_err_ret;
8084 		}
8085 		/*
8086 		 * Increment the ire_ob_pkt_count field for ire if it is an
8087 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8088 		 * increment the same for the parent IRE, sire, if it is some
8089 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8090 		 */
8091 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8092 			UPDATE_OB_PKT_COUNT(ire);
8093 			ire->ire_last_used_time = lbolt;
8094 		}
8095 
8096 		if (sire != NULL) {
8097 			gw = sire->ire_gateway_addr;
8098 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8099 			    IRE_INTERFACE)) == 0);
8100 			UPDATE_OB_PKT_COUNT(sire);
8101 			sire->ire_last_used_time = lbolt;
8102 		}
8103 		/*
8104 		 * We have a route to reach the destination.  Find the
8105 		 * appropriate ill, then get a source address using
8106 		 * ipif_select_source().
8107 		 *
8108 		 * If we are here trying to create an IRE_CACHE for an offlink
8109 		 * destination and have an IRE_CACHE entry for VNI, then use
8110 		 * ire_stq instead since VNI's queue is a black hole.
8111 		 */
8112 		if ((ire->ire_type == IRE_CACHE) &&
8113 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8114 			dst_ill = ire->ire_stq->q_ptr;
8115 			ill_refhold(dst_ill);
8116 		} else {
8117 			ill_t *ill = ire->ire_ipif->ipif_ill;
8118 
8119 			if (IS_IPMP(ill)) {
8120 				dst_ill =
8121 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8122 			} else {
8123 				dst_ill = ill;
8124 				ill_refhold(dst_ill);
8125 			}
8126 		}
8127 
8128 		if (dst_ill == NULL) {
8129 			if (ip_debug > 2) {
8130 				pr_addr_dbg("ip_newroute: no dst "
8131 				    "ill for dst %s\n", AF_INET, &dst);
8132 			}
8133 			goto icmp_err_ret;
8134 		}
8135 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8136 
8137 		/*
8138 		 * Pick the best source address from dst_ill.
8139 		 *
8140 		 * 1) Try to pick the source address from the destination
8141 		 *    route. Clustering assumes that when we have multiple
8142 		 *    prefixes hosted on an interface, the prefix of the
8143 		 *    source address matches the prefix of the destination
8144 		 *    route. We do this only if the address is not
8145 		 *    DEPRECATED.
8146 		 *
8147 		 * 2) If the conn is in a different zone than the ire, we
8148 		 *    need to pick a source address from the right zone.
8149 		 */
8150 		ASSERT(src_ipif == NULL);
8151 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8152 			/*
8153 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8154 			 * Check that the ipif matching the requested source
8155 			 * address still exists.
8156 			 */
8157 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8158 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8159 		}
8160 
8161 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8162 
8163 		if (src_ipif == NULL &&
8164 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8165 			ire_marks |= IRE_MARK_USESRC_CHECK;
8166 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8167 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8168 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8169 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8170 			    ire->ire_zoneid != ALL_ZONES) ||
8171 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8172 				/*
8173 				 * If the destination is reachable via a
8174 				 * given gateway, the selected source address
8175 				 * should be in the same subnet as the gateway.
8176 				 * Otherwise, the destination is not reachable.
8177 				 *
8178 				 * If there are no interfaces on the same subnet
8179 				 * as the destination, ipif_select_source gives
8180 				 * first non-deprecated interface which might be
8181 				 * on a different subnet than the gateway.
8182 				 * This is not desirable. Hence pass the dst_ire
8183 				 * source address to ipif_select_source.
8184 				 * It is sure that the destination is reachable
8185 				 * with the dst_ire source address subnet.
8186 				 * So passing dst_ire source address to
8187 				 * ipif_select_source will make sure that the
8188 				 * selected source will be on the same subnet
8189 				 * as dst_ire source address.
8190 				 */
8191 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8192 
8193 				src_ipif = ipif_select_source(dst_ill, saddr,
8194 				    zoneid);
8195 				if (src_ipif == NULL) {
8196 					/*
8197 					 * In the case of multirouting, it may
8198 					 * happen that ipif_select_source fails
8199 					 * as DAD may disallow use of the
8200 					 * particular source interface.  Anyway,
8201 					 * we need to continue and attempt to
8202 					 * resolve other multirt routes.
8203 					 */
8204 					if ((sire != NULL) &&
8205 					    (sire->ire_flags & RTF_MULTIRT)) {
8206 						ire_refrele(ire);
8207 						ire = NULL;
8208 						multirt_resolve_next = B_TRUE;
8209 						multirt_res_failures++;
8210 						continue;
8211 					}
8212 
8213 					if (ip_debug > 2) {
8214 						pr_addr_dbg("ip_newroute: "
8215 						    "no src for dst %s ",
8216 						    AF_INET, &dst);
8217 						printf("on interface %s\n",
8218 						    dst_ill->ill_name);
8219 					}
8220 					goto icmp_err_ret;
8221 				}
8222 			} else {
8223 				src_ipif = ire->ire_ipif;
8224 				ASSERT(src_ipif != NULL);
8225 				/* hold src_ipif for uniformity */
8226 				ipif_refhold(src_ipif);
8227 			}
8228 		}
8229 
8230 		/*
8231 		 * Assign a source address while we have the conn.
8232 		 * We can't have ip_wput_ire pick a source address when the
8233 		 * packet returns from arp since we need to look at
8234 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8235 		 * going through arp.
8236 		 *
8237 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8238 		 *	  it uses ip6i to store this information.
8239 		 */
8240 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8241 			ipha->ipha_src = src_ipif->ipif_src_addr;
8242 
8243 		if (ip_debug > 3) {
8244 			/* ip2dbg */
8245 			pr_addr_dbg("ip_newroute: first hop %s\n",
8246 			    AF_INET, &gw);
8247 		}
8248 		ip2dbg(("\tire type %s (%d)\n",
8249 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8250 
8251 		/*
8252 		 * The TTL of multirouted packets is bounded by the
8253 		 * ip_multirt_ttl ndd variable.
8254 		 */
8255 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8256 			/* Force TTL of multirouted packets */
8257 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8258 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8259 				ip2dbg(("ip_newroute: forcing multirt TTL "
8260 				    "to %d (was %d), dst 0x%08x\n",
8261 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8262 				    ntohl(sire->ire_addr)));
8263 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8264 			}
8265 		}
8266 		/*
8267 		 * At this point in ip_newroute(), ire is either the
8268 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8269 		 * destination or an IRE_INTERFACE type that should be used
8270 		 * to resolve an on-subnet destination or an on-subnet
8271 		 * next-hop gateway.
8272 		 *
8273 		 * In the IRE_CACHE case, we have the following :
8274 		 *
8275 		 * 1) src_ipif - used for getting a source address.
8276 		 *
8277 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8278 		 *    means packets using this IRE_CACHE will go out on
8279 		 *    dst_ill.
8280 		 *
8281 		 * 3) The IRE sire will point to the prefix that is the
8282 		 *    longest  matching route for the destination. These
8283 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8284 		 *
8285 		 *    The newly created IRE_CACHE entry for the off-subnet
8286 		 *    destination is tied to both the prefix route and the
8287 		 *    interface route used to resolve the next-hop gateway
8288 		 *    via the ire_phandle and ire_ihandle fields,
8289 		 *    respectively.
8290 		 *
8291 		 * In the IRE_INTERFACE case, we have the following :
8292 		 *
8293 		 * 1) src_ipif - used for getting a source address.
8294 		 *
8295 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8296 		 *    means packets using the IRE_CACHE that we will build
8297 		 *    here will go out on dst_ill.
8298 		 *
8299 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8300 		 *    to be created will only be tied to the IRE_INTERFACE
8301 		 *    that was derived from the ire_ihandle field.
8302 		 *
8303 		 *    If sire is non-NULL, it means the destination is
8304 		 *    off-link and we will first create the IRE_CACHE for the
8305 		 *    gateway. Next time through ip_newroute, we will create
8306 		 *    the IRE_CACHE for the final destination as described
8307 		 *    above.
8308 		 *
8309 		 * In both cases, after the current resolution has been
8310 		 * completed (or possibly initialised, in the IRE_INTERFACE
8311 		 * case), the loop may be re-entered to attempt the resolution
8312 		 * of another RTF_MULTIRT route.
8313 		 *
8314 		 * When an IRE_CACHE entry for the off-subnet destination is
8315 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8316 		 * for further processing in emission loops.
8317 		 */
8318 		save_ire = ire;
8319 		switch (ire->ire_type) {
8320 		case IRE_CACHE: {
8321 			ire_t	*ipif_ire;
8322 
8323 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8324 			if (gw == 0)
8325 				gw = ire->ire_gateway_addr;
8326 			/*
8327 			 * We need 3 ire's to create a new cache ire for an
8328 			 * off-link destination from the cache ire of the
8329 			 * gateway.
8330 			 *
8331 			 *	1. The prefix ire 'sire' (Note that this does
8332 			 *	   not apply to the conn_nexthop_set case)
8333 			 *	2. The cache ire of the gateway 'ire'
8334 			 *	3. The interface ire 'ipif_ire'
8335 			 *
8336 			 * We have (1) and (2). We lookup (3) below.
8337 			 *
8338 			 * If there is no interface route to the gateway,
8339 			 * it is a race condition, where we found the cache
8340 			 * but the interface route has been deleted.
8341 			 */
8342 			if (ip_nexthop) {
8343 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8344 			} else {
8345 				ipif_ire =
8346 				    ire_ihandle_lookup_offlink(ire, sire);
8347 			}
8348 			if (ipif_ire == NULL) {
8349 				ip1dbg(("ip_newroute: "
8350 				    "ire_ihandle_lookup_offlink failed\n"));
8351 				goto icmp_err_ret;
8352 			}
8353 
8354 			/*
8355 			 * Check cached gateway IRE for any security
8356 			 * attributes; if found, associate the gateway
8357 			 * credentials group to the destination IRE.
8358 			 */
8359 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8360 				mutex_enter(&attrp->igsa_lock);
8361 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8362 					GCGRP_REFHOLD(gcgrp);
8363 				mutex_exit(&attrp->igsa_lock);
8364 			}
8365 
8366 			/*
8367 			 * XXX For the source of the resolver mp,
8368 			 * we are using the same DL_UNITDATA_REQ
8369 			 * (from save_ire->ire_nce->nce_res_mp)
8370 			 * though the save_ire is not pointing at the same ill.
8371 			 * This is incorrect. We need to send it up to the
8372 			 * resolver to get the right res_mp. For ethernets
8373 			 * this may be okay (ill_type == DL_ETHER).
8374 			 */
8375 
8376 			ire = ire_create(
8377 			    (uchar_t *)&dst,		/* dest address */
8378 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8379 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8380 			    (uchar_t *)&gw,		/* gateway address */
8381 			    &save_ire->ire_max_frag,
8382 			    save_ire->ire_nce,		/* src nce */
8383 			    dst_ill->ill_rq,		/* recv-from queue */
8384 			    dst_ill->ill_wq,		/* send-to queue */
8385 			    IRE_CACHE,			/* IRE type */
8386 			    src_ipif,
8387 			    (sire != NULL) ?
8388 			    sire->ire_mask : 0, 	/* Parent mask */
8389 			    (sire != NULL) ?
8390 			    sire->ire_phandle : 0,	/* Parent handle */
8391 			    ipif_ire->ire_ihandle,	/* Interface handle */
8392 			    (sire != NULL) ? (sire->ire_flags &
8393 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8394 			    (sire != NULL) ?
8395 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8396 			    NULL,
8397 			    gcgrp,
8398 			    ipst);
8399 
8400 			if (ire == NULL) {
8401 				if (gcgrp != NULL) {
8402 					GCGRP_REFRELE(gcgrp);
8403 					gcgrp = NULL;
8404 				}
8405 				ire_refrele(ipif_ire);
8406 				ire_refrele(save_ire);
8407 				break;
8408 			}
8409 
8410 			/* reference now held by IRE */
8411 			gcgrp = NULL;
8412 
8413 			ire->ire_marks |= ire_marks;
8414 
8415 			/*
8416 			 * Prevent sire and ipif_ire from getting deleted.
8417 			 * The newly created ire is tied to both of them via
8418 			 * the phandle and ihandle respectively.
8419 			 */
8420 			if (sire != NULL) {
8421 				IRB_REFHOLD(sire->ire_bucket);
8422 				/* Has it been removed already ? */
8423 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8424 					IRB_REFRELE(sire->ire_bucket);
8425 					ire_refrele(ipif_ire);
8426 					ire_refrele(save_ire);
8427 					break;
8428 				}
8429 			}
8430 
8431 			IRB_REFHOLD(ipif_ire->ire_bucket);
8432 			/* Has it been removed already ? */
8433 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8434 				IRB_REFRELE(ipif_ire->ire_bucket);
8435 				if (sire != NULL)
8436 					IRB_REFRELE(sire->ire_bucket);
8437 				ire_refrele(ipif_ire);
8438 				ire_refrele(save_ire);
8439 				break;
8440 			}
8441 
8442 			xmit_mp = first_mp;
8443 			/*
8444 			 * In the case of multirouting, a copy
8445 			 * of the packet is done before its sending.
8446 			 * The copy is used to attempt another
8447 			 * route resolution, in a next loop.
8448 			 */
8449 			if (ire->ire_flags & RTF_MULTIRT) {
8450 				copy_mp = copymsg(first_mp);
8451 				if (copy_mp != NULL) {
8452 					xmit_mp = copy_mp;
8453 					MULTIRT_DEBUG_TAG(first_mp);
8454 				}
8455 			}
8456 
8457 			ire_add_then_send(q, ire, xmit_mp);
8458 			ire_refrele(save_ire);
8459 
8460 			/* Assert that sire is not deleted yet. */
8461 			if (sire != NULL) {
8462 				ASSERT(sire->ire_ptpn != NULL);
8463 				IRB_REFRELE(sire->ire_bucket);
8464 			}
8465 
8466 			/* Assert that ipif_ire is not deleted yet. */
8467 			ASSERT(ipif_ire->ire_ptpn != NULL);
8468 			IRB_REFRELE(ipif_ire->ire_bucket);
8469 			ire_refrele(ipif_ire);
8470 
8471 			/*
8472 			 * If copy_mp is not NULL, multirouting was
8473 			 * requested. We loop to initiate a next
8474 			 * route resolution attempt, starting from sire.
8475 			 */
8476 			if (copy_mp != NULL) {
8477 				/*
8478 				 * Search for the next unresolved
8479 				 * multirt route.
8480 				 */
8481 				copy_mp = NULL;
8482 				ipif_ire = NULL;
8483 				ire = NULL;
8484 				multirt_resolve_next = B_TRUE;
8485 				continue;
8486 			}
8487 			if (sire != NULL)
8488 				ire_refrele(sire);
8489 			ipif_refrele(src_ipif);
8490 			ill_refrele(dst_ill);
8491 			return;
8492 		}
8493 		case IRE_IF_NORESOLVER: {
8494 			if (dst_ill->ill_resolver_mp == NULL) {
8495 				ip1dbg(("ip_newroute: dst_ill %p "
8496 				    "for IRE_IF_NORESOLVER ire %p has "
8497 				    "no ill_resolver_mp\n",
8498 				    (void *)dst_ill, (void *)ire));
8499 				break;
8500 			}
8501 
8502 			/*
8503 			 * TSol note: We are creating the ire cache for the
8504 			 * destination 'dst'. If 'dst' is offlink, going
8505 			 * through the first hop 'gw', the security attributes
8506 			 * of 'dst' must be set to point to the gateway
8507 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8508 			 * is possible that 'dst' is a potential gateway that is
8509 			 * referenced by some route that has some security
8510 			 * attributes. Thus in the former case, we need to do a
8511 			 * gcgrp_lookup of 'gw' while in the latter case we
8512 			 * need to do gcgrp_lookup of 'dst' itself.
8513 			 */
8514 			ga.ga_af = AF_INET;
8515 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8516 			    &ga.ga_addr);
8517 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8518 
8519 			ire = ire_create(
8520 			    (uchar_t *)&dst,		/* dest address */
8521 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8522 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8523 			    (uchar_t *)&gw,		/* gateway address */
8524 			    &save_ire->ire_max_frag,
8525 			    NULL,			/* no src nce */
8526 			    dst_ill->ill_rq,		/* recv-from queue */
8527 			    dst_ill->ill_wq,		/* send-to queue */
8528 			    IRE_CACHE,
8529 			    src_ipif,
8530 			    save_ire->ire_mask,		/* Parent mask */
8531 			    (sire != NULL) ?		/* Parent handle */
8532 			    sire->ire_phandle : 0,
8533 			    save_ire->ire_ihandle,	/* Interface handle */
8534 			    (sire != NULL) ? sire->ire_flags &
8535 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8536 			    &(save_ire->ire_uinfo),
8537 			    NULL,
8538 			    gcgrp,
8539 			    ipst);
8540 
8541 			if (ire == NULL) {
8542 				if (gcgrp != NULL) {
8543 					GCGRP_REFRELE(gcgrp);
8544 					gcgrp = NULL;
8545 				}
8546 				ire_refrele(save_ire);
8547 				break;
8548 			}
8549 
8550 			/* reference now held by IRE */
8551 			gcgrp = NULL;
8552 
8553 			ire->ire_marks |= ire_marks;
8554 
8555 			/* Prevent save_ire from getting deleted */
8556 			IRB_REFHOLD(save_ire->ire_bucket);
8557 			/* Has it been removed already ? */
8558 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8559 				IRB_REFRELE(save_ire->ire_bucket);
8560 				ire_refrele(save_ire);
8561 				break;
8562 			}
8563 
8564 			/*
8565 			 * In the case of multirouting, a copy
8566 			 * of the packet is made before it is sent.
8567 			 * The copy is used in the next
8568 			 * loop to attempt another resolution.
8569 			 */
8570 			xmit_mp = first_mp;
8571 			if ((sire != NULL) &&
8572 			    (sire->ire_flags & RTF_MULTIRT)) {
8573 				copy_mp = copymsg(first_mp);
8574 				if (copy_mp != NULL) {
8575 					xmit_mp = copy_mp;
8576 					MULTIRT_DEBUG_TAG(first_mp);
8577 				}
8578 			}
8579 			ire_add_then_send(q, ire, xmit_mp);
8580 
8581 			/* Assert that it is not deleted yet. */
8582 			ASSERT(save_ire->ire_ptpn != NULL);
8583 			IRB_REFRELE(save_ire->ire_bucket);
8584 			ire_refrele(save_ire);
8585 
8586 			if (copy_mp != NULL) {
8587 				/*
8588 				 * If we found a (no)resolver, we ignore any
8589 				 * trailing top priority IRE_CACHE in further
8590 				 * loops. This ensures that we do not omit any
8591 				 * (no)resolver.
8592 				 * This IRE_CACHE, if any, will be processed
8593 				 * by another thread entering ip_newroute().
8594 				 * IRE_CACHE entries, if any, will be processed
8595 				 * by another thread entering ip_newroute(),
8596 				 * (upon resolver response, for instance).
8597 				 * This aims to force parallel multirt
8598 				 * resolutions as soon as a packet must be sent.
8599 				 * In the best case, after the tx of only one
8600 				 * packet, all reachable routes are resolved.
8601 				 * Otherwise, the resolution of all RTF_MULTIRT
8602 				 * routes would require several emissions.
8603 				 */
8604 				multirt_flags &= ~MULTIRT_CACHEGW;
8605 
8606 				/*
8607 				 * Search for the next unresolved multirt
8608 				 * route.
8609 				 */
8610 				copy_mp = NULL;
8611 				save_ire = NULL;
8612 				ire = NULL;
8613 				multirt_resolve_next = B_TRUE;
8614 				continue;
8615 			}
8616 
8617 			/*
8618 			 * Don't need sire anymore
8619 			 */
8620 			if (sire != NULL)
8621 				ire_refrele(sire);
8622 
8623 			ipif_refrele(src_ipif);
8624 			ill_refrele(dst_ill);
8625 			return;
8626 		}
8627 		case IRE_IF_RESOLVER:
8628 			/*
8629 			 * We can't build an IRE_CACHE yet, but at least we
8630 			 * found a resolver that can help.
8631 			 */
8632 			res_mp = dst_ill->ill_resolver_mp;
8633 			if (!OK_RESOLVER_MP(res_mp))
8634 				break;
8635 
8636 			/*
8637 			 * To be at this point in the code with a non-zero gw
8638 			 * means that dst is reachable through a gateway that
8639 			 * we have never resolved.  By changing dst to the gw
8640 			 * addr we resolve the gateway first.
8641 			 * When ire_add_then_send() tries to put the IP dg
8642 			 * to dst, it will reenter ip_newroute() at which
8643 			 * time we will find the IRE_CACHE for the gw and
8644 			 * create another IRE_CACHE in case IRE_CACHE above.
8645 			 */
8646 			if (gw != INADDR_ANY) {
8647 				/*
8648 				 * The source ipif that was determined above was
8649 				 * relative to the destination address, not the
8650 				 * gateway's. If src_ipif was not taken out of
8651 				 * the IRE_IF_RESOLVER entry, we'll need to call
8652 				 * ipif_select_source() again.
8653 				 */
8654 				if (src_ipif != ire->ire_ipif) {
8655 					ipif_refrele(src_ipif);
8656 					src_ipif = ipif_select_source(dst_ill,
8657 					    gw, zoneid);
8658 					/*
8659 					 * In the case of multirouting, it may
8660 					 * happen that ipif_select_source fails
8661 					 * as DAD may disallow use of the
8662 					 * particular source interface.  Anyway,
8663 					 * we need to continue and attempt to
8664 					 * resolve other multirt routes.
8665 					 */
8666 					if (src_ipif == NULL) {
8667 						if (sire != NULL &&
8668 						    (sire->ire_flags &
8669 						    RTF_MULTIRT)) {
8670 							ire_refrele(ire);
8671 							ire = NULL;
8672 							multirt_resolve_next =
8673 							    B_TRUE;
8674 							multirt_res_failures++;
8675 							continue;
8676 						}
8677 						if (ip_debug > 2) {
8678 							pr_addr_dbg(
8679 							    "ip_newroute: no "
8680 							    "src for gw %s ",
8681 							    AF_INET, &gw);
8682 							printf("on "
8683 							    "interface %s\n",
8684 							    dst_ill->ill_name);
8685 						}
8686 						goto icmp_err_ret;
8687 					}
8688 				}
8689 				save_dst = dst;
8690 				dst = gw;
8691 				gw = INADDR_ANY;
8692 			}
8693 
8694 			/*
8695 			 * We obtain a partial IRE_CACHE which we will pass
8696 			 * along with the resolver query.  When the response
8697 			 * comes back it will be there ready for us to add.
8698 			 * The ire_max_frag is atomically set under the
8699 			 * irebucket lock in ire_add_v[46].
8700 			 */
8701 
8702 			ire = ire_create_mp(
8703 			    (uchar_t *)&dst,		/* dest address */
8704 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8705 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8706 			    (uchar_t *)&gw,		/* gateway address */
8707 			    NULL,			/* ire_max_frag */
8708 			    NULL,			/* no src nce */
8709 			    dst_ill->ill_rq,		/* recv-from queue */
8710 			    dst_ill->ill_wq,		/* send-to queue */
8711 			    IRE_CACHE,
8712 			    src_ipif,			/* Interface ipif */
8713 			    save_ire->ire_mask,		/* Parent mask */
8714 			    0,
8715 			    save_ire->ire_ihandle,	/* Interface handle */
8716 			    0,				/* flags if any */
8717 			    &(save_ire->ire_uinfo),
8718 			    NULL,
8719 			    NULL,
8720 			    ipst);
8721 
8722 			if (ire == NULL) {
8723 				ire_refrele(save_ire);
8724 				break;
8725 			}
8726 
8727 			if ((sire != NULL) &&
8728 			    (sire->ire_flags & RTF_MULTIRT)) {
8729 				copy_mp = copymsg(first_mp);
8730 				if (copy_mp != NULL)
8731 					MULTIRT_DEBUG_TAG(copy_mp);
8732 			}
8733 
8734 			ire->ire_marks |= ire_marks;
8735 
8736 			/*
8737 			 * Construct message chain for the resolver
8738 			 * of the form:
8739 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8740 			 * Packet could contain a IPSEC_OUT mp.
8741 			 *
8742 			 * NOTE : ire will be added later when the response
8743 			 * comes back from ARP. If the response does not
8744 			 * come back, ARP frees the packet. For this reason,
8745 			 * we can't REFHOLD the bucket of save_ire to prevent
8746 			 * deletions. We may not be able to REFRELE the bucket
8747 			 * if the response never comes back. Thus, before
8748 			 * adding the ire, ire_add_v4 will make sure that the
8749 			 * interface route does not get deleted. This is the
8750 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8751 			 * where we can always prevent deletions because of
8752 			 * the synchronous nature of adding IRES i.e
8753 			 * ire_add_then_send is called after creating the IRE.
8754 			 */
8755 			ASSERT(ire->ire_mp != NULL);
8756 			ire->ire_mp->b_cont = first_mp;
8757 			/* Have saved_mp handy, for cleanup if canput fails */
8758 			saved_mp = mp;
8759 			mp = copyb(res_mp);
8760 			if (mp == NULL) {
8761 				/* Prepare for cleanup */
8762 				mp = saved_mp; /* pkt */
8763 				ire_delete(ire); /* ire_mp */
8764 				ire = NULL;
8765 				ire_refrele(save_ire);
8766 				if (copy_mp != NULL) {
8767 					MULTIRT_DEBUG_UNTAG(copy_mp);
8768 					freemsg(copy_mp);
8769 					copy_mp = NULL;
8770 				}
8771 				break;
8772 			}
8773 			linkb(mp, ire->ire_mp);
8774 
8775 			/*
8776 			 * Fill in the source and dest addrs for the resolver.
8777 			 * NOTE: this depends on memory layouts imposed by
8778 			 * ill_init().
8779 			 */
8780 			areq = (areq_t *)mp->b_rptr;
8781 			addrp = (ipaddr_t *)((char *)areq +
8782 			    areq->areq_sender_addr_offset);
8783 			*addrp = save_ire->ire_src_addr;
8784 
8785 			ire_refrele(save_ire);
8786 			addrp = (ipaddr_t *)((char *)areq +
8787 			    areq->areq_target_addr_offset);
8788 			*addrp = dst;
8789 			/* Up to the resolver. */
8790 			if (canputnext(dst_ill->ill_rq) &&
8791 			    !(dst_ill->ill_arp_closing)) {
8792 				putnext(dst_ill->ill_rq, mp);
8793 				ire = NULL;
8794 				if (copy_mp != NULL) {
8795 					/*
8796 					 * If we found a resolver, we ignore
8797 					 * any trailing top priority IRE_CACHE
8798 					 * in the further loops. This ensures
8799 					 * that we do not omit any resolver.
8800 					 * IRE_CACHE entries, if any, will be
8801 					 * processed next time we enter
8802 					 * ip_newroute().
8803 					 */
8804 					multirt_flags &= ~MULTIRT_CACHEGW;
8805 					/*
8806 					 * Search for the next unresolved
8807 					 * multirt route.
8808 					 */
8809 					first_mp = copy_mp;
8810 					copy_mp = NULL;
8811 					/* Prepare the next resolution loop. */
8812 					mp = first_mp;
8813 					EXTRACT_PKT_MP(mp, first_mp,
8814 					    mctl_present);
8815 					if (mctl_present)
8816 						io = (ipsec_out_t *)
8817 						    first_mp->b_rptr;
8818 					ipha = (ipha_t *)mp->b_rptr;
8819 
8820 					ASSERT(sire != NULL);
8821 
8822 					dst = save_dst;
8823 					multirt_resolve_next = B_TRUE;
8824 					continue;
8825 				}
8826 
8827 				if (sire != NULL)
8828 					ire_refrele(sire);
8829 
8830 				/*
8831 				 * The response will come back in ip_wput
8832 				 * with db_type IRE_DB_TYPE.
8833 				 */
8834 				ipif_refrele(src_ipif);
8835 				ill_refrele(dst_ill);
8836 				return;
8837 			} else {
8838 				/* Prepare for cleanup */
8839 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8840 				    mp);
8841 				mp->b_cont = NULL;
8842 				freeb(mp); /* areq */
8843 				/*
8844 				 * this is an ire that is not added to the
8845 				 * cache. ire_freemblk will handle the release
8846 				 * of any resources associated with the ire.
8847 				 */
8848 				ire_delete(ire); /* ire_mp */
8849 				mp = saved_mp; /* pkt */
8850 				ire = NULL;
8851 				if (copy_mp != NULL) {
8852 					MULTIRT_DEBUG_UNTAG(copy_mp);
8853 					freemsg(copy_mp);
8854 					copy_mp = NULL;
8855 				}
8856 				break;
8857 			}
8858 		default:
8859 			break;
8860 		}
8861 	} while (multirt_resolve_next);
8862 
8863 	ip1dbg(("ip_newroute: dropped\n"));
8864 	/* Did this packet originate externally? */
8865 	if (mp->b_prev) {
8866 		mp->b_next = NULL;
8867 		mp->b_prev = NULL;
8868 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8869 	} else {
8870 		if (dst_ill != NULL) {
8871 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8872 		} else {
8873 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8874 		}
8875 	}
8876 	ASSERT(copy_mp == NULL);
8877 	MULTIRT_DEBUG_UNTAG(first_mp);
8878 	freemsg(first_mp);
8879 	if (ire != NULL)
8880 		ire_refrele(ire);
8881 	if (sire != NULL)
8882 		ire_refrele(sire);
8883 	if (src_ipif != NULL)
8884 		ipif_refrele(src_ipif);
8885 	if (dst_ill != NULL)
8886 		ill_refrele(dst_ill);
8887 	return;
8888 
8889 icmp_err_ret:
8890 	ip1dbg(("ip_newroute: no route\n"));
8891 	if (src_ipif != NULL)
8892 		ipif_refrele(src_ipif);
8893 	if (dst_ill != NULL)
8894 		ill_refrele(dst_ill);
8895 	if (sire != NULL)
8896 		ire_refrele(sire);
8897 	/* Did this packet originate externally? */
8898 	if (mp->b_prev) {
8899 		mp->b_next = NULL;
8900 		mp->b_prev = NULL;
8901 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8902 		q = WR(q);
8903 	} else {
8904 		/*
8905 		 * There is no outgoing ill, so just increment the
8906 		 * system MIB.
8907 		 */
8908 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8909 		/*
8910 		 * Since ip_wput() isn't close to finished, we fill
8911 		 * in enough of the header for credible error reporting.
8912 		 */
8913 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8914 			/* Failed */
8915 			MULTIRT_DEBUG_UNTAG(first_mp);
8916 			freemsg(first_mp);
8917 			if (ire != NULL)
8918 				ire_refrele(ire);
8919 			return;
8920 		}
8921 	}
8922 
8923 	/*
8924 	 * At this point we will have ire only if RTF_BLACKHOLE
8925 	 * or RTF_REJECT flags are set on the IRE. It will not
8926 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8927 	 */
8928 	if (ire != NULL) {
8929 		if (ire->ire_flags & RTF_BLACKHOLE) {
8930 			ire_refrele(ire);
8931 			MULTIRT_DEBUG_UNTAG(first_mp);
8932 			freemsg(first_mp);
8933 			return;
8934 		}
8935 		ire_refrele(ire);
8936 	}
8937 	if (ip_source_routed(ipha, ipst)) {
8938 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8939 		    zoneid, ipst);
8940 		return;
8941 	}
8942 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8943 }
8944 
8945 ip_opt_info_t zero_info;
8946 
8947 /*
8948  * IPv4 -
8949  * ip_newroute_ipif is called by ip_wput_multicast and
8950  * ip_rput_forward_multicast whenever we need to send
8951  * out a packet to a destination address for which we do not have specific
8952  * routing information. It is used when the packet will be sent out
8953  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8954  * socket option is set or icmp error message wants to go out on a particular
8955  * interface for a unicast packet.
8956  *
8957  * In most cases, the destination address is resolved thanks to the ipif
8958  * intrinsic resolver. However, there are some cases where the call to
8959  * ip_newroute_ipif must take into account the potential presence of
8960  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8961  * that uses the interface. This is specified through flags,
8962  * which can be a combination of:
8963  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8964  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8965  *   and flags. Additionally, the packet source address has to be set to
8966  *   the specified address. The caller is thus expected to set this flag
8967  *   if the packet has no specific source address yet.
8968  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8969  *   flag, the resulting ire will inherit the flag. All unresolved routes
8970  *   to the destination must be explored in the same call to
8971  *   ip_newroute_ipif().
8972  */
8973 static void
8974 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8975     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8976 {
8977 	areq_t	*areq;
8978 	ire_t	*ire = NULL;
8979 	mblk_t	*res_mp;
8980 	ipaddr_t *addrp;
8981 	mblk_t *first_mp;
8982 	ire_t	*save_ire = NULL;
8983 	ipif_t	*src_ipif = NULL;
8984 	ushort_t ire_marks = 0;
8985 	ill_t	*dst_ill = NULL;
8986 	ipha_t *ipha;
8987 	mblk_t	*saved_mp;
8988 	ire_t   *fire = NULL;
8989 	mblk_t  *copy_mp = NULL;
8990 	boolean_t multirt_resolve_next;
8991 	boolean_t unspec_src;
8992 	ipaddr_t ipha_dst;
8993 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8994 
8995 	/*
8996 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8997 	 * here for uniformity
8998 	 */
8999 	ipif_refhold(ipif);
9000 
9001 	/*
9002 	 * This loop is run only once in most cases.
9003 	 * We loop to resolve further routes only when the destination
9004 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9005 	 */
9006 	do {
9007 		if (dst_ill != NULL) {
9008 			ill_refrele(dst_ill);
9009 			dst_ill = NULL;
9010 		}
9011 		if (src_ipif != NULL) {
9012 			ipif_refrele(src_ipif);
9013 			src_ipif = NULL;
9014 		}
9015 		multirt_resolve_next = B_FALSE;
9016 
9017 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9018 		    ipif->ipif_ill->ill_name));
9019 
9020 		first_mp = mp;
9021 		if (DB_TYPE(mp) == M_CTL)
9022 			mp = mp->b_cont;
9023 		ipha = (ipha_t *)mp->b_rptr;
9024 
9025 		/*
9026 		 * Save the packet destination address, we may need it after
9027 		 * the packet has been consumed.
9028 		 */
9029 		ipha_dst = ipha->ipha_dst;
9030 
9031 		/*
9032 		 * If the interface is a pt-pt interface we look for an
9033 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9034 		 * local_address and the pt-pt destination address. Otherwise
9035 		 * we just match the local address.
9036 		 * NOTE: dst could be different than ipha->ipha_dst in case
9037 		 * of sending igmp multicast packets over a point-to-point
9038 		 * connection.
9039 		 * Thus we must be careful enough to check ipha_dst to be a
9040 		 * multicast address, otherwise it will take xmit_if path for
9041 		 * multicast packets resulting into kernel stack overflow by
9042 		 * repeated calls to ip_newroute_ipif from ire_send().
9043 		 */
9044 		if (CLASSD(ipha_dst) &&
9045 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9046 			goto err_ret;
9047 		}
9048 
9049 		/*
9050 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9051 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9052 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9053 		 * propagate its flags to the new ire.
9054 		 */
9055 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9056 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9057 			ip2dbg(("ip_newroute_ipif: "
9058 			    "ipif_lookup_multi_ire("
9059 			    "ipif %p, dst %08x) = fire %p\n",
9060 			    (void *)ipif, ntohl(dst), (void *)fire));
9061 		}
9062 
9063 		/*
9064 		 * Note: While we pick a dst_ill we are really only
9065 		 * interested in the ill for load spreading. The source
9066 		 * ipif is determined by source address selection below.
9067 		 */
9068 		if (IS_IPMP(ipif->ipif_ill)) {
9069 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9070 
9071 			if (CLASSD(ipha_dst))
9072 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9073 			else
9074 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9075 		} else {
9076 			dst_ill = ipif->ipif_ill;
9077 			ill_refhold(dst_ill);
9078 		}
9079 
9080 		if (dst_ill == NULL) {
9081 			if (ip_debug > 2) {
9082 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9083 				    "for dst %s\n", AF_INET, &dst);
9084 			}
9085 			goto err_ret;
9086 		}
9087 
9088 		/*
9089 		 * Pick a source address preferring non-deprecated ones.
9090 		 * Unlike ip_newroute, we don't do any source address
9091 		 * selection here since for multicast it really does not help
9092 		 * in inbound load spreading as in the unicast case.
9093 		 */
9094 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9095 		    (fire->ire_flags & RTF_SETSRC)) {
9096 			/*
9097 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9098 			 * on that interface. This ire has RTF_SETSRC flag, so
9099 			 * the source address of the packet must be changed.
9100 			 * Check that the ipif matching the requested source
9101 			 * address still exists.
9102 			 */
9103 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9104 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9105 		}
9106 
9107 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9108 
9109 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9110 		    (IS_IPMP(ipif->ipif_ill) ||
9111 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9112 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9113 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9114 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9115 		    (src_ipif == NULL) &&
9116 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9117 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9118 			if (src_ipif == NULL) {
9119 				if (ip_debug > 2) {
9120 					/* ip1dbg */
9121 					pr_addr_dbg("ip_newroute_ipif: "
9122 					    "no src for dst %s",
9123 					    AF_INET, &dst);
9124 				}
9125 				ip1dbg((" on interface %s\n",
9126 				    dst_ill->ill_name));
9127 				goto err_ret;
9128 			}
9129 			ipif_refrele(ipif);
9130 			ipif = src_ipif;
9131 			ipif_refhold(ipif);
9132 		}
9133 		if (src_ipif == NULL) {
9134 			src_ipif = ipif;
9135 			ipif_refhold(src_ipif);
9136 		}
9137 
9138 		/*
9139 		 * Assign a source address while we have the conn.
9140 		 * We can't have ip_wput_ire pick a source address when the
9141 		 * packet returns from arp since conn_unspec_src might be set
9142 		 * and we lose the conn when going through arp.
9143 		 */
9144 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9145 			ipha->ipha_src = src_ipif->ipif_src_addr;
9146 
9147 		/*
9148 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9149 		 * that the outgoing interface does not have an interface ire.
9150 		 */
9151 		if (CLASSD(ipha_dst) && (connp == NULL ||
9152 		    connp->conn_outgoing_ill == NULL) &&
9153 		    infop->ip_opt_ill_index == 0) {
9154 			/* ipif_to_ire returns an held ire */
9155 			ire = ipif_to_ire(ipif);
9156 			if (ire == NULL)
9157 				goto err_ret;
9158 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9159 				goto err_ret;
9160 			save_ire = ire;
9161 
9162 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9163 			    "flags %04x\n",
9164 			    (void *)ire, (void *)ipif, flags));
9165 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9166 			    (fire->ire_flags & RTF_MULTIRT)) {
9167 				/*
9168 				 * As requested by flags, an IRE_OFFSUBNET was
9169 				 * looked up on that interface. This ire has
9170 				 * RTF_MULTIRT flag, so the resolution loop will
9171 				 * be re-entered to resolve additional routes on
9172 				 * other interfaces. For that purpose, a copy of
9173 				 * the packet is performed at this point.
9174 				 */
9175 				fire->ire_last_used_time = lbolt;
9176 				copy_mp = copymsg(first_mp);
9177 				if (copy_mp) {
9178 					MULTIRT_DEBUG_TAG(copy_mp);
9179 				}
9180 			}
9181 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9182 			    (fire->ire_flags & RTF_SETSRC)) {
9183 				/*
9184 				 * As requested by flags, an IRE_OFFSUBET was
9185 				 * looked up on that interface. This ire has
9186 				 * RTF_SETSRC flag, so the source address of the
9187 				 * packet must be changed.
9188 				 */
9189 				ipha->ipha_src = fire->ire_src_addr;
9190 			}
9191 		} else {
9192 			/*
9193 			 * The only ways we can come here are:
9194 			 * 1) IP_BOUND_IF socket option is set
9195 			 * 2) SO_DONTROUTE socket option is set
9196 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9197 			 * In all cases, the new ire will not be added
9198 			 * into cache table.
9199 			 */
9200 			ASSERT(connp == NULL || connp->conn_dontroute ||
9201 			    connp->conn_outgoing_ill != NULL ||
9202 			    infop->ip_opt_ill_index != 0);
9203 			ire_marks |= IRE_MARK_NOADD;
9204 		}
9205 
9206 		switch (ipif->ipif_net_type) {
9207 		case IRE_IF_NORESOLVER: {
9208 			/* We have what we need to build an IRE_CACHE. */
9209 
9210 			if (dst_ill->ill_resolver_mp == NULL) {
9211 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9212 				    "for IRE_IF_NORESOLVER ire %p has "
9213 				    "no ill_resolver_mp\n",
9214 				    (void *)dst_ill, (void *)ire));
9215 				break;
9216 			}
9217 
9218 			/*
9219 			 * The new ire inherits the IRE_OFFSUBNET flags
9220 			 * and source address, if this was requested.
9221 			 */
9222 			ire = ire_create(
9223 			    (uchar_t *)&dst,		/* dest address */
9224 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9225 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9226 			    NULL,			/* gateway address */
9227 			    &ipif->ipif_mtu,
9228 			    NULL,			/* no src nce */
9229 			    dst_ill->ill_rq,		/* recv-from queue */
9230 			    dst_ill->ill_wq,		/* send-to queue */
9231 			    IRE_CACHE,
9232 			    src_ipif,
9233 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9234 			    (fire != NULL) ?		/* Parent handle */
9235 			    fire->ire_phandle : 0,
9236 			    (save_ire != NULL) ?	/* Interface handle */
9237 			    save_ire->ire_ihandle : 0,
9238 			    (fire != NULL) ?
9239 			    (fire->ire_flags &
9240 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9241 			    (save_ire == NULL ? &ire_uinfo_null :
9242 			    &save_ire->ire_uinfo),
9243 			    NULL,
9244 			    NULL,
9245 			    ipst);
9246 
9247 			if (ire == NULL) {
9248 				if (save_ire != NULL)
9249 					ire_refrele(save_ire);
9250 				break;
9251 			}
9252 
9253 			ire->ire_marks |= ire_marks;
9254 
9255 			/*
9256 			 * If IRE_MARK_NOADD is set then we need to convert
9257 			 * the max_fragp to a useable value now. This is
9258 			 * normally done in ire_add_v[46]. We also need to
9259 			 * associate the ire with an nce (normally would be
9260 			 * done in ip_wput_nondata()).
9261 			 *
9262 			 * Note that IRE_MARK_NOADD packets created here
9263 			 * do not have a non-null ire_mp pointer. The null
9264 			 * value of ire_bucket indicates that they were
9265 			 * never added.
9266 			 */
9267 			if (ire->ire_marks & IRE_MARK_NOADD) {
9268 				uint_t  max_frag;
9269 
9270 				max_frag = *ire->ire_max_fragp;
9271 				ire->ire_max_fragp = NULL;
9272 				ire->ire_max_frag = max_frag;
9273 
9274 				if ((ire->ire_nce = ndp_lookup_v4(
9275 				    ire_to_ill(ire),
9276 				    (ire->ire_gateway_addr != INADDR_ANY ?
9277 				    &ire->ire_gateway_addr : &ire->ire_addr),
9278 				    B_FALSE)) == NULL) {
9279 					if (save_ire != NULL)
9280 						ire_refrele(save_ire);
9281 					break;
9282 				}
9283 				ASSERT(ire->ire_nce->nce_state ==
9284 				    ND_REACHABLE);
9285 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9286 			}
9287 
9288 			/* Prevent save_ire from getting deleted */
9289 			if (save_ire != NULL) {
9290 				IRB_REFHOLD(save_ire->ire_bucket);
9291 				/* Has it been removed already ? */
9292 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9293 					IRB_REFRELE(save_ire->ire_bucket);
9294 					ire_refrele(save_ire);
9295 					break;
9296 				}
9297 			}
9298 
9299 			ire_add_then_send(q, ire, first_mp);
9300 
9301 			/* Assert that save_ire is not deleted yet. */
9302 			if (save_ire != NULL) {
9303 				ASSERT(save_ire->ire_ptpn != NULL);
9304 				IRB_REFRELE(save_ire->ire_bucket);
9305 				ire_refrele(save_ire);
9306 				save_ire = NULL;
9307 			}
9308 			if (fire != NULL) {
9309 				ire_refrele(fire);
9310 				fire = NULL;
9311 			}
9312 
9313 			/*
9314 			 * the resolution loop is re-entered if this
9315 			 * was requested through flags and if we
9316 			 * actually are in a multirouting case.
9317 			 */
9318 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9319 				boolean_t need_resolve =
9320 				    ire_multirt_need_resolve(ipha_dst,
9321 				    msg_getlabel(copy_mp), ipst);
9322 				if (!need_resolve) {
9323 					MULTIRT_DEBUG_UNTAG(copy_mp);
9324 					freemsg(copy_mp);
9325 					copy_mp = NULL;
9326 				} else {
9327 					/*
9328 					 * ipif_lookup_group() calls
9329 					 * ire_lookup_multi() that uses
9330 					 * ire_ftable_lookup() to find
9331 					 * an IRE_INTERFACE for the group.
9332 					 * In the multirt case,
9333 					 * ire_lookup_multi() then invokes
9334 					 * ire_multirt_lookup() to find
9335 					 * the next resolvable ire.
9336 					 * As a result, we obtain an new
9337 					 * interface, derived from the
9338 					 * next ire.
9339 					 */
9340 					ipif_refrele(ipif);
9341 					ipif = ipif_lookup_group(ipha_dst,
9342 					    zoneid, ipst);
9343 					ip2dbg(("ip_newroute_ipif: "
9344 					    "multirt dst %08x, ipif %p\n",
9345 					    htonl(dst), (void *)ipif));
9346 					if (ipif != NULL) {
9347 						mp = copy_mp;
9348 						copy_mp = NULL;
9349 						multirt_resolve_next = B_TRUE;
9350 						continue;
9351 					} else {
9352 						freemsg(copy_mp);
9353 					}
9354 				}
9355 			}
9356 			if (ipif != NULL)
9357 				ipif_refrele(ipif);
9358 			ill_refrele(dst_ill);
9359 			ipif_refrele(src_ipif);
9360 			return;
9361 		}
9362 		case IRE_IF_RESOLVER:
9363 			/*
9364 			 * We can't build an IRE_CACHE yet, but at least
9365 			 * we found a resolver that can help.
9366 			 */
9367 			res_mp = dst_ill->ill_resolver_mp;
9368 			if (!OK_RESOLVER_MP(res_mp))
9369 				break;
9370 
9371 			/*
9372 			 * We obtain a partial IRE_CACHE which we will pass
9373 			 * along with the resolver query.  When the response
9374 			 * comes back it will be there ready for us to add.
9375 			 * The new ire inherits the IRE_OFFSUBNET flags
9376 			 * and source address, if this was requested.
9377 			 * The ire_max_frag is atomically set under the
9378 			 * irebucket lock in ire_add_v[46]. Only in the
9379 			 * case of IRE_MARK_NOADD, we set it here itself.
9380 			 */
9381 			ire = ire_create_mp(
9382 			    (uchar_t *)&dst,		/* dest address */
9383 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9384 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9385 			    NULL,			/* gateway address */
9386 			    (ire_marks & IRE_MARK_NOADD) ?
9387 			    ipif->ipif_mtu : 0,		/* max_frag */
9388 			    NULL,			/* no src nce */
9389 			    dst_ill->ill_rq,		/* recv-from queue */
9390 			    dst_ill->ill_wq,		/* send-to queue */
9391 			    IRE_CACHE,
9392 			    src_ipif,
9393 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9394 			    (fire != NULL) ?		/* Parent handle */
9395 			    fire->ire_phandle : 0,
9396 			    (save_ire != NULL) ?	/* Interface handle */
9397 			    save_ire->ire_ihandle : 0,
9398 			    (fire != NULL) ?		/* flags if any */
9399 			    (fire->ire_flags &
9400 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9401 			    (save_ire == NULL ? &ire_uinfo_null :
9402 			    &save_ire->ire_uinfo),
9403 			    NULL,
9404 			    NULL,
9405 			    ipst);
9406 
9407 			if (save_ire != NULL) {
9408 				ire_refrele(save_ire);
9409 				save_ire = NULL;
9410 			}
9411 			if (ire == NULL)
9412 				break;
9413 
9414 			ire->ire_marks |= ire_marks;
9415 			/*
9416 			 * Construct message chain for the resolver of the
9417 			 * form:
9418 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9419 			 *
9420 			 * NOTE : ire will be added later when the response
9421 			 * comes back from ARP. If the response does not
9422 			 * come back, ARP frees the packet. For this reason,
9423 			 * we can't REFHOLD the bucket of save_ire to prevent
9424 			 * deletions. We may not be able to REFRELE the
9425 			 * bucket if the response never comes back.
9426 			 * Thus, before adding the ire, ire_add_v4 will make
9427 			 * sure that the interface route does not get deleted.
9428 			 * This is the only case unlike ip_newroute_v6,
9429 			 * ip_newroute_ipif_v6 where we can always prevent
9430 			 * deletions because ire_add_then_send is called after
9431 			 * creating the IRE.
9432 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9433 			 * does not add this IRE into the IRE CACHE.
9434 			 */
9435 			ASSERT(ire->ire_mp != NULL);
9436 			ire->ire_mp->b_cont = first_mp;
9437 			/* Have saved_mp handy, for cleanup if canput fails */
9438 			saved_mp = mp;
9439 			mp = copyb(res_mp);
9440 			if (mp == NULL) {
9441 				/* Prepare for cleanup */
9442 				mp = saved_mp; /* pkt */
9443 				ire_delete(ire); /* ire_mp */
9444 				ire = NULL;
9445 				if (copy_mp != NULL) {
9446 					MULTIRT_DEBUG_UNTAG(copy_mp);
9447 					freemsg(copy_mp);
9448 					copy_mp = NULL;
9449 				}
9450 				break;
9451 			}
9452 			linkb(mp, ire->ire_mp);
9453 
9454 			/*
9455 			 * Fill in the source and dest addrs for the resolver.
9456 			 * NOTE: this depends on memory layouts imposed by
9457 			 * ill_init().  There are corner cases above where we
9458 			 * might've created the IRE with an INADDR_ANY source
9459 			 * address (e.g., if the zeroth ipif on an underlying
9460 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9461 			 * on the ill has a usable test address).  If so, tell
9462 			 * ARP to use ipha_src as its sender address.
9463 			 */
9464 			areq = (areq_t *)mp->b_rptr;
9465 			addrp = (ipaddr_t *)((char *)areq +
9466 			    areq->areq_sender_addr_offset);
9467 			if (ire->ire_src_addr != INADDR_ANY)
9468 				*addrp = ire->ire_src_addr;
9469 			else
9470 				*addrp = ipha->ipha_src;
9471 			addrp = (ipaddr_t *)((char *)areq +
9472 			    areq->areq_target_addr_offset);
9473 			*addrp = dst;
9474 			/* Up to the resolver. */
9475 			if (canputnext(dst_ill->ill_rq) &&
9476 			    !(dst_ill->ill_arp_closing)) {
9477 				putnext(dst_ill->ill_rq, mp);
9478 				/*
9479 				 * The response will come back in ip_wput
9480 				 * with db_type IRE_DB_TYPE.
9481 				 */
9482 			} else {
9483 				mp->b_cont = NULL;
9484 				freeb(mp); /* areq */
9485 				ire_delete(ire); /* ire_mp */
9486 				saved_mp->b_next = NULL;
9487 				saved_mp->b_prev = NULL;
9488 				freemsg(first_mp); /* pkt */
9489 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9490 			}
9491 
9492 			if (fire != NULL) {
9493 				ire_refrele(fire);
9494 				fire = NULL;
9495 			}
9496 
9497 			/*
9498 			 * The resolution loop is re-entered if this was
9499 			 * requested through flags and we actually are
9500 			 * in a multirouting case.
9501 			 */
9502 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9503 				boolean_t need_resolve =
9504 				    ire_multirt_need_resolve(ipha_dst,
9505 				    msg_getlabel(copy_mp), ipst);
9506 				if (!need_resolve) {
9507 					MULTIRT_DEBUG_UNTAG(copy_mp);
9508 					freemsg(copy_mp);
9509 					copy_mp = NULL;
9510 				} else {
9511 					/*
9512 					 * ipif_lookup_group() calls
9513 					 * ire_lookup_multi() that uses
9514 					 * ire_ftable_lookup() to find
9515 					 * an IRE_INTERFACE for the group.
9516 					 * In the multirt case,
9517 					 * ire_lookup_multi() then invokes
9518 					 * ire_multirt_lookup() to find
9519 					 * the next resolvable ire.
9520 					 * As a result, we obtain an new
9521 					 * interface, derived from the
9522 					 * next ire.
9523 					 */
9524 					ipif_refrele(ipif);
9525 					ipif = ipif_lookup_group(ipha_dst,
9526 					    zoneid, ipst);
9527 					if (ipif != NULL) {
9528 						mp = copy_mp;
9529 						copy_mp = NULL;
9530 						multirt_resolve_next = B_TRUE;
9531 						continue;
9532 					} else {
9533 						freemsg(copy_mp);
9534 					}
9535 				}
9536 			}
9537 			if (ipif != NULL)
9538 				ipif_refrele(ipif);
9539 			ill_refrele(dst_ill);
9540 			ipif_refrele(src_ipif);
9541 			return;
9542 		default:
9543 			break;
9544 		}
9545 	} while (multirt_resolve_next);
9546 
9547 err_ret:
9548 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9549 	if (fire != NULL)
9550 		ire_refrele(fire);
9551 	ipif_refrele(ipif);
9552 	/* Did this packet originate externally? */
9553 	if (dst_ill != NULL)
9554 		ill_refrele(dst_ill);
9555 	if (src_ipif != NULL)
9556 		ipif_refrele(src_ipif);
9557 	if (mp->b_prev || mp->b_next) {
9558 		mp->b_next = NULL;
9559 		mp->b_prev = NULL;
9560 	} else {
9561 		/*
9562 		 * Since ip_wput() isn't close to finished, we fill
9563 		 * in enough of the header for credible error reporting.
9564 		 */
9565 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9566 			/* Failed */
9567 			freemsg(first_mp);
9568 			if (ire != NULL)
9569 				ire_refrele(ire);
9570 			return;
9571 		}
9572 	}
9573 	/*
9574 	 * At this point we will have ire only if RTF_BLACKHOLE
9575 	 * or RTF_REJECT flags are set on the IRE. It will not
9576 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9577 	 */
9578 	if (ire != NULL) {
9579 		if (ire->ire_flags & RTF_BLACKHOLE) {
9580 			ire_refrele(ire);
9581 			freemsg(first_mp);
9582 			return;
9583 		}
9584 		ire_refrele(ire);
9585 	}
9586 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9587 }
9588 
9589 /* Name/Value Table Lookup Routine */
9590 char *
9591 ip_nv_lookup(nv_t *nv, int value)
9592 {
9593 	if (!nv)
9594 		return (NULL);
9595 	for (; nv->nv_name; nv++) {
9596 		if (nv->nv_value == value)
9597 			return (nv->nv_name);
9598 	}
9599 	return ("unknown");
9600 }
9601 
9602 /*
9603  * This is a module open, i.e. this is a control stream for access
9604  * to a DLPI device.  We allocate an ill_t as the instance data in
9605  * this case.
9606  */
9607 int
9608 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9609 {
9610 	ill_t	*ill;
9611 	int	err;
9612 	zoneid_t zoneid;
9613 	netstack_t *ns;
9614 	ip_stack_t *ipst;
9615 
9616 	/*
9617 	 * Prevent unprivileged processes from pushing IP so that
9618 	 * they can't send raw IP.
9619 	 */
9620 	if (secpolicy_net_rawaccess(credp) != 0)
9621 		return (EPERM);
9622 
9623 	ns = netstack_find_by_cred(credp);
9624 	ASSERT(ns != NULL);
9625 	ipst = ns->netstack_ip;
9626 	ASSERT(ipst != NULL);
9627 
9628 	/*
9629 	 * For exclusive stacks we set the zoneid to zero
9630 	 * to make IP operate as if in the global zone.
9631 	 */
9632 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9633 		zoneid = GLOBAL_ZONEID;
9634 	else
9635 		zoneid = crgetzoneid(credp);
9636 
9637 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9638 	q->q_ptr = WR(q)->q_ptr = ill;
9639 	ill->ill_ipst = ipst;
9640 	ill->ill_zoneid = zoneid;
9641 
9642 	/*
9643 	 * ill_init initializes the ill fields and then sends down
9644 	 * down a DL_INFO_REQ after calling qprocson.
9645 	 */
9646 	err = ill_init(q, ill);
9647 	if (err != 0) {
9648 		mi_free(ill);
9649 		netstack_rele(ipst->ips_netstack);
9650 		q->q_ptr = NULL;
9651 		WR(q)->q_ptr = NULL;
9652 		return (err);
9653 	}
9654 
9655 	/* ill_init initializes the ipsq marking this thread as writer */
9656 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9657 	/* Wait for the DL_INFO_ACK */
9658 	mutex_enter(&ill->ill_lock);
9659 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9660 		/*
9661 		 * Return value of 0 indicates a pending signal.
9662 		 */
9663 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9664 		if (err == 0) {
9665 			mutex_exit(&ill->ill_lock);
9666 			(void) ip_close(q, 0);
9667 			return (EINTR);
9668 		}
9669 	}
9670 	mutex_exit(&ill->ill_lock);
9671 
9672 	/*
9673 	 * ip_rput_other could have set an error  in ill_error on
9674 	 * receipt of M_ERROR.
9675 	 */
9676 
9677 	err = ill->ill_error;
9678 	if (err != 0) {
9679 		(void) ip_close(q, 0);
9680 		return (err);
9681 	}
9682 
9683 	ill->ill_credp = credp;
9684 	crhold(credp);
9685 
9686 	mutex_enter(&ipst->ips_ip_mi_lock);
9687 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9688 	    credp);
9689 	mutex_exit(&ipst->ips_ip_mi_lock);
9690 	if (err) {
9691 		(void) ip_close(q, 0);
9692 		return (err);
9693 	}
9694 	return (0);
9695 }
9696 
9697 /* For /dev/ip aka AF_INET open */
9698 int
9699 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9700 {
9701 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9702 }
9703 
9704 /* For /dev/ip6 aka AF_INET6 open */
9705 int
9706 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9707 {
9708 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9709 }
9710 
9711 /* IP open routine. */
9712 int
9713 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9714     boolean_t isv6)
9715 {
9716 	conn_t 		*connp;
9717 	major_t		maj;
9718 	zoneid_t	zoneid;
9719 	netstack_t	*ns;
9720 	ip_stack_t	*ipst;
9721 
9722 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9723 
9724 	/* Allow reopen. */
9725 	if (q->q_ptr != NULL)
9726 		return (0);
9727 
9728 	if (sflag & MODOPEN) {
9729 		/* This is a module open */
9730 		return (ip_modopen(q, devp, flag, sflag, credp));
9731 	}
9732 
9733 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9734 		/*
9735 		 * Non streams based socket looking for a stream
9736 		 * to access IP
9737 		 */
9738 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9739 		    credp, isv6));
9740 	}
9741 
9742 	ns = netstack_find_by_cred(credp);
9743 	ASSERT(ns != NULL);
9744 	ipst = ns->netstack_ip;
9745 	ASSERT(ipst != NULL);
9746 
9747 	/*
9748 	 * For exclusive stacks we set the zoneid to zero
9749 	 * to make IP operate as if in the global zone.
9750 	 */
9751 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9752 		zoneid = GLOBAL_ZONEID;
9753 	else
9754 		zoneid = crgetzoneid(credp);
9755 
9756 	/*
9757 	 * We are opening as a device. This is an IP client stream, and we
9758 	 * allocate an conn_t as the instance data.
9759 	 */
9760 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9761 
9762 	/*
9763 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9764 	 * done by netstack_find_by_cred()
9765 	 */
9766 	netstack_rele(ipst->ips_netstack);
9767 
9768 	connp->conn_zoneid = zoneid;
9769 	connp->conn_sqp = NULL;
9770 	connp->conn_initial_sqp = NULL;
9771 	connp->conn_final_sqp = NULL;
9772 
9773 	connp->conn_upq = q;
9774 	q->q_ptr = WR(q)->q_ptr = connp;
9775 
9776 	if (flag & SO_SOCKSTR)
9777 		connp->conn_flags |= IPCL_SOCKET;
9778 
9779 	/* Minor tells us which /dev entry was opened */
9780 	if (isv6) {
9781 		connp->conn_af_isv6 = B_TRUE;
9782 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9783 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9784 	} else {
9785 		connp->conn_af_isv6 = B_FALSE;
9786 		connp->conn_pkt_isv6 = B_FALSE;
9787 	}
9788 
9789 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9790 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9791 		connp->conn_minor_arena = ip_minor_arena_la;
9792 	} else {
9793 		/*
9794 		 * Either minor numbers in the large arena were exhausted
9795 		 * or a non socket application is doing the open.
9796 		 * Try to allocate from the small arena.
9797 		 */
9798 		if ((connp->conn_dev =
9799 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9800 			/* CONN_DEC_REF takes care of netstack_rele() */
9801 			q->q_ptr = WR(q)->q_ptr = NULL;
9802 			CONN_DEC_REF(connp);
9803 			return (EBUSY);
9804 		}
9805 		connp->conn_minor_arena = ip_minor_arena_sa;
9806 	}
9807 
9808 	maj = getemajor(*devp);
9809 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9810 
9811 	/*
9812 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9813 	 */
9814 	connp->conn_cred = credp;
9815 
9816 	/*
9817 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9818 	 */
9819 	connp->conn_recv = ip_conn_input;
9820 
9821 	crhold(connp->conn_cred);
9822 
9823 	/*
9824 	 * If the caller has the process-wide flag set, then default to MAC
9825 	 * exempt mode.  This allows read-down to unlabeled hosts.
9826 	 */
9827 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9828 		connp->conn_mac_mode = CONN_MAC_AWARE;
9829 
9830 	connp->conn_rq = q;
9831 	connp->conn_wq = WR(q);
9832 
9833 	/* Non-zero default values */
9834 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9835 
9836 	/*
9837 	 * Make the conn globally visible to walkers
9838 	 */
9839 	ASSERT(connp->conn_ref == 1);
9840 	mutex_enter(&connp->conn_lock);
9841 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9842 	mutex_exit(&connp->conn_lock);
9843 
9844 	qprocson(q);
9845 
9846 	return (0);
9847 }
9848 
9849 /*
9850  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9851  * Note that there is no race since either ip_output function works - it
9852  * is just an optimization to enter the best ip_output routine directly.
9853  */
9854 void
9855 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9856     ip_stack_t *ipst)
9857 {
9858 	if (isv6)  {
9859 		if (bump_mib) {
9860 			BUMP_MIB(&ipst->ips_ip6_mib,
9861 			    ipIfStatsOutSwitchIPVersion);
9862 		}
9863 		connp->conn_send = ip_output_v6;
9864 		connp->conn_pkt_isv6 = B_TRUE;
9865 	} else {
9866 		if (bump_mib) {
9867 			BUMP_MIB(&ipst->ips_ip_mib,
9868 			    ipIfStatsOutSwitchIPVersion);
9869 		}
9870 		connp->conn_send = ip_output;
9871 		connp->conn_pkt_isv6 = B_FALSE;
9872 	}
9873 
9874 }
9875 
9876 /*
9877  * See if IPsec needs loading because of the options in mp.
9878  */
9879 static boolean_t
9880 ipsec_opt_present(mblk_t *mp)
9881 {
9882 	uint8_t *optcp, *next_optcp, *opt_endcp;
9883 	struct opthdr *opt;
9884 	struct T_opthdr *topt;
9885 	int opthdr_len;
9886 	t_uscalar_t optname, optlevel;
9887 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9888 	ipsec_req_t *ipsr;
9889 
9890 	/*
9891 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9892 	 * return TRUE.
9893 	 */
9894 
9895 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9896 	opt_endcp = optcp + tor->OPT_length;
9897 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9898 		opthdr_len = sizeof (struct T_opthdr);
9899 	} else {		/* O_OPTMGMT_REQ */
9900 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9901 		opthdr_len = sizeof (struct opthdr);
9902 	}
9903 	for (; optcp < opt_endcp; optcp = next_optcp) {
9904 		if (optcp + opthdr_len > opt_endcp)
9905 			return (B_FALSE);	/* Not enough option header. */
9906 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9907 			topt = (struct T_opthdr *)optcp;
9908 			optlevel = topt->level;
9909 			optname = topt->name;
9910 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9911 		} else {
9912 			opt = (struct opthdr *)optcp;
9913 			optlevel = opt->level;
9914 			optname = opt->name;
9915 			next_optcp = optcp + opthdr_len +
9916 			    _TPI_ALIGN_OPT(opt->len);
9917 		}
9918 		if ((next_optcp < optcp) || /* wraparound pointer space */
9919 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9920 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9921 			return (B_FALSE); /* bad option buffer */
9922 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9923 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9924 			/*
9925 			 * Check to see if it's an all-bypass or all-zeroes
9926 			 * IPsec request.  Don't bother loading IPsec if
9927 			 * the socket doesn't want to use it.  (A good example
9928 			 * is a bypass request.)
9929 			 *
9930 			 * Basically, if any of the non-NEVER bits are set,
9931 			 * load IPsec.
9932 			 */
9933 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9934 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9935 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9936 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9937 			    != 0)
9938 				return (B_TRUE);
9939 		}
9940 	}
9941 	return (B_FALSE);
9942 }
9943 
9944 /*
9945  * If conn is is waiting for ipsec to finish loading, kick it.
9946  */
9947 /* ARGSUSED */
9948 static void
9949 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9950 {
9951 	t_scalar_t	optreq_prim;
9952 	mblk_t		*mp;
9953 	cred_t		*cr;
9954 	int		err = 0;
9955 
9956 	/*
9957 	 * This function is called, after ipsec loading is complete.
9958 	 * Since IP checks exclusively and atomically (i.e it prevents
9959 	 * ipsec load from completing until ip_optcom_req completes)
9960 	 * whether ipsec load is complete, there cannot be a race with IP
9961 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9962 	 */
9963 	mutex_enter(&connp->conn_lock);
9964 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9965 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9966 		mp = connp->conn_ipsec_opt_mp;
9967 		connp->conn_ipsec_opt_mp = NULL;
9968 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9969 		mutex_exit(&connp->conn_lock);
9970 
9971 		/*
9972 		 * All Solaris components should pass a db_credp
9973 		 * for this TPI message, hence we ASSERT.
9974 		 * But in case there is some other M_PROTO that looks
9975 		 * like a TPI message sent by some other kernel
9976 		 * component, we check and return an error.
9977 		 */
9978 		cr = msg_getcred(mp, NULL);
9979 		ASSERT(cr != NULL);
9980 		if (cr == NULL) {
9981 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
9982 			if (mp != NULL)
9983 				qreply(connp->conn_wq, mp);
9984 			return;
9985 		}
9986 
9987 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9988 
9989 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9990 		if (optreq_prim == T_OPTMGMT_REQ) {
9991 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9992 			    &ip_opt_obj, B_FALSE);
9993 		} else {
9994 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9995 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9996 			    &ip_opt_obj, B_FALSE);
9997 		}
9998 		if (err != EINPROGRESS)
9999 			CONN_OPER_PENDING_DONE(connp);
10000 		return;
10001 	}
10002 	mutex_exit(&connp->conn_lock);
10003 }
10004 
10005 /*
10006  * Called from the ipsec_loader thread, outside any perimeter, to tell
10007  * ip qenable any of the queues waiting for the ipsec loader to
10008  * complete.
10009  */
10010 void
10011 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10012 {
10013 	netstack_t *ns = ipss->ipsec_netstack;
10014 
10015 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10016 }
10017 
10018 /*
10019  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10020  * determines the grp on which it has to become exclusive, queues the mp
10021  * and IPSQ draining restarts the optmgmt
10022  */
10023 static boolean_t
10024 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10025 {
10026 	conn_t *connp = Q_TO_CONN(q);
10027 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10028 
10029 	/*
10030 	 * Take IPsec requests and treat them special.
10031 	 */
10032 	if (ipsec_opt_present(mp)) {
10033 		/* First check if IPsec is loaded. */
10034 		mutex_enter(&ipss->ipsec_loader_lock);
10035 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10036 			mutex_exit(&ipss->ipsec_loader_lock);
10037 			return (B_FALSE);
10038 		}
10039 		mutex_enter(&connp->conn_lock);
10040 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10041 
10042 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10043 		connp->conn_ipsec_opt_mp = mp;
10044 		mutex_exit(&connp->conn_lock);
10045 		mutex_exit(&ipss->ipsec_loader_lock);
10046 
10047 		ipsec_loader_loadnow(ipss);
10048 		return (B_TRUE);
10049 	}
10050 	return (B_FALSE);
10051 }
10052 
10053 /*
10054  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10055  * all of them are copied to the conn_t. If the req is "zero", the policy is
10056  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10057  * fields.
10058  * We keep only the latest setting of the policy and thus policy setting
10059  * is not incremental/cumulative.
10060  *
10061  * Requests to set policies with multiple alternative actions will
10062  * go through a different API.
10063  */
10064 int
10065 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10066 {
10067 	uint_t ah_req = 0;
10068 	uint_t esp_req = 0;
10069 	uint_t se_req = 0;
10070 	ipsec_act_t *actp = NULL;
10071 	uint_t nact;
10072 	ipsec_policy_head_t *ph;
10073 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
10074 	int error = 0;
10075 	netstack_t	*ns = connp->conn_netstack;
10076 	ip_stack_t	*ipst = ns->netstack_ip;
10077 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10078 
10079 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10080 
10081 	/*
10082 	 * The IP_SEC_OPT option does not allow variable length parameters,
10083 	 * hence a request cannot be NULL.
10084 	 */
10085 	if (req == NULL)
10086 		return (EINVAL);
10087 
10088 	ah_req = req->ipsr_ah_req;
10089 	esp_req = req->ipsr_esp_req;
10090 	se_req = req->ipsr_self_encap_req;
10091 
10092 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10093 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10094 		return (EINVAL);
10095 
10096 	/*
10097 	 * Are we dealing with a request to reset the policy (i.e.
10098 	 * zero requests).
10099 	 */
10100 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10101 	    (esp_req & REQ_MASK) == 0 &&
10102 	    (se_req & REQ_MASK) == 0);
10103 
10104 	if (!is_pol_reset) {
10105 		/*
10106 		 * If we couldn't load IPsec, fail with "protocol
10107 		 * not supported".
10108 		 * IPsec may not have been loaded for a request with zero
10109 		 * policies, so we don't fail in this case.
10110 		 */
10111 		mutex_enter(&ipss->ipsec_loader_lock);
10112 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10113 			mutex_exit(&ipss->ipsec_loader_lock);
10114 			return (EPROTONOSUPPORT);
10115 		}
10116 		mutex_exit(&ipss->ipsec_loader_lock);
10117 
10118 		/*
10119 		 * Test for valid requests. Invalid algorithms
10120 		 * need to be tested by IPsec code because new
10121 		 * algorithms can be added dynamically.
10122 		 */
10123 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10124 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10125 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10126 			return (EINVAL);
10127 		}
10128 
10129 		/*
10130 		 * Only privileged users can issue these
10131 		 * requests.
10132 		 */
10133 		if (((ah_req & IPSEC_PREF_NEVER) ||
10134 		    (esp_req & IPSEC_PREF_NEVER) ||
10135 		    (se_req & IPSEC_PREF_NEVER)) &&
10136 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10137 			return (EPERM);
10138 		}
10139 
10140 		/*
10141 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10142 		 * are mutually exclusive.
10143 		 */
10144 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10145 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10146 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10147 			/* Both of them are set */
10148 			return (EINVAL);
10149 		}
10150 	}
10151 
10152 	mutex_enter(&connp->conn_lock);
10153 
10154 	/*
10155 	 * If we have already cached policies in ip_bind_connected*(), don't
10156 	 * let them change now. We cache policies for connections
10157 	 * whose src,dst [addr, port] is known.
10158 	 */
10159 	if (connp->conn_policy_cached) {
10160 		mutex_exit(&connp->conn_lock);
10161 		return (EINVAL);
10162 	}
10163 
10164 	/*
10165 	 * We have a zero policies, reset the connection policy if already
10166 	 * set. This will cause the connection to inherit the
10167 	 * global policy, if any.
10168 	 */
10169 	if (is_pol_reset) {
10170 		if (connp->conn_policy != NULL) {
10171 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10172 			connp->conn_policy = NULL;
10173 		}
10174 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10175 		connp->conn_in_enforce_policy = B_FALSE;
10176 		connp->conn_out_enforce_policy = B_FALSE;
10177 		mutex_exit(&connp->conn_lock);
10178 		return (0);
10179 	}
10180 
10181 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10182 	    ipst->ips_netstack);
10183 	if (ph == NULL)
10184 		goto enomem;
10185 
10186 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10187 	if (actp == NULL)
10188 		goto enomem;
10189 
10190 	/*
10191 	 * Always insert IPv4 policy entries, since they can also apply to
10192 	 * ipv6 sockets being used in ipv4-compat mode.
10193 	 */
10194 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10195 	    IPSEC_TYPE_INBOUND, ns))
10196 		goto enomem;
10197 	is_pol_inserted = B_TRUE;
10198 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10199 	    IPSEC_TYPE_OUTBOUND, ns))
10200 		goto enomem;
10201 
10202 	/*
10203 	 * We're looking at a v6 socket, also insert the v6-specific
10204 	 * entries.
10205 	 */
10206 	if (connp->conn_af_isv6) {
10207 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10208 		    IPSEC_TYPE_INBOUND, ns))
10209 			goto enomem;
10210 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10211 		    IPSEC_TYPE_OUTBOUND, ns))
10212 			goto enomem;
10213 	}
10214 
10215 	ipsec_actvec_free(actp, nact);
10216 
10217 	/*
10218 	 * If the requests need security, set enforce_policy.
10219 	 * If the requests are IPSEC_PREF_NEVER, one should
10220 	 * still set conn_out_enforce_policy so that an ipsec_out
10221 	 * gets attached in ip_wput. This is needed so that
10222 	 * for connections that we don't cache policy in ip_bind,
10223 	 * if global policy matches in ip_wput_attach_policy, we
10224 	 * don't wrongly inherit global policy. Similarly, we need
10225 	 * to set conn_in_enforce_policy also so that we don't verify
10226 	 * policy wrongly.
10227 	 */
10228 	if ((ah_req & REQ_MASK) != 0 ||
10229 	    (esp_req & REQ_MASK) != 0 ||
10230 	    (se_req & REQ_MASK) != 0) {
10231 		connp->conn_in_enforce_policy = B_TRUE;
10232 		connp->conn_out_enforce_policy = B_TRUE;
10233 		connp->conn_flags |= IPCL_CHECK_POLICY;
10234 	}
10235 
10236 	mutex_exit(&connp->conn_lock);
10237 	return (error);
10238 #undef REQ_MASK
10239 
10240 	/*
10241 	 * Common memory-allocation-failure exit path.
10242 	 */
10243 enomem:
10244 	mutex_exit(&connp->conn_lock);
10245 	if (actp != NULL)
10246 		ipsec_actvec_free(actp, nact);
10247 	if (is_pol_inserted)
10248 		ipsec_polhead_flush(ph, ns);
10249 	return (ENOMEM);
10250 }
10251 
10252 /*
10253  * Only for options that pass in an IP addr. Currently only V4 options
10254  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10255  * So this function assumes level is IPPROTO_IP
10256  */
10257 int
10258 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10259     mblk_t *first_mp)
10260 {
10261 	ipif_t *ipif = NULL;
10262 	int error;
10263 	ill_t *ill;
10264 	int zoneid;
10265 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10266 
10267 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10268 
10269 	if (addr != INADDR_ANY || checkonly) {
10270 		ASSERT(connp != NULL);
10271 		zoneid = IPCL_ZONEID(connp);
10272 		if (option == IP_NEXTHOP) {
10273 			ipif = ipif_lookup_onlink_addr(addr,
10274 			    connp->conn_zoneid, ipst);
10275 		} else {
10276 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10277 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10278 			    &error, ipst);
10279 		}
10280 		if (ipif == NULL) {
10281 			if (error == EINPROGRESS)
10282 				return (error);
10283 			if ((option == IP_MULTICAST_IF) ||
10284 			    (option == IP_NEXTHOP))
10285 				return (EHOSTUNREACH);
10286 			else
10287 				return (EINVAL);
10288 		} else if (checkonly) {
10289 			if (option == IP_MULTICAST_IF) {
10290 				ill = ipif->ipif_ill;
10291 				/* not supported by the virtual network iface */
10292 				if (IS_VNI(ill)) {
10293 					ipif_refrele(ipif);
10294 					return (EINVAL);
10295 				}
10296 			}
10297 			ipif_refrele(ipif);
10298 			return (0);
10299 		}
10300 		ill = ipif->ipif_ill;
10301 		mutex_enter(&connp->conn_lock);
10302 		mutex_enter(&ill->ill_lock);
10303 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10304 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10305 			mutex_exit(&ill->ill_lock);
10306 			mutex_exit(&connp->conn_lock);
10307 			ipif_refrele(ipif);
10308 			return (option == IP_MULTICAST_IF ?
10309 			    EHOSTUNREACH : EINVAL);
10310 		}
10311 	} else {
10312 		mutex_enter(&connp->conn_lock);
10313 	}
10314 
10315 	/* None of the options below are supported on the VNI */
10316 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10317 		mutex_exit(&ill->ill_lock);
10318 		mutex_exit(&connp->conn_lock);
10319 		ipif_refrele(ipif);
10320 		return (EINVAL);
10321 	}
10322 
10323 	switch (option) {
10324 	case IP_MULTICAST_IF:
10325 		connp->conn_multicast_ipif = ipif;
10326 		break;
10327 	case IP_NEXTHOP:
10328 		connp->conn_nexthop_v4 = addr;
10329 		connp->conn_nexthop_set = B_TRUE;
10330 		break;
10331 	}
10332 
10333 	if (ipif != NULL) {
10334 		mutex_exit(&ill->ill_lock);
10335 		mutex_exit(&connp->conn_lock);
10336 		ipif_refrele(ipif);
10337 		return (0);
10338 	}
10339 	mutex_exit(&connp->conn_lock);
10340 	/* We succeded in cleared the option */
10341 	return (0);
10342 }
10343 
10344 /*
10345  * For options that pass in an ifindex specifying the ill. V6 options always
10346  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10347  */
10348 int
10349 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10350     int level, int option, mblk_t *first_mp)
10351 {
10352 	ill_t *ill = NULL;
10353 	int error = 0;
10354 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10355 
10356 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10357 	if (ifindex != 0) {
10358 		ASSERT(connp != NULL);
10359 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10360 		    first_mp, ip_restart_optmgmt, &error, ipst);
10361 		if (ill != NULL) {
10362 			if (checkonly) {
10363 				/* not supported by the virtual network iface */
10364 				if (IS_VNI(ill)) {
10365 					ill_refrele(ill);
10366 					return (EINVAL);
10367 				}
10368 				ill_refrele(ill);
10369 				return (0);
10370 			}
10371 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10372 			    0, NULL)) {
10373 				ill_refrele(ill);
10374 				ill = NULL;
10375 				mutex_enter(&connp->conn_lock);
10376 				goto setit;
10377 			}
10378 			mutex_enter(&connp->conn_lock);
10379 			mutex_enter(&ill->ill_lock);
10380 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10381 				mutex_exit(&ill->ill_lock);
10382 				mutex_exit(&connp->conn_lock);
10383 				ill_refrele(ill);
10384 				ill = NULL;
10385 				mutex_enter(&connp->conn_lock);
10386 			}
10387 			goto setit;
10388 		} else if (error == EINPROGRESS) {
10389 			return (error);
10390 		} else {
10391 			error = 0;
10392 		}
10393 	}
10394 	mutex_enter(&connp->conn_lock);
10395 setit:
10396 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10397 
10398 	/*
10399 	 * The options below assume that the ILL (if any) transmits and/or
10400 	 * receives traffic. Neither of which is true for the virtual network
10401 	 * interface, so fail setting these on a VNI.
10402 	 */
10403 	if (IS_VNI(ill)) {
10404 		ASSERT(ill != NULL);
10405 		mutex_exit(&ill->ill_lock);
10406 		mutex_exit(&connp->conn_lock);
10407 		ill_refrele(ill);
10408 		return (EINVAL);
10409 	}
10410 
10411 	if (level == IPPROTO_IP) {
10412 		switch (option) {
10413 		case IP_BOUND_IF:
10414 			connp->conn_incoming_ill = ill;
10415 			connp->conn_outgoing_ill = ill;
10416 			break;
10417 
10418 		case IP_MULTICAST_IF:
10419 			/*
10420 			 * This option is an internal special. The socket
10421 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10422 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10423 			 * specifies an ifindex and we try first on V6 ill's.
10424 			 * If we don't find one, we they try using on v4 ill's
10425 			 * intenally and we come here.
10426 			 */
10427 			if (!checkonly && ill != NULL) {
10428 				ipif_t	*ipif;
10429 				ipif = ill->ill_ipif;
10430 
10431 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10432 					mutex_exit(&ill->ill_lock);
10433 					mutex_exit(&connp->conn_lock);
10434 					ill_refrele(ill);
10435 					ill = NULL;
10436 					mutex_enter(&connp->conn_lock);
10437 				} else {
10438 					connp->conn_multicast_ipif = ipif;
10439 				}
10440 			}
10441 			break;
10442 
10443 		case IP_DHCPINIT_IF:
10444 			if (connp->conn_dhcpinit_ill != NULL) {
10445 				/*
10446 				 * We've locked the conn so conn_cleanup_ill()
10447 				 * cannot clear conn_dhcpinit_ill -- so it's
10448 				 * safe to access the ill.
10449 				 */
10450 				ill_t *oill = connp->conn_dhcpinit_ill;
10451 
10452 				ASSERT(oill->ill_dhcpinit != 0);
10453 				atomic_dec_32(&oill->ill_dhcpinit);
10454 				connp->conn_dhcpinit_ill = NULL;
10455 			}
10456 
10457 			if (ill != NULL) {
10458 				connp->conn_dhcpinit_ill = ill;
10459 				atomic_inc_32(&ill->ill_dhcpinit);
10460 			}
10461 			break;
10462 		}
10463 	} else {
10464 		switch (option) {
10465 		case IPV6_BOUND_IF:
10466 			connp->conn_incoming_ill = ill;
10467 			connp->conn_outgoing_ill = ill;
10468 			break;
10469 
10470 		case IPV6_MULTICAST_IF:
10471 			/*
10472 			 * Set conn_multicast_ill to be the IPv6 ill.
10473 			 * Set conn_multicast_ipif to be an IPv4 ipif
10474 			 * for ifindex to make IPv4 mapped addresses
10475 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10476 			 * Even if no IPv6 ill exists for the ifindex
10477 			 * we need to check for an IPv4 ifindex in order
10478 			 * for this to work with mapped addresses. In that
10479 			 * case only set conn_multicast_ipif.
10480 			 */
10481 			if (!checkonly) {
10482 				if (ifindex == 0) {
10483 					connp->conn_multicast_ill = NULL;
10484 					connp->conn_multicast_ipif = NULL;
10485 				} else if (ill != NULL) {
10486 					connp->conn_multicast_ill = ill;
10487 				}
10488 			}
10489 			break;
10490 		}
10491 	}
10492 
10493 	if (ill != NULL) {
10494 		mutex_exit(&ill->ill_lock);
10495 		mutex_exit(&connp->conn_lock);
10496 		ill_refrele(ill);
10497 		return (0);
10498 	}
10499 	mutex_exit(&connp->conn_lock);
10500 	/*
10501 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10502 	 * locate the ill and could not set the option (ifindex != 0)
10503 	 */
10504 	return (ifindex == 0 ? 0 : EINVAL);
10505 }
10506 
10507 /* This routine sets socket options. */
10508 /* ARGSUSED */
10509 int
10510 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10511     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10512     void *dummy, cred_t *cr, mblk_t *first_mp)
10513 {
10514 	int		*i1 = (int *)invalp;
10515 	conn_t		*connp = Q_TO_CONN(q);
10516 	int		error = 0;
10517 	boolean_t	checkonly;
10518 	ire_t		*ire;
10519 	boolean_t	found;
10520 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10521 
10522 	switch (optset_context) {
10523 
10524 	case SETFN_OPTCOM_CHECKONLY:
10525 		checkonly = B_TRUE;
10526 		/*
10527 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10528 		 * inlen != 0 implies value supplied and
10529 		 * 	we have to "pretend" to set it.
10530 		 * inlen == 0 implies that there is no
10531 		 * 	value part in T_CHECK request and just validation
10532 		 * done elsewhere should be enough, we just return here.
10533 		 */
10534 		if (inlen == 0) {
10535 			*outlenp = 0;
10536 			return (0);
10537 		}
10538 		break;
10539 	case SETFN_OPTCOM_NEGOTIATE:
10540 	case SETFN_UD_NEGOTIATE:
10541 	case SETFN_CONN_NEGOTIATE:
10542 		checkonly = B_FALSE;
10543 		break;
10544 	default:
10545 		/*
10546 		 * We should never get here
10547 		 */
10548 		*outlenp = 0;
10549 		return (EINVAL);
10550 	}
10551 
10552 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10553 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10554 
10555 	/*
10556 	 * For fixed length options, no sanity check
10557 	 * of passed in length is done. It is assumed *_optcom_req()
10558 	 * routines do the right thing.
10559 	 */
10560 
10561 	switch (level) {
10562 	case SOL_SOCKET:
10563 		/*
10564 		 * conn_lock protects the bitfields, and is used to
10565 		 * set the fields atomically.
10566 		 */
10567 		switch (name) {
10568 		case SO_BROADCAST:
10569 			if (!checkonly) {
10570 				/* TODO: use value someplace? */
10571 				mutex_enter(&connp->conn_lock);
10572 				connp->conn_broadcast = *i1 ? 1 : 0;
10573 				mutex_exit(&connp->conn_lock);
10574 			}
10575 			break;	/* goto sizeof (int) option return */
10576 		case SO_USELOOPBACK:
10577 			if (!checkonly) {
10578 				/* TODO: use value someplace? */
10579 				mutex_enter(&connp->conn_lock);
10580 				connp->conn_loopback = *i1 ? 1 : 0;
10581 				mutex_exit(&connp->conn_lock);
10582 			}
10583 			break;	/* goto sizeof (int) option return */
10584 		case SO_DONTROUTE:
10585 			if (!checkonly) {
10586 				mutex_enter(&connp->conn_lock);
10587 				connp->conn_dontroute = *i1 ? 1 : 0;
10588 				mutex_exit(&connp->conn_lock);
10589 			}
10590 			break;	/* goto sizeof (int) option return */
10591 		case SO_REUSEADDR:
10592 			if (!checkonly) {
10593 				mutex_enter(&connp->conn_lock);
10594 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10595 				mutex_exit(&connp->conn_lock);
10596 			}
10597 			break;	/* goto sizeof (int) option return */
10598 		case SO_PROTOTYPE:
10599 			if (!checkonly) {
10600 				mutex_enter(&connp->conn_lock);
10601 				connp->conn_proto = *i1;
10602 				mutex_exit(&connp->conn_lock);
10603 			}
10604 			break;	/* goto sizeof (int) option return */
10605 		case SO_ALLZONES:
10606 			if (!checkonly) {
10607 				mutex_enter(&connp->conn_lock);
10608 				if (IPCL_IS_BOUND(connp)) {
10609 					mutex_exit(&connp->conn_lock);
10610 					return (EINVAL);
10611 				}
10612 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10613 				mutex_exit(&connp->conn_lock);
10614 			}
10615 			break;	/* goto sizeof (int) option return */
10616 		case SO_ANON_MLP:
10617 			if (!checkonly) {
10618 				mutex_enter(&connp->conn_lock);
10619 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10620 				mutex_exit(&connp->conn_lock);
10621 			}
10622 			break;	/* goto sizeof (int) option return */
10623 		case SO_MAC_EXEMPT:
10624 			if (secpolicy_net_mac_aware(cr) != 0 ||
10625 			    IPCL_IS_BOUND(connp))
10626 				return (EACCES);
10627 			if (!checkonly) {
10628 				mutex_enter(&connp->conn_lock);
10629 				connp->conn_mac_mode = *i1 != 0 ?
10630 				    CONN_MAC_AWARE : CONN_MAC_DEFAULT;
10631 				mutex_exit(&connp->conn_lock);
10632 			}
10633 			break;	/* goto sizeof (int) option return */
10634 		case SO_MAC_IMPLICIT:
10635 			if (secpolicy_net_mac_implicit(cr) != 0)
10636 				return (EACCES);
10637 			if (!checkonly) {
10638 				mutex_enter(&connp->conn_lock);
10639 				connp->conn_mac_mode = *i1 != 0 ?
10640 				    CONN_MAC_IMPLICIT : CONN_MAC_DEFAULT;
10641 				mutex_exit(&connp->conn_lock);
10642 			}
10643 			break;	/* goto sizeof (int) option return */
10644 		default:
10645 			/*
10646 			 * "soft" error (negative)
10647 			 * option not handled at this level
10648 			 * Note: Do not modify *outlenp
10649 			 */
10650 			return (-EINVAL);
10651 		}
10652 		break;
10653 	case IPPROTO_IP:
10654 		switch (name) {
10655 		case IP_NEXTHOP:
10656 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10657 				return (EPERM);
10658 			/* FALLTHRU */
10659 		case IP_MULTICAST_IF: {
10660 			ipaddr_t addr = *i1;
10661 
10662 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10663 			    first_mp);
10664 			if (error != 0)
10665 				return (error);
10666 			break;	/* goto sizeof (int) option return */
10667 		}
10668 
10669 		case IP_MULTICAST_TTL:
10670 			/* Recorded in transport above IP */
10671 			*outvalp = *invalp;
10672 			*outlenp = sizeof (uchar_t);
10673 			return (0);
10674 		case IP_MULTICAST_LOOP:
10675 			if (!checkonly) {
10676 				mutex_enter(&connp->conn_lock);
10677 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10678 				mutex_exit(&connp->conn_lock);
10679 			}
10680 			*outvalp = *invalp;
10681 			*outlenp = sizeof (uchar_t);
10682 			return (0);
10683 		case IP_ADD_MEMBERSHIP:
10684 		case MCAST_JOIN_GROUP:
10685 		case IP_DROP_MEMBERSHIP:
10686 		case MCAST_LEAVE_GROUP: {
10687 			struct ip_mreq *mreqp;
10688 			struct group_req *greqp;
10689 			ire_t *ire;
10690 			boolean_t done = B_FALSE;
10691 			ipaddr_t group, ifaddr;
10692 			struct sockaddr_in *sin;
10693 			uint32_t *ifindexp;
10694 			boolean_t mcast_opt = B_TRUE;
10695 			mcast_record_t fmode;
10696 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10697 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10698 
10699 			switch (name) {
10700 			case IP_ADD_MEMBERSHIP:
10701 				mcast_opt = B_FALSE;
10702 				/* FALLTHRU */
10703 			case MCAST_JOIN_GROUP:
10704 				fmode = MODE_IS_EXCLUDE;
10705 				optfn = ip_opt_add_group;
10706 				break;
10707 
10708 			case IP_DROP_MEMBERSHIP:
10709 				mcast_opt = B_FALSE;
10710 				/* FALLTHRU */
10711 			case MCAST_LEAVE_GROUP:
10712 				fmode = MODE_IS_INCLUDE;
10713 				optfn = ip_opt_delete_group;
10714 				break;
10715 			}
10716 
10717 			if (mcast_opt) {
10718 				greqp = (struct group_req *)i1;
10719 				sin = (struct sockaddr_in *)&greqp->gr_group;
10720 				if (sin->sin_family != AF_INET) {
10721 					*outlenp = 0;
10722 					return (ENOPROTOOPT);
10723 				}
10724 				group = (ipaddr_t)sin->sin_addr.s_addr;
10725 				ifaddr = INADDR_ANY;
10726 				ifindexp = &greqp->gr_interface;
10727 			} else {
10728 				mreqp = (struct ip_mreq *)i1;
10729 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10730 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10731 				ifindexp = NULL;
10732 			}
10733 
10734 			/*
10735 			 * In the multirouting case, we need to replicate
10736 			 * the request on all interfaces that will take part
10737 			 * in replication.  We do so because multirouting is
10738 			 * reflective, thus we will probably receive multi-
10739 			 * casts on those interfaces.
10740 			 * The ip_multirt_apply_membership() succeeds if the
10741 			 * operation succeeds on at least one interface.
10742 			 */
10743 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10744 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10745 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10746 			if (ire != NULL) {
10747 				if (ire->ire_flags & RTF_MULTIRT) {
10748 					error = ip_multirt_apply_membership(
10749 					    optfn, ire, connp, checkonly, group,
10750 					    fmode, INADDR_ANY, first_mp);
10751 					done = B_TRUE;
10752 				}
10753 				ire_refrele(ire);
10754 			}
10755 			if (!done) {
10756 				error = optfn(connp, checkonly, group, ifaddr,
10757 				    ifindexp, fmode, INADDR_ANY, first_mp);
10758 			}
10759 			if (error) {
10760 				/*
10761 				 * EINPROGRESS is a soft error, needs retry
10762 				 * so don't make *outlenp zero.
10763 				 */
10764 				if (error != EINPROGRESS)
10765 					*outlenp = 0;
10766 				return (error);
10767 			}
10768 			/* OK return - copy input buffer into output buffer */
10769 			if (invalp != outvalp) {
10770 				/* don't trust bcopy for identical src/dst */
10771 				bcopy(invalp, outvalp, inlen);
10772 			}
10773 			*outlenp = inlen;
10774 			return (0);
10775 		}
10776 		case IP_BLOCK_SOURCE:
10777 		case IP_UNBLOCK_SOURCE:
10778 		case IP_ADD_SOURCE_MEMBERSHIP:
10779 		case IP_DROP_SOURCE_MEMBERSHIP:
10780 		case MCAST_BLOCK_SOURCE:
10781 		case MCAST_UNBLOCK_SOURCE:
10782 		case MCAST_JOIN_SOURCE_GROUP:
10783 		case MCAST_LEAVE_SOURCE_GROUP: {
10784 			struct ip_mreq_source *imreqp;
10785 			struct group_source_req *gsreqp;
10786 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10787 			uint32_t ifindex = 0;
10788 			mcast_record_t fmode;
10789 			struct sockaddr_in *sin;
10790 			ire_t *ire;
10791 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10792 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10793 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10794 
10795 			switch (name) {
10796 			case IP_BLOCK_SOURCE:
10797 				mcast_opt = B_FALSE;
10798 				/* FALLTHRU */
10799 			case MCAST_BLOCK_SOURCE:
10800 				fmode = MODE_IS_EXCLUDE;
10801 				optfn = ip_opt_add_group;
10802 				break;
10803 
10804 			case IP_UNBLOCK_SOURCE:
10805 				mcast_opt = B_FALSE;
10806 				/* FALLTHRU */
10807 			case MCAST_UNBLOCK_SOURCE:
10808 				fmode = MODE_IS_EXCLUDE;
10809 				optfn = ip_opt_delete_group;
10810 				break;
10811 
10812 			case IP_ADD_SOURCE_MEMBERSHIP:
10813 				mcast_opt = B_FALSE;
10814 				/* FALLTHRU */
10815 			case MCAST_JOIN_SOURCE_GROUP:
10816 				fmode = MODE_IS_INCLUDE;
10817 				optfn = ip_opt_add_group;
10818 				break;
10819 
10820 			case IP_DROP_SOURCE_MEMBERSHIP:
10821 				mcast_opt = B_FALSE;
10822 				/* FALLTHRU */
10823 			case MCAST_LEAVE_SOURCE_GROUP:
10824 				fmode = MODE_IS_INCLUDE;
10825 				optfn = ip_opt_delete_group;
10826 				break;
10827 			}
10828 
10829 			if (mcast_opt) {
10830 				gsreqp = (struct group_source_req *)i1;
10831 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10832 					*outlenp = 0;
10833 					return (ENOPROTOOPT);
10834 				}
10835 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10836 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10837 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10838 				src = (ipaddr_t)sin->sin_addr.s_addr;
10839 				ifindex = gsreqp->gsr_interface;
10840 			} else {
10841 				imreqp = (struct ip_mreq_source *)i1;
10842 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10843 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10844 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10845 			}
10846 
10847 			/*
10848 			 * In the multirouting case, we need to replicate
10849 			 * the request as noted in the mcast cases above.
10850 			 */
10851 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10852 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10853 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10854 			if (ire != NULL) {
10855 				if (ire->ire_flags & RTF_MULTIRT) {
10856 					error = ip_multirt_apply_membership(
10857 					    optfn, ire, connp, checkonly, grp,
10858 					    fmode, src, first_mp);
10859 					done = B_TRUE;
10860 				}
10861 				ire_refrele(ire);
10862 			}
10863 			if (!done) {
10864 				error = optfn(connp, checkonly, grp, ifaddr,
10865 				    &ifindex, fmode, src, first_mp);
10866 			}
10867 			if (error != 0) {
10868 				/*
10869 				 * EINPROGRESS is a soft error, needs retry
10870 				 * so don't make *outlenp zero.
10871 				 */
10872 				if (error != EINPROGRESS)
10873 					*outlenp = 0;
10874 				return (error);
10875 			}
10876 			/* OK return - copy input buffer into output buffer */
10877 			if (invalp != outvalp) {
10878 				bcopy(invalp, outvalp, inlen);
10879 			}
10880 			*outlenp = inlen;
10881 			return (0);
10882 		}
10883 		case IP_SEC_OPT:
10884 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10885 			if (error != 0) {
10886 				*outlenp = 0;
10887 				return (error);
10888 			}
10889 			break;
10890 		case IP_HDRINCL:
10891 		case IP_OPTIONS:
10892 		case T_IP_OPTIONS:
10893 		case IP_TOS:
10894 		case T_IP_TOS:
10895 		case IP_TTL:
10896 		case IP_RECVDSTADDR:
10897 		case IP_RECVOPTS:
10898 			/* OK return - copy input buffer into output buffer */
10899 			if (invalp != outvalp) {
10900 				/* don't trust bcopy for identical src/dst */
10901 				bcopy(invalp, outvalp, inlen);
10902 			}
10903 			*outlenp = inlen;
10904 			return (0);
10905 		case IP_RECVIF:
10906 			/* Retrieve the inbound interface index */
10907 			if (!checkonly) {
10908 				mutex_enter(&connp->conn_lock);
10909 				connp->conn_recvif = *i1 ? 1 : 0;
10910 				mutex_exit(&connp->conn_lock);
10911 			}
10912 			break;	/* goto sizeof (int) option return */
10913 		case IP_RECVPKTINFO:
10914 			if (!checkonly) {
10915 				mutex_enter(&connp->conn_lock);
10916 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10917 				mutex_exit(&connp->conn_lock);
10918 			}
10919 			break;	/* goto sizeof (int) option return */
10920 		case IP_RECVSLLA:
10921 			/* Retrieve the source link layer address */
10922 			if (!checkonly) {
10923 				mutex_enter(&connp->conn_lock);
10924 				connp->conn_recvslla = *i1 ? 1 : 0;
10925 				mutex_exit(&connp->conn_lock);
10926 			}
10927 			break;	/* goto sizeof (int) option return */
10928 		case MRT_INIT:
10929 		case MRT_DONE:
10930 		case MRT_ADD_VIF:
10931 		case MRT_DEL_VIF:
10932 		case MRT_ADD_MFC:
10933 		case MRT_DEL_MFC:
10934 		case MRT_ASSERT:
10935 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10936 				*outlenp = 0;
10937 				return (error);
10938 			}
10939 			error = ip_mrouter_set((int)name, q, checkonly,
10940 			    (uchar_t *)invalp, inlen, first_mp);
10941 			if (error) {
10942 				*outlenp = 0;
10943 				return (error);
10944 			}
10945 			/* OK return - copy input buffer into output buffer */
10946 			if (invalp != outvalp) {
10947 				/* don't trust bcopy for identical src/dst */
10948 				bcopy(invalp, outvalp, inlen);
10949 			}
10950 			*outlenp = inlen;
10951 			return (0);
10952 		case IP_BOUND_IF:
10953 		case IP_DHCPINIT_IF:
10954 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10955 			    level, name, first_mp);
10956 			if (error != 0)
10957 				return (error);
10958 			break; 		/* goto sizeof (int) option return */
10959 
10960 		case IP_UNSPEC_SRC:
10961 			/* Allow sending with a zero source address */
10962 			if (!checkonly) {
10963 				mutex_enter(&connp->conn_lock);
10964 				connp->conn_unspec_src = *i1 ? 1 : 0;
10965 				mutex_exit(&connp->conn_lock);
10966 			}
10967 			break;	/* goto sizeof (int) option return */
10968 		default:
10969 			/*
10970 			 * "soft" error (negative)
10971 			 * option not handled at this level
10972 			 * Note: Do not modify *outlenp
10973 			 */
10974 			return (-EINVAL);
10975 		}
10976 		break;
10977 	case IPPROTO_IPV6:
10978 		switch (name) {
10979 		case IPV6_BOUND_IF:
10980 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10981 			    level, name, first_mp);
10982 			if (error != 0)
10983 				return (error);
10984 			break; 		/* goto sizeof (int) option return */
10985 
10986 		case IPV6_MULTICAST_IF:
10987 			/*
10988 			 * The only possible errors are EINPROGRESS and
10989 			 * EINVAL. EINPROGRESS will be restarted and is not
10990 			 * a hard error. We call this option on both V4 and V6
10991 			 * If both return EINVAL, then this call returns
10992 			 * EINVAL. If at least one of them succeeds we
10993 			 * return success.
10994 			 */
10995 			found = B_FALSE;
10996 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10997 			    level, name, first_mp);
10998 			if (error == EINPROGRESS)
10999 				return (error);
11000 			if (error == 0)
11001 				found = B_TRUE;
11002 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11003 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11004 			if (error == 0)
11005 				found = B_TRUE;
11006 			if (!found)
11007 				return (error);
11008 			break; 		/* goto sizeof (int) option return */
11009 
11010 		case IPV6_MULTICAST_HOPS:
11011 			/* Recorded in transport above IP */
11012 			break;	/* goto sizeof (int) option return */
11013 		case IPV6_MULTICAST_LOOP:
11014 			if (!checkonly) {
11015 				mutex_enter(&connp->conn_lock);
11016 				connp->conn_multicast_loop = *i1;
11017 				mutex_exit(&connp->conn_lock);
11018 			}
11019 			break;	/* goto sizeof (int) option return */
11020 		case IPV6_JOIN_GROUP:
11021 		case MCAST_JOIN_GROUP:
11022 		case IPV6_LEAVE_GROUP:
11023 		case MCAST_LEAVE_GROUP: {
11024 			struct ipv6_mreq *ip_mreqp;
11025 			struct group_req *greqp;
11026 			ire_t *ire;
11027 			boolean_t done = B_FALSE;
11028 			in6_addr_t groupv6;
11029 			uint32_t ifindex;
11030 			boolean_t mcast_opt = B_TRUE;
11031 			mcast_record_t fmode;
11032 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11033 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11034 
11035 			switch (name) {
11036 			case IPV6_JOIN_GROUP:
11037 				mcast_opt = B_FALSE;
11038 				/* FALLTHRU */
11039 			case MCAST_JOIN_GROUP:
11040 				fmode = MODE_IS_EXCLUDE;
11041 				optfn = ip_opt_add_group_v6;
11042 				break;
11043 
11044 			case IPV6_LEAVE_GROUP:
11045 				mcast_opt = B_FALSE;
11046 				/* FALLTHRU */
11047 			case MCAST_LEAVE_GROUP:
11048 				fmode = MODE_IS_INCLUDE;
11049 				optfn = ip_opt_delete_group_v6;
11050 				break;
11051 			}
11052 
11053 			if (mcast_opt) {
11054 				struct sockaddr_in *sin;
11055 				struct sockaddr_in6 *sin6;
11056 				greqp = (struct group_req *)i1;
11057 				if (greqp->gr_group.ss_family == AF_INET) {
11058 					sin = (struct sockaddr_in *)
11059 					    &(greqp->gr_group);
11060 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11061 					    &groupv6);
11062 				} else {
11063 					sin6 = (struct sockaddr_in6 *)
11064 					    &(greqp->gr_group);
11065 					groupv6 = sin6->sin6_addr;
11066 				}
11067 				ifindex = greqp->gr_interface;
11068 			} else {
11069 				ip_mreqp = (struct ipv6_mreq *)i1;
11070 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11071 				ifindex = ip_mreqp->ipv6mr_interface;
11072 			}
11073 			/*
11074 			 * In the multirouting case, we need to replicate
11075 			 * the request on all interfaces that will take part
11076 			 * in replication.  We do so because multirouting is
11077 			 * reflective, thus we will probably receive multi-
11078 			 * casts on those interfaces.
11079 			 * The ip_multirt_apply_membership_v6() succeeds if
11080 			 * the operation succeeds on at least one interface.
11081 			 */
11082 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11083 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11084 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11085 			if (ire != NULL) {
11086 				if (ire->ire_flags & RTF_MULTIRT) {
11087 					error = ip_multirt_apply_membership_v6(
11088 					    optfn, ire, connp, checkonly,
11089 					    &groupv6, fmode, &ipv6_all_zeros,
11090 					    first_mp);
11091 					done = B_TRUE;
11092 				}
11093 				ire_refrele(ire);
11094 			}
11095 			if (!done) {
11096 				error = optfn(connp, checkonly, &groupv6,
11097 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11098 			}
11099 			if (error) {
11100 				/*
11101 				 * EINPROGRESS is a soft error, needs retry
11102 				 * so don't make *outlenp zero.
11103 				 */
11104 				if (error != EINPROGRESS)
11105 					*outlenp = 0;
11106 				return (error);
11107 			}
11108 			/* OK return - copy input buffer into output buffer */
11109 			if (invalp != outvalp) {
11110 				/* don't trust bcopy for identical src/dst */
11111 				bcopy(invalp, outvalp, inlen);
11112 			}
11113 			*outlenp = inlen;
11114 			return (0);
11115 		}
11116 		case MCAST_BLOCK_SOURCE:
11117 		case MCAST_UNBLOCK_SOURCE:
11118 		case MCAST_JOIN_SOURCE_GROUP:
11119 		case MCAST_LEAVE_SOURCE_GROUP: {
11120 			struct group_source_req *gsreqp;
11121 			in6_addr_t v6grp, v6src;
11122 			uint32_t ifindex;
11123 			mcast_record_t fmode;
11124 			ire_t *ire;
11125 			boolean_t done = B_FALSE;
11126 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11127 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11128 
11129 			switch (name) {
11130 			case MCAST_BLOCK_SOURCE:
11131 				fmode = MODE_IS_EXCLUDE;
11132 				optfn = ip_opt_add_group_v6;
11133 				break;
11134 			case MCAST_UNBLOCK_SOURCE:
11135 				fmode = MODE_IS_EXCLUDE;
11136 				optfn = ip_opt_delete_group_v6;
11137 				break;
11138 			case MCAST_JOIN_SOURCE_GROUP:
11139 				fmode = MODE_IS_INCLUDE;
11140 				optfn = ip_opt_add_group_v6;
11141 				break;
11142 			case MCAST_LEAVE_SOURCE_GROUP:
11143 				fmode = MODE_IS_INCLUDE;
11144 				optfn = ip_opt_delete_group_v6;
11145 				break;
11146 			}
11147 
11148 			gsreqp = (struct group_source_req *)i1;
11149 			ifindex = gsreqp->gsr_interface;
11150 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11151 				struct sockaddr_in *s;
11152 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11153 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11154 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11155 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11156 			} else {
11157 				struct sockaddr_in6 *s6;
11158 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11159 				v6grp = s6->sin6_addr;
11160 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11161 				v6src = s6->sin6_addr;
11162 			}
11163 
11164 			/*
11165 			 * In the multirouting case, we need to replicate
11166 			 * the request as noted in the mcast cases above.
11167 			 */
11168 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11169 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11170 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11171 			if (ire != NULL) {
11172 				if (ire->ire_flags & RTF_MULTIRT) {
11173 					error = ip_multirt_apply_membership_v6(
11174 					    optfn, ire, connp, checkonly,
11175 					    &v6grp, fmode, &v6src, first_mp);
11176 					done = B_TRUE;
11177 				}
11178 				ire_refrele(ire);
11179 			}
11180 			if (!done) {
11181 				error = optfn(connp, checkonly, &v6grp,
11182 				    ifindex, fmode, &v6src, first_mp);
11183 			}
11184 			if (error != 0) {
11185 				/*
11186 				 * EINPROGRESS is a soft error, needs retry
11187 				 * so don't make *outlenp zero.
11188 				 */
11189 				if (error != EINPROGRESS)
11190 					*outlenp = 0;
11191 				return (error);
11192 			}
11193 			/* OK return - copy input buffer into output buffer */
11194 			if (invalp != outvalp) {
11195 				bcopy(invalp, outvalp, inlen);
11196 			}
11197 			*outlenp = inlen;
11198 			return (0);
11199 		}
11200 		case IPV6_UNICAST_HOPS:
11201 			/* Recorded in transport above IP */
11202 			break;	/* goto sizeof (int) option return */
11203 		case IPV6_UNSPEC_SRC:
11204 			/* Allow sending with a zero source address */
11205 			if (!checkonly) {
11206 				mutex_enter(&connp->conn_lock);
11207 				connp->conn_unspec_src = *i1 ? 1 : 0;
11208 				mutex_exit(&connp->conn_lock);
11209 			}
11210 			break;	/* goto sizeof (int) option return */
11211 		case IPV6_RECVPKTINFO:
11212 			if (!checkonly) {
11213 				mutex_enter(&connp->conn_lock);
11214 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11215 				mutex_exit(&connp->conn_lock);
11216 			}
11217 			break;	/* goto sizeof (int) option return */
11218 		case IPV6_RECVTCLASS:
11219 			if (!checkonly) {
11220 				if (*i1 < 0 || *i1 > 1) {
11221 					return (EINVAL);
11222 				}
11223 				mutex_enter(&connp->conn_lock);
11224 				connp->conn_ipv6_recvtclass = *i1;
11225 				mutex_exit(&connp->conn_lock);
11226 			}
11227 			break;
11228 		case IPV6_RECVPATHMTU:
11229 			if (!checkonly) {
11230 				if (*i1 < 0 || *i1 > 1) {
11231 					return (EINVAL);
11232 				}
11233 				mutex_enter(&connp->conn_lock);
11234 				connp->conn_ipv6_recvpathmtu = *i1;
11235 				mutex_exit(&connp->conn_lock);
11236 			}
11237 			break;
11238 		case IPV6_RECVHOPLIMIT:
11239 			if (!checkonly) {
11240 				mutex_enter(&connp->conn_lock);
11241 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11242 				mutex_exit(&connp->conn_lock);
11243 			}
11244 			break;	/* goto sizeof (int) option return */
11245 		case IPV6_RECVHOPOPTS:
11246 			if (!checkonly) {
11247 				mutex_enter(&connp->conn_lock);
11248 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11249 				mutex_exit(&connp->conn_lock);
11250 			}
11251 			break;	/* goto sizeof (int) option return */
11252 		case IPV6_RECVDSTOPTS:
11253 			if (!checkonly) {
11254 				mutex_enter(&connp->conn_lock);
11255 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11256 				mutex_exit(&connp->conn_lock);
11257 			}
11258 			break;	/* goto sizeof (int) option return */
11259 		case IPV6_RECVRTHDR:
11260 			if (!checkonly) {
11261 				mutex_enter(&connp->conn_lock);
11262 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11263 				mutex_exit(&connp->conn_lock);
11264 			}
11265 			break;	/* goto sizeof (int) option return */
11266 		case IPV6_RECVRTHDRDSTOPTS:
11267 			if (!checkonly) {
11268 				mutex_enter(&connp->conn_lock);
11269 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11270 				mutex_exit(&connp->conn_lock);
11271 			}
11272 			break;	/* goto sizeof (int) option return */
11273 		case IPV6_PKTINFO:
11274 			if (inlen == 0)
11275 				return (-EINVAL);	/* clearing option */
11276 			error = ip6_set_pktinfo(cr, connp,
11277 			    (struct in6_pktinfo *)invalp);
11278 			if (error != 0)
11279 				*outlenp = 0;
11280 			else
11281 				*outlenp = inlen;
11282 			return (error);
11283 		case IPV6_NEXTHOP: {
11284 			struct sockaddr_in6 *sin6;
11285 
11286 			/* Verify that the nexthop is reachable */
11287 			if (inlen == 0)
11288 				return (-EINVAL);	/* clearing option */
11289 
11290 			sin6 = (struct sockaddr_in6 *)invalp;
11291 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11292 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11293 			    NULL, MATCH_IRE_DEFAULT, ipst);
11294 
11295 			if (ire == NULL) {
11296 				*outlenp = 0;
11297 				return (EHOSTUNREACH);
11298 			}
11299 			ire_refrele(ire);
11300 			return (-EINVAL);
11301 		}
11302 		case IPV6_SEC_OPT:
11303 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11304 			if (error != 0) {
11305 				*outlenp = 0;
11306 				return (error);
11307 			}
11308 			break;
11309 		case IPV6_SRC_PREFERENCES: {
11310 			/*
11311 			 * This is implemented strictly in the ip module
11312 			 * (here and in tcp_opt_*() to accomodate tcp
11313 			 * sockets).  Modules above ip pass this option
11314 			 * down here since ip is the only one that needs to
11315 			 * be aware of source address preferences.
11316 			 *
11317 			 * This socket option only affects connected
11318 			 * sockets that haven't already bound to a specific
11319 			 * IPv6 address.  In other words, sockets that
11320 			 * don't call bind() with an address other than the
11321 			 * unspecified address and that call connect().
11322 			 * ip_bind_connected_v6() passes these preferences
11323 			 * to the ipif_select_source_v6() function.
11324 			 */
11325 			if (inlen != sizeof (uint32_t))
11326 				return (EINVAL);
11327 			error = ip6_set_src_preferences(connp,
11328 			    *(uint32_t *)invalp);
11329 			if (error != 0) {
11330 				*outlenp = 0;
11331 				return (error);
11332 			} else {
11333 				*outlenp = sizeof (uint32_t);
11334 			}
11335 			break;
11336 		}
11337 		case IPV6_V6ONLY:
11338 			if (*i1 < 0 || *i1 > 1) {
11339 				return (EINVAL);
11340 			}
11341 			mutex_enter(&connp->conn_lock);
11342 			connp->conn_ipv6_v6only = *i1;
11343 			mutex_exit(&connp->conn_lock);
11344 			break;
11345 		default:
11346 			return (-EINVAL);
11347 		}
11348 		break;
11349 	default:
11350 		/*
11351 		 * "soft" error (negative)
11352 		 * option not handled at this level
11353 		 * Note: Do not modify *outlenp
11354 		 */
11355 		return (-EINVAL);
11356 	}
11357 	/*
11358 	 * Common case of return from an option that is sizeof (int)
11359 	 */
11360 	*(int *)outvalp = *i1;
11361 	*outlenp = sizeof (int);
11362 	return (0);
11363 }
11364 
11365 /*
11366  * This routine gets default values of certain options whose default
11367  * values are maintained by protocol specific code
11368  */
11369 /* ARGSUSED */
11370 int
11371 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11372 {
11373 	int *i1 = (int *)ptr;
11374 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11375 
11376 	switch (level) {
11377 	case IPPROTO_IP:
11378 		switch (name) {
11379 		case IP_MULTICAST_TTL:
11380 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11381 			return (sizeof (uchar_t));
11382 		case IP_MULTICAST_LOOP:
11383 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11384 			return (sizeof (uchar_t));
11385 		default:
11386 			return (-1);
11387 		}
11388 	case IPPROTO_IPV6:
11389 		switch (name) {
11390 		case IPV6_UNICAST_HOPS:
11391 			*i1 = ipst->ips_ipv6_def_hops;
11392 			return (sizeof (int));
11393 		case IPV6_MULTICAST_HOPS:
11394 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11395 			return (sizeof (int));
11396 		case IPV6_MULTICAST_LOOP:
11397 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11398 			return (sizeof (int));
11399 		case IPV6_V6ONLY:
11400 			*i1 = 1;
11401 			return (sizeof (int));
11402 		default:
11403 			return (-1);
11404 		}
11405 	default:
11406 		return (-1);
11407 	}
11408 	/* NOTREACHED */
11409 }
11410 
11411 /*
11412  * Given a destination address and a pointer to where to put the information
11413  * this routine fills in the mtuinfo.
11414  */
11415 int
11416 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11417     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11418 {
11419 	ire_t *ire;
11420 	ip_stack_t	*ipst = ns->netstack_ip;
11421 
11422 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11423 		return (-1);
11424 
11425 	bzero(mtuinfo, sizeof (*mtuinfo));
11426 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11427 	mtuinfo->ip6m_addr.sin6_port = port;
11428 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11429 
11430 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11431 	if (ire != NULL) {
11432 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11433 		ire_refrele(ire);
11434 	} else {
11435 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11436 	}
11437 	return (sizeof (struct ip6_mtuinfo));
11438 }
11439 
11440 /*
11441  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11442  * checking of cred and that ip_g_mrouter is set should be done and
11443  * isn't.  This doesn't matter as the error checking is done properly for the
11444  * other MRT options coming in through ip_opt_set.
11445  */
11446 int
11447 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11448 {
11449 	conn_t		*connp = Q_TO_CONN(q);
11450 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11451 
11452 	switch (level) {
11453 	case IPPROTO_IP:
11454 		switch (name) {
11455 		case MRT_VERSION:
11456 		case MRT_ASSERT:
11457 			(void) ip_mrouter_get(name, q, ptr);
11458 			return (sizeof (int));
11459 		case IP_SEC_OPT:
11460 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11461 		case IP_NEXTHOP:
11462 			if (connp->conn_nexthop_set) {
11463 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11464 				return (sizeof (ipaddr_t));
11465 			} else
11466 				return (0);
11467 		case IP_RECVPKTINFO:
11468 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11469 			return (sizeof (int));
11470 		default:
11471 			break;
11472 		}
11473 		break;
11474 	case IPPROTO_IPV6:
11475 		switch (name) {
11476 		case IPV6_SEC_OPT:
11477 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11478 		case IPV6_SRC_PREFERENCES: {
11479 			return (ip6_get_src_preferences(connp,
11480 			    (uint32_t *)ptr));
11481 		}
11482 		case IPV6_V6ONLY:
11483 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11484 			return (sizeof (int));
11485 		case IPV6_PATHMTU:
11486 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11487 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11488 		default:
11489 			break;
11490 		}
11491 		break;
11492 	default:
11493 		break;
11494 	}
11495 	return (-1);
11496 }
11497 /* Named Dispatch routine to get a current value out of our parameter table. */
11498 /* ARGSUSED */
11499 static int
11500 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11501 {
11502 	ipparam_t *ippa = (ipparam_t *)cp;
11503 
11504 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11505 	return (0);
11506 }
11507 
11508 /* ARGSUSED */
11509 static int
11510 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11511 {
11512 
11513 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11514 	return (0);
11515 }
11516 
11517 /*
11518  * Set ip{,6}_forwarding values.  This means walking through all of the
11519  * ill's and toggling their forwarding values.
11520  */
11521 /* ARGSUSED */
11522 static int
11523 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11524 {
11525 	long new_value;
11526 	int *forwarding_value = (int *)cp;
11527 	ill_t *ill;
11528 	boolean_t isv6;
11529 	ill_walk_context_t ctx;
11530 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11531 
11532 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11533 
11534 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11535 	    new_value < 0 || new_value > 1) {
11536 		return (EINVAL);
11537 	}
11538 
11539 	*forwarding_value = new_value;
11540 
11541 	/*
11542 	 * Regardless of the current value of ip_forwarding, set all per-ill
11543 	 * values of ip_forwarding to the value being set.
11544 	 *
11545 	 * Bring all the ill's up to date with the new global value.
11546 	 */
11547 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11548 
11549 	if (isv6)
11550 		ill = ILL_START_WALK_V6(&ctx, ipst);
11551 	else
11552 		ill = ILL_START_WALK_V4(&ctx, ipst);
11553 
11554 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11555 		(void) ill_forward_set(ill, new_value != 0);
11556 
11557 	rw_exit(&ipst->ips_ill_g_lock);
11558 	return (0);
11559 }
11560 
11561 /*
11562  * Walk through the param array specified registering each element with the
11563  * Named Dispatch handler. This is called only during init. So it is ok
11564  * not to acquire any locks
11565  */
11566 static boolean_t
11567 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11568     ipndp_t *ipnd, size_t ipnd_cnt)
11569 {
11570 	for (; ippa_cnt-- > 0; ippa++) {
11571 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11572 			if (!nd_load(ndp, ippa->ip_param_name,
11573 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11574 				nd_free(ndp);
11575 				return (B_FALSE);
11576 			}
11577 		}
11578 	}
11579 
11580 	for (; ipnd_cnt-- > 0; ipnd++) {
11581 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11582 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11583 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11584 			    ipnd->ip_ndp_data)) {
11585 				nd_free(ndp);
11586 				return (B_FALSE);
11587 			}
11588 		}
11589 	}
11590 
11591 	return (B_TRUE);
11592 }
11593 
11594 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11595 /* ARGSUSED */
11596 static int
11597 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11598 {
11599 	long		new_value;
11600 	ipparam_t	*ippa = (ipparam_t *)cp;
11601 
11602 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11603 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11604 		return (EINVAL);
11605 	}
11606 	ippa->ip_param_value = new_value;
11607 	return (0);
11608 }
11609 
11610 /*
11611  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11612  * When an ipf is passed here for the first time, if
11613  * we already have in-order fragments on the queue, we convert from the fast-
11614  * path reassembly scheme to the hard-case scheme.  From then on, additional
11615  * fragments are reassembled here.  We keep track of the start and end offsets
11616  * of each piece, and the number of holes in the chain.  When the hole count
11617  * goes to zero, we are done!
11618  *
11619  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11620  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11621  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11622  * after the call to ip_reassemble().
11623  */
11624 int
11625 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11626     size_t msg_len)
11627 {
11628 	uint_t	end;
11629 	mblk_t	*next_mp;
11630 	mblk_t	*mp1;
11631 	uint_t	offset;
11632 	boolean_t incr_dups = B_TRUE;
11633 	boolean_t offset_zero_seen = B_FALSE;
11634 	boolean_t pkt_boundary_checked = B_FALSE;
11635 
11636 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11637 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11638 
11639 	/* Add in byte count */
11640 	ipf->ipf_count += msg_len;
11641 	if (ipf->ipf_end) {
11642 		/*
11643 		 * We were part way through in-order reassembly, but now there
11644 		 * is a hole.  We walk through messages already queued, and
11645 		 * mark them for hard case reassembly.  We know that up till
11646 		 * now they were in order starting from offset zero.
11647 		 */
11648 		offset = 0;
11649 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11650 			IP_REASS_SET_START(mp1, offset);
11651 			if (offset == 0) {
11652 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11653 				offset = -ipf->ipf_nf_hdr_len;
11654 			}
11655 			offset += mp1->b_wptr - mp1->b_rptr;
11656 			IP_REASS_SET_END(mp1, offset);
11657 		}
11658 		/* One hole at the end. */
11659 		ipf->ipf_hole_cnt = 1;
11660 		/* Brand it as a hard case, forever. */
11661 		ipf->ipf_end = 0;
11662 	}
11663 	/* Walk through all the new pieces. */
11664 	do {
11665 		end = start + (mp->b_wptr - mp->b_rptr);
11666 		/*
11667 		 * If start is 0, decrease 'end' only for the first mblk of
11668 		 * the fragment. Otherwise 'end' can get wrong value in the
11669 		 * second pass of the loop if first mblk is exactly the
11670 		 * size of ipf_nf_hdr_len.
11671 		 */
11672 		if (start == 0 && !offset_zero_seen) {
11673 			/* First segment */
11674 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11675 			end -= ipf->ipf_nf_hdr_len;
11676 			offset_zero_seen = B_TRUE;
11677 		}
11678 		next_mp = mp->b_cont;
11679 		/*
11680 		 * We are checking to see if there is any interesing data
11681 		 * to process.  If there isn't and the mblk isn't the
11682 		 * one which carries the unfragmentable header then we
11683 		 * drop it.  It's possible to have just the unfragmentable
11684 		 * header come through without any data.  That needs to be
11685 		 * saved.
11686 		 *
11687 		 * If the assert at the top of this function holds then the
11688 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11689 		 * is infrequently traveled enough that the test is left in
11690 		 * to protect against future code changes which break that
11691 		 * invariant.
11692 		 */
11693 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11694 			/* Empty.  Blast it. */
11695 			IP_REASS_SET_START(mp, 0);
11696 			IP_REASS_SET_END(mp, 0);
11697 			/*
11698 			 * If the ipf points to the mblk we are about to free,
11699 			 * update ipf to point to the next mblk (or NULL
11700 			 * if none).
11701 			 */
11702 			if (ipf->ipf_mp->b_cont == mp)
11703 				ipf->ipf_mp->b_cont = next_mp;
11704 			freeb(mp);
11705 			continue;
11706 		}
11707 		mp->b_cont = NULL;
11708 		IP_REASS_SET_START(mp, start);
11709 		IP_REASS_SET_END(mp, end);
11710 		if (!ipf->ipf_tail_mp) {
11711 			ipf->ipf_tail_mp = mp;
11712 			ipf->ipf_mp->b_cont = mp;
11713 			if (start == 0 || !more) {
11714 				ipf->ipf_hole_cnt = 1;
11715 				/*
11716 				 * if the first fragment comes in more than one
11717 				 * mblk, this loop will be executed for each
11718 				 * mblk. Need to adjust hole count so exiting
11719 				 * this routine will leave hole count at 1.
11720 				 */
11721 				if (next_mp)
11722 					ipf->ipf_hole_cnt++;
11723 			} else
11724 				ipf->ipf_hole_cnt = 2;
11725 			continue;
11726 		} else if (ipf->ipf_last_frag_seen && !more &&
11727 		    !pkt_boundary_checked) {
11728 			/*
11729 			 * We check datagram boundary only if this fragment
11730 			 * claims to be the last fragment and we have seen a
11731 			 * last fragment in the past too. We do this only
11732 			 * once for a given fragment.
11733 			 *
11734 			 * start cannot be 0 here as fragments with start=0
11735 			 * and MF=0 gets handled as a complete packet. These
11736 			 * fragments should not reach here.
11737 			 */
11738 
11739 			if (start + msgdsize(mp) !=
11740 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11741 				/*
11742 				 * We have two fragments both of which claim
11743 				 * to be the last fragment but gives conflicting
11744 				 * information about the whole datagram size.
11745 				 * Something fishy is going on. Drop the
11746 				 * fragment and free up the reassembly list.
11747 				 */
11748 				return (IP_REASS_FAILED);
11749 			}
11750 
11751 			/*
11752 			 * We shouldn't come to this code block again for this
11753 			 * particular fragment.
11754 			 */
11755 			pkt_boundary_checked = B_TRUE;
11756 		}
11757 
11758 		/* New stuff at or beyond tail? */
11759 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11760 		if (start >= offset) {
11761 			if (ipf->ipf_last_frag_seen) {
11762 				/* current fragment is beyond last fragment */
11763 				return (IP_REASS_FAILED);
11764 			}
11765 			/* Link it on end. */
11766 			ipf->ipf_tail_mp->b_cont = mp;
11767 			ipf->ipf_tail_mp = mp;
11768 			if (more) {
11769 				if (start != offset)
11770 					ipf->ipf_hole_cnt++;
11771 			} else if (start == offset && next_mp == NULL)
11772 					ipf->ipf_hole_cnt--;
11773 			continue;
11774 		}
11775 		mp1 = ipf->ipf_mp->b_cont;
11776 		offset = IP_REASS_START(mp1);
11777 		/* New stuff at the front? */
11778 		if (start < offset) {
11779 			if (start == 0) {
11780 				if (end >= offset) {
11781 					/* Nailed the hole at the begining. */
11782 					ipf->ipf_hole_cnt--;
11783 				}
11784 			} else if (end < offset) {
11785 				/*
11786 				 * A hole, stuff, and a hole where there used
11787 				 * to be just a hole.
11788 				 */
11789 				ipf->ipf_hole_cnt++;
11790 			}
11791 			mp->b_cont = mp1;
11792 			/* Check for overlap. */
11793 			while (end > offset) {
11794 				if (end < IP_REASS_END(mp1)) {
11795 					mp->b_wptr -= end - offset;
11796 					IP_REASS_SET_END(mp, offset);
11797 					BUMP_MIB(ill->ill_ip_mib,
11798 					    ipIfStatsReasmPartDups);
11799 					break;
11800 				}
11801 				/* Did we cover another hole? */
11802 				if ((mp1->b_cont &&
11803 				    IP_REASS_END(mp1) !=
11804 				    IP_REASS_START(mp1->b_cont) &&
11805 				    end >= IP_REASS_START(mp1->b_cont)) ||
11806 				    (!ipf->ipf_last_frag_seen && !more)) {
11807 					ipf->ipf_hole_cnt--;
11808 				}
11809 				/* Clip out mp1. */
11810 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11811 					/*
11812 					 * After clipping out mp1, this guy
11813 					 * is now hanging off the end.
11814 					 */
11815 					ipf->ipf_tail_mp = mp;
11816 				}
11817 				IP_REASS_SET_START(mp1, 0);
11818 				IP_REASS_SET_END(mp1, 0);
11819 				/* Subtract byte count */
11820 				ipf->ipf_count -= mp1->b_datap->db_lim -
11821 				    mp1->b_datap->db_base;
11822 				freeb(mp1);
11823 				BUMP_MIB(ill->ill_ip_mib,
11824 				    ipIfStatsReasmPartDups);
11825 				mp1 = mp->b_cont;
11826 				if (!mp1)
11827 					break;
11828 				offset = IP_REASS_START(mp1);
11829 			}
11830 			ipf->ipf_mp->b_cont = mp;
11831 			continue;
11832 		}
11833 		/*
11834 		 * The new piece starts somewhere between the start of the head
11835 		 * and before the end of the tail.
11836 		 */
11837 		for (; mp1; mp1 = mp1->b_cont) {
11838 			offset = IP_REASS_END(mp1);
11839 			if (start < offset) {
11840 				if (end <= offset) {
11841 					/* Nothing new. */
11842 					IP_REASS_SET_START(mp, 0);
11843 					IP_REASS_SET_END(mp, 0);
11844 					/* Subtract byte count */
11845 					ipf->ipf_count -= mp->b_datap->db_lim -
11846 					    mp->b_datap->db_base;
11847 					if (incr_dups) {
11848 						ipf->ipf_num_dups++;
11849 						incr_dups = B_FALSE;
11850 					}
11851 					freeb(mp);
11852 					BUMP_MIB(ill->ill_ip_mib,
11853 					    ipIfStatsReasmDuplicates);
11854 					break;
11855 				}
11856 				/*
11857 				 * Trim redundant stuff off beginning of new
11858 				 * piece.
11859 				 */
11860 				IP_REASS_SET_START(mp, offset);
11861 				mp->b_rptr += offset - start;
11862 				BUMP_MIB(ill->ill_ip_mib,
11863 				    ipIfStatsReasmPartDups);
11864 				start = offset;
11865 				if (!mp1->b_cont) {
11866 					/*
11867 					 * After trimming, this guy is now
11868 					 * hanging off the end.
11869 					 */
11870 					mp1->b_cont = mp;
11871 					ipf->ipf_tail_mp = mp;
11872 					if (!more) {
11873 						ipf->ipf_hole_cnt--;
11874 					}
11875 					break;
11876 				}
11877 			}
11878 			if (start >= IP_REASS_START(mp1->b_cont))
11879 				continue;
11880 			/* Fill a hole */
11881 			if (start > offset)
11882 				ipf->ipf_hole_cnt++;
11883 			mp->b_cont = mp1->b_cont;
11884 			mp1->b_cont = mp;
11885 			mp1 = mp->b_cont;
11886 			offset = IP_REASS_START(mp1);
11887 			if (end >= offset) {
11888 				ipf->ipf_hole_cnt--;
11889 				/* Check for overlap. */
11890 				while (end > offset) {
11891 					if (end < IP_REASS_END(mp1)) {
11892 						mp->b_wptr -= end - offset;
11893 						IP_REASS_SET_END(mp, offset);
11894 						/*
11895 						 * TODO we might bump
11896 						 * this up twice if there is
11897 						 * overlap at both ends.
11898 						 */
11899 						BUMP_MIB(ill->ill_ip_mib,
11900 						    ipIfStatsReasmPartDups);
11901 						break;
11902 					}
11903 					/* Did we cover another hole? */
11904 					if ((mp1->b_cont &&
11905 					    IP_REASS_END(mp1)
11906 					    != IP_REASS_START(mp1->b_cont) &&
11907 					    end >=
11908 					    IP_REASS_START(mp1->b_cont)) ||
11909 					    (!ipf->ipf_last_frag_seen &&
11910 					    !more)) {
11911 						ipf->ipf_hole_cnt--;
11912 					}
11913 					/* Clip out mp1. */
11914 					if ((mp->b_cont = mp1->b_cont) ==
11915 					    NULL) {
11916 						/*
11917 						 * After clipping out mp1,
11918 						 * this guy is now hanging
11919 						 * off the end.
11920 						 */
11921 						ipf->ipf_tail_mp = mp;
11922 					}
11923 					IP_REASS_SET_START(mp1, 0);
11924 					IP_REASS_SET_END(mp1, 0);
11925 					/* Subtract byte count */
11926 					ipf->ipf_count -=
11927 					    mp1->b_datap->db_lim -
11928 					    mp1->b_datap->db_base;
11929 					freeb(mp1);
11930 					BUMP_MIB(ill->ill_ip_mib,
11931 					    ipIfStatsReasmPartDups);
11932 					mp1 = mp->b_cont;
11933 					if (!mp1)
11934 						break;
11935 					offset = IP_REASS_START(mp1);
11936 				}
11937 			}
11938 			break;
11939 		}
11940 	} while (start = end, mp = next_mp);
11941 
11942 	/* Fragment just processed could be the last one. Remember this fact */
11943 	if (!more)
11944 		ipf->ipf_last_frag_seen = B_TRUE;
11945 
11946 	/* Still got holes? */
11947 	if (ipf->ipf_hole_cnt)
11948 		return (IP_REASS_PARTIAL);
11949 	/* Clean up overloaded fields to avoid upstream disasters. */
11950 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11951 		IP_REASS_SET_START(mp1, 0);
11952 		IP_REASS_SET_END(mp1, 0);
11953 	}
11954 	return (IP_REASS_COMPLETE);
11955 }
11956 
11957 /*
11958  * ipsec processing for the fast path, used for input UDP Packets
11959  * Returns true if ready for passup to UDP.
11960  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
11961  * was an ESP-in-UDP packet, etc.).
11962  */
11963 static boolean_t
11964 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11965     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
11966 {
11967 	uint32_t	ill_index;
11968 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11969 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11970 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11971 	udp_t		*udp = connp->conn_udp;
11972 
11973 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11974 	/* The ill_index of the incoming ILL */
11975 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11976 
11977 	/* pass packet up to the transport */
11978 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11979 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11980 		    NULL, mctl_present);
11981 		if (*first_mpp == NULL) {
11982 			return (B_FALSE);
11983 		}
11984 	}
11985 
11986 	/* Initiate IPPF processing for fastpath UDP */
11987 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11988 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11989 		if (*mpp == NULL) {
11990 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11991 			    "deferred/dropped during IPPF processing\n"));
11992 			return (B_FALSE);
11993 		}
11994 	}
11995 	/*
11996 	 * Remove 0-spi if it's 0, or move everything behind
11997 	 * the UDP header over it and forward to ESP via
11998 	 * ip_proto_input().
11999 	 */
12000 	if (udp->udp_nat_t_endpoint) {
12001 		if (mctl_present) {
12002 			/* mctl_present *shouldn't* happen. */
12003 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12004 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12005 			    &ipss->ipsec_dropper);
12006 			*first_mpp = NULL;
12007 			return (B_FALSE);
12008 		}
12009 
12010 		/* "ill" is "recv_ill" in actuality. */
12011 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12012 			return (B_FALSE);
12013 
12014 		/* Else continue like a normal UDP packet. */
12015 	}
12016 
12017 	/*
12018 	 * We make the checks as below since we are in the fast path
12019 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12020 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12021 	 */
12022 	if (connp->conn_recvif || connp->conn_recvslla ||
12023 	    connp->conn_ip_recvpktinfo) {
12024 		if (connp->conn_recvif) {
12025 			in_flags = IPF_RECVIF;
12026 		}
12027 		/*
12028 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12029 		 * so the flag passed to ip_add_info is based on IP version
12030 		 * of connp.
12031 		 */
12032 		if (connp->conn_ip_recvpktinfo) {
12033 			if (connp->conn_af_isv6) {
12034 				/*
12035 				 * V6 only needs index
12036 				 */
12037 				in_flags |= IPF_RECVIF;
12038 			} else {
12039 				/*
12040 				 * V4 needs index + matching address.
12041 				 */
12042 				in_flags |= IPF_RECVADDR;
12043 			}
12044 		}
12045 		if (connp->conn_recvslla) {
12046 			in_flags |= IPF_RECVSLLA;
12047 		}
12048 		/*
12049 		 * since in_flags are being set ill will be
12050 		 * referenced in ip_add_info, so it better not
12051 		 * be NULL.
12052 		 */
12053 		/*
12054 		 * the actual data will be contained in b_cont
12055 		 * upon successful return of the following call.
12056 		 * If the call fails then the original mblk is
12057 		 * returned.
12058 		 */
12059 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12060 		    ipst);
12061 	}
12062 
12063 	return (B_TRUE);
12064 }
12065 
12066 /*
12067  * Fragmentation reassembly.  Each ILL has a hash table for
12068  * queuing packets undergoing reassembly for all IPIFs
12069  * associated with the ILL.  The hash is based on the packet
12070  * IP ident field.  The ILL frag hash table was allocated
12071  * as a timer block at the time the ILL was created.  Whenever
12072  * there is anything on the reassembly queue, the timer will
12073  * be running.  Returns B_TRUE if successful else B_FALSE;
12074  * frees mp on failure.
12075  */
12076 static boolean_t
12077 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12078     uint32_t *cksum_val, uint16_t *cksum_flags)
12079 {
12080 	uint32_t	frag_offset_flags;
12081 	mblk_t		*mp = *mpp;
12082 	mblk_t		*t_mp;
12083 	ipaddr_t	dst;
12084 	uint8_t		proto = ipha->ipha_protocol;
12085 	uint32_t	sum_val;
12086 	uint16_t	sum_flags;
12087 	ipf_t		*ipf;
12088 	ipf_t		**ipfp;
12089 	ipfb_t		*ipfb;
12090 	uint16_t	ident;
12091 	uint32_t	offset;
12092 	ipaddr_t	src;
12093 	uint_t		hdr_length;
12094 	uint32_t	end;
12095 	mblk_t		*mp1;
12096 	mblk_t		*tail_mp;
12097 	size_t		count;
12098 	size_t		msg_len;
12099 	uint8_t		ecn_info = 0;
12100 	uint32_t	packet_size;
12101 	boolean_t	pruned = B_FALSE;
12102 	ip_stack_t *ipst = ill->ill_ipst;
12103 
12104 	if (cksum_val != NULL)
12105 		*cksum_val = 0;
12106 	if (cksum_flags != NULL)
12107 		*cksum_flags = 0;
12108 
12109 	/*
12110 	 * Drop the fragmented as early as possible, if
12111 	 * we don't have resource(s) to re-assemble.
12112 	 */
12113 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12114 		freemsg(mp);
12115 		return (B_FALSE);
12116 	}
12117 
12118 	/* Check for fragmentation offset; return if there's none */
12119 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12120 	    (IPH_MF | IPH_OFFSET)) == 0)
12121 		return (B_TRUE);
12122 
12123 	/*
12124 	 * We utilize hardware computed checksum info only for UDP since
12125 	 * IP fragmentation is a normal occurrence for the protocol.  In
12126 	 * addition, checksum offload support for IP fragments carrying
12127 	 * UDP payload is commonly implemented across network adapters.
12128 	 */
12129 	ASSERT(recv_ill != NULL);
12130 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12131 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12132 		mblk_t *mp1 = mp->b_cont;
12133 		int32_t len;
12134 
12135 		/* Record checksum information from the packet */
12136 		sum_val = (uint32_t)DB_CKSUM16(mp);
12137 		sum_flags = DB_CKSUMFLAGS(mp);
12138 
12139 		/* IP payload offset from beginning of mblk */
12140 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12141 
12142 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12143 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12144 		    offset >= DB_CKSUMSTART(mp) &&
12145 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12146 			uint32_t adj;
12147 			/*
12148 			 * Partial checksum has been calculated by hardware
12149 			 * and attached to the packet; in addition, any
12150 			 * prepended extraneous data is even byte aligned.
12151 			 * If any such data exists, we adjust the checksum;
12152 			 * this would also handle any postpended data.
12153 			 */
12154 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12155 			    mp, mp1, len, adj);
12156 
12157 			/* One's complement subtract extraneous checksum */
12158 			if (adj >= sum_val)
12159 				sum_val = ~(adj - sum_val) & 0xFFFF;
12160 			else
12161 				sum_val -= adj;
12162 		}
12163 	} else {
12164 		sum_val = 0;
12165 		sum_flags = 0;
12166 	}
12167 
12168 	/* Clear hardware checksumming flag */
12169 	DB_CKSUMFLAGS(mp) = 0;
12170 
12171 	ident = ipha->ipha_ident;
12172 	offset = (frag_offset_flags << 3) & 0xFFFF;
12173 	src = ipha->ipha_src;
12174 	dst = ipha->ipha_dst;
12175 	hdr_length = IPH_HDR_LENGTH(ipha);
12176 	end = ntohs(ipha->ipha_length) - hdr_length;
12177 
12178 	/* If end == 0 then we have a packet with no data, so just free it */
12179 	if (end == 0) {
12180 		freemsg(mp);
12181 		return (B_FALSE);
12182 	}
12183 
12184 	/* Record the ECN field info. */
12185 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12186 	if (offset != 0) {
12187 		/*
12188 		 * If this isn't the first piece, strip the header, and
12189 		 * add the offset to the end value.
12190 		 */
12191 		mp->b_rptr += hdr_length;
12192 		end += offset;
12193 	}
12194 
12195 	msg_len = MBLKSIZE(mp);
12196 	tail_mp = mp;
12197 	while (tail_mp->b_cont != NULL) {
12198 		tail_mp = tail_mp->b_cont;
12199 		msg_len += MBLKSIZE(tail_mp);
12200 	}
12201 
12202 	/* If the reassembly list for this ILL will get too big, prune it */
12203 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12204 	    ipst->ips_ip_reass_queue_bytes) {
12205 		ill_frag_prune(ill,
12206 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12207 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12208 		pruned = B_TRUE;
12209 	}
12210 
12211 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12212 	mutex_enter(&ipfb->ipfb_lock);
12213 
12214 	ipfp = &ipfb->ipfb_ipf;
12215 	/* Try to find an existing fragment queue for this packet. */
12216 	for (;;) {
12217 		ipf = ipfp[0];
12218 		if (ipf != NULL) {
12219 			/*
12220 			 * It has to match on ident and src/dst address.
12221 			 */
12222 			if (ipf->ipf_ident == ident &&
12223 			    ipf->ipf_src == src &&
12224 			    ipf->ipf_dst == dst &&
12225 			    ipf->ipf_protocol == proto) {
12226 				/*
12227 				 * If we have received too many
12228 				 * duplicate fragments for this packet
12229 				 * free it.
12230 				 */
12231 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12232 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12233 					freemsg(mp);
12234 					mutex_exit(&ipfb->ipfb_lock);
12235 					return (B_FALSE);
12236 				}
12237 				/* Found it. */
12238 				break;
12239 			}
12240 			ipfp = &ipf->ipf_hash_next;
12241 			continue;
12242 		}
12243 
12244 		/*
12245 		 * If we pruned the list, do we want to store this new
12246 		 * fragment?. We apply an optimization here based on the
12247 		 * fact that most fragments will be received in order.
12248 		 * So if the offset of this incoming fragment is zero,
12249 		 * it is the first fragment of a new packet. We will
12250 		 * keep it.  Otherwise drop the fragment, as we have
12251 		 * probably pruned the packet already (since the
12252 		 * packet cannot be found).
12253 		 */
12254 		if (pruned && offset != 0) {
12255 			mutex_exit(&ipfb->ipfb_lock);
12256 			freemsg(mp);
12257 			return (B_FALSE);
12258 		}
12259 
12260 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12261 			/*
12262 			 * Too many fragmented packets in this hash
12263 			 * bucket. Free the oldest.
12264 			 */
12265 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12266 		}
12267 
12268 		/* New guy.  Allocate a frag message. */
12269 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12270 		if (mp1 == NULL) {
12271 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12272 			freemsg(mp);
12273 reass_done:
12274 			mutex_exit(&ipfb->ipfb_lock);
12275 			return (B_FALSE);
12276 		}
12277 
12278 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12279 		mp1->b_cont = mp;
12280 
12281 		/* Initialize the fragment header. */
12282 		ipf = (ipf_t *)mp1->b_rptr;
12283 		ipf->ipf_mp = mp1;
12284 		ipf->ipf_ptphn = ipfp;
12285 		ipfp[0] = ipf;
12286 		ipf->ipf_hash_next = NULL;
12287 		ipf->ipf_ident = ident;
12288 		ipf->ipf_protocol = proto;
12289 		ipf->ipf_src = src;
12290 		ipf->ipf_dst = dst;
12291 		ipf->ipf_nf_hdr_len = 0;
12292 		/* Record reassembly start time. */
12293 		ipf->ipf_timestamp = gethrestime_sec();
12294 		/* Record ipf generation and account for frag header */
12295 		ipf->ipf_gen = ill->ill_ipf_gen++;
12296 		ipf->ipf_count = MBLKSIZE(mp1);
12297 		ipf->ipf_last_frag_seen = B_FALSE;
12298 		ipf->ipf_ecn = ecn_info;
12299 		ipf->ipf_num_dups = 0;
12300 		ipfb->ipfb_frag_pkts++;
12301 		ipf->ipf_checksum = 0;
12302 		ipf->ipf_checksum_flags = 0;
12303 
12304 		/* Store checksum value in fragment header */
12305 		if (sum_flags != 0) {
12306 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12307 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12308 			ipf->ipf_checksum = sum_val;
12309 			ipf->ipf_checksum_flags = sum_flags;
12310 		}
12311 
12312 		/*
12313 		 * We handle reassembly two ways.  In the easy case,
12314 		 * where all the fragments show up in order, we do
12315 		 * minimal bookkeeping, and just clip new pieces on
12316 		 * the end.  If we ever see a hole, then we go off
12317 		 * to ip_reassemble which has to mark the pieces and
12318 		 * keep track of the number of holes, etc.  Obviously,
12319 		 * the point of having both mechanisms is so we can
12320 		 * handle the easy case as efficiently as possible.
12321 		 */
12322 		if (offset == 0) {
12323 			/* Easy case, in-order reassembly so far. */
12324 			ipf->ipf_count += msg_len;
12325 			ipf->ipf_tail_mp = tail_mp;
12326 			/*
12327 			 * Keep track of next expected offset in
12328 			 * ipf_end.
12329 			 */
12330 			ipf->ipf_end = end;
12331 			ipf->ipf_nf_hdr_len = hdr_length;
12332 		} else {
12333 			/* Hard case, hole at the beginning. */
12334 			ipf->ipf_tail_mp = NULL;
12335 			/*
12336 			 * ipf_end == 0 means that we have given up
12337 			 * on easy reassembly.
12338 			 */
12339 			ipf->ipf_end = 0;
12340 
12341 			/* Forget checksum offload from now on */
12342 			ipf->ipf_checksum_flags = 0;
12343 
12344 			/*
12345 			 * ipf_hole_cnt is set by ip_reassemble.
12346 			 * ipf_count is updated by ip_reassemble.
12347 			 * No need to check for return value here
12348 			 * as we don't expect reassembly to complete
12349 			 * or fail for the first fragment itself.
12350 			 */
12351 			(void) ip_reassemble(mp, ipf,
12352 			    (frag_offset_flags & IPH_OFFSET) << 3,
12353 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12354 		}
12355 		/* Update per ipfb and ill byte counts */
12356 		ipfb->ipfb_count += ipf->ipf_count;
12357 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12358 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12359 		/* If the frag timer wasn't already going, start it. */
12360 		mutex_enter(&ill->ill_lock);
12361 		ill_frag_timer_start(ill);
12362 		mutex_exit(&ill->ill_lock);
12363 		goto reass_done;
12364 	}
12365 
12366 	/*
12367 	 * If the packet's flag has changed (it could be coming up
12368 	 * from an interface different than the previous, therefore
12369 	 * possibly different checksum capability), then forget about
12370 	 * any stored checksum states.  Otherwise add the value to
12371 	 * the existing one stored in the fragment header.
12372 	 */
12373 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12374 		sum_val += ipf->ipf_checksum;
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 	} else if (ipf->ipf_checksum_flags != 0) {
12379 		/* Forget checksum offload from now on */
12380 		ipf->ipf_checksum_flags = 0;
12381 	}
12382 
12383 	/*
12384 	 * We have a new piece of a datagram which is already being
12385 	 * reassembled.  Update the ECN info if all IP fragments
12386 	 * are ECN capable.  If there is one which is not, clear
12387 	 * all the info.  If there is at least one which has CE
12388 	 * code point, IP needs to report that up to transport.
12389 	 */
12390 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12391 		if (ecn_info == IPH_ECN_CE)
12392 			ipf->ipf_ecn = IPH_ECN_CE;
12393 	} else {
12394 		ipf->ipf_ecn = IPH_ECN_NECT;
12395 	}
12396 	if (offset && ipf->ipf_end == offset) {
12397 		/* The new fragment fits at the end */
12398 		ipf->ipf_tail_mp->b_cont = mp;
12399 		/* Update the byte count */
12400 		ipf->ipf_count += msg_len;
12401 		/* Update per ipfb and ill byte counts */
12402 		ipfb->ipfb_count += msg_len;
12403 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12404 		atomic_add_32(&ill->ill_frag_count, msg_len);
12405 		if (frag_offset_flags & IPH_MF) {
12406 			/* More to come. */
12407 			ipf->ipf_end = end;
12408 			ipf->ipf_tail_mp = tail_mp;
12409 			goto reass_done;
12410 		}
12411 	} else {
12412 		/* Go do the hard cases. */
12413 		int ret;
12414 
12415 		if (offset == 0)
12416 			ipf->ipf_nf_hdr_len = hdr_length;
12417 
12418 		/* Save current byte count */
12419 		count = ipf->ipf_count;
12420 		ret = ip_reassemble(mp, ipf,
12421 		    (frag_offset_flags & IPH_OFFSET) << 3,
12422 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12423 		/* Count of bytes added and subtracted (freeb()ed) */
12424 		count = ipf->ipf_count - count;
12425 		if (count) {
12426 			/* Update per ipfb and ill byte counts */
12427 			ipfb->ipfb_count += count;
12428 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12429 			atomic_add_32(&ill->ill_frag_count, count);
12430 		}
12431 		if (ret == IP_REASS_PARTIAL) {
12432 			goto reass_done;
12433 		} else if (ret == IP_REASS_FAILED) {
12434 			/* Reassembly failed. Free up all resources */
12435 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12436 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12437 				IP_REASS_SET_START(t_mp, 0);
12438 				IP_REASS_SET_END(t_mp, 0);
12439 			}
12440 			freemsg(mp);
12441 			goto reass_done;
12442 		}
12443 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12444 	}
12445 	/*
12446 	 * We have completed reassembly.  Unhook the frag header from
12447 	 * the reassembly list.
12448 	 *
12449 	 * Before we free the frag header, record the ECN info
12450 	 * to report back to the transport.
12451 	 */
12452 	ecn_info = ipf->ipf_ecn;
12453 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12454 	ipfp = ipf->ipf_ptphn;
12455 
12456 	/* We need to supply these to caller */
12457 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12458 		sum_val = ipf->ipf_checksum;
12459 	else
12460 		sum_val = 0;
12461 
12462 	mp1 = ipf->ipf_mp;
12463 	count = ipf->ipf_count;
12464 	ipf = ipf->ipf_hash_next;
12465 	if (ipf != NULL)
12466 		ipf->ipf_ptphn = ipfp;
12467 	ipfp[0] = ipf;
12468 	atomic_add_32(&ill->ill_frag_count, -count);
12469 	ASSERT(ipfb->ipfb_count >= count);
12470 	ipfb->ipfb_count -= count;
12471 	ipfb->ipfb_frag_pkts--;
12472 	mutex_exit(&ipfb->ipfb_lock);
12473 	/* Ditch the frag header. */
12474 	mp = mp1->b_cont;
12475 
12476 	freeb(mp1);
12477 
12478 	/* Restore original IP length in header. */
12479 	packet_size = (uint32_t)msgdsize(mp);
12480 	if (packet_size > IP_MAXPACKET) {
12481 		freemsg(mp);
12482 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12483 		return (B_FALSE);
12484 	}
12485 
12486 	if (DB_REF(mp) > 1) {
12487 		mblk_t *mp2 = copymsg(mp);
12488 
12489 		freemsg(mp);
12490 		if (mp2 == NULL) {
12491 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12492 			return (B_FALSE);
12493 		}
12494 		mp = mp2;
12495 	}
12496 	ipha = (ipha_t *)mp->b_rptr;
12497 
12498 	ipha->ipha_length = htons((uint16_t)packet_size);
12499 	/* We're now complete, zip the frag state */
12500 	ipha->ipha_fragment_offset_and_flags = 0;
12501 	/* Record the ECN info. */
12502 	ipha->ipha_type_of_service &= 0xFC;
12503 	ipha->ipha_type_of_service |= ecn_info;
12504 	*mpp = mp;
12505 
12506 	/* Reassembly is successful; return checksum information if needed */
12507 	if (cksum_val != NULL)
12508 		*cksum_val = sum_val;
12509 	if (cksum_flags != NULL)
12510 		*cksum_flags = sum_flags;
12511 
12512 	return (B_TRUE);
12513 }
12514 
12515 /*
12516  * Perform ip header check sum update local options.
12517  * return B_TRUE if all is well, else return B_FALSE and release
12518  * the mp. caller is responsible for decrementing ire ref cnt.
12519  */
12520 static boolean_t
12521 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12522     ip_stack_t *ipst)
12523 {
12524 	mblk_t		*first_mp;
12525 	boolean_t	mctl_present;
12526 	uint16_t	sum;
12527 
12528 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12529 	/*
12530 	 * Don't do the checksum if it has gone through AH/ESP
12531 	 * processing.
12532 	 */
12533 	if (!mctl_present) {
12534 		sum = ip_csum_hdr(ipha);
12535 		if (sum != 0) {
12536 			if (ill != NULL) {
12537 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12538 			} else {
12539 				BUMP_MIB(&ipst->ips_ip_mib,
12540 				    ipIfStatsInCksumErrs);
12541 			}
12542 			freemsg(first_mp);
12543 			return (B_FALSE);
12544 		}
12545 	}
12546 
12547 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12548 		if (mctl_present)
12549 			freeb(first_mp);
12550 		return (B_FALSE);
12551 	}
12552 
12553 	return (B_TRUE);
12554 }
12555 
12556 /*
12557  * All udp packet are delivered to the local host via this routine.
12558  */
12559 void
12560 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12561     ill_t *recv_ill)
12562 {
12563 	uint32_t	sum;
12564 	uint32_t	u1;
12565 	boolean_t	mctl_present;
12566 	conn_t		*connp;
12567 	mblk_t		*first_mp;
12568 	uint16_t	*up;
12569 	ill_t		*ill = (ill_t *)q->q_ptr;
12570 	uint16_t	reass_hck_flags = 0;
12571 	ip_stack_t	*ipst;
12572 
12573 	ASSERT(recv_ill != NULL);
12574 	ipst = recv_ill->ill_ipst;
12575 
12576 #define	rptr    ((uchar_t *)ipha)
12577 
12578 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12579 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12580 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12581 	ASSERT(ill != NULL);
12582 
12583 	/*
12584 	 * FAST PATH for udp packets
12585 	 */
12586 
12587 	/* u1 is # words of IP options */
12588 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12589 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12590 
12591 	/* IP options present */
12592 	if (u1 != 0)
12593 		goto ipoptions;
12594 
12595 	/* Check the IP header checksum.  */
12596 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12597 		/* Clear the IP header h/w cksum flag */
12598 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12599 	} else if (!mctl_present) {
12600 		/*
12601 		 * Don't verify header checksum if this packet is coming
12602 		 * back from AH/ESP as we already did it.
12603 		 */
12604 #define	uph	((uint16_t *)ipha)
12605 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12606 		    uph[6] + uph[7] + uph[8] + uph[9];
12607 #undef	uph
12608 		/* finish doing IP checksum */
12609 		sum = (sum & 0xFFFF) + (sum >> 16);
12610 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12611 		if (sum != 0 && sum != 0xFFFF) {
12612 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12613 			freemsg(first_mp);
12614 			return;
12615 		}
12616 	}
12617 
12618 	/*
12619 	 * Count for SNMP of inbound packets for ire.
12620 	 * if mctl is present this might be a secure packet and
12621 	 * has already been counted for in ip_proto_input().
12622 	 */
12623 	if (!mctl_present) {
12624 		UPDATE_IB_PKT_COUNT(ire);
12625 		ire->ire_last_used_time = lbolt;
12626 	}
12627 
12628 	/* packet part of fragmented IP packet? */
12629 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12630 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12631 		goto fragmented;
12632 	}
12633 
12634 	/* u1 = IP header length (20 bytes) */
12635 	u1 = IP_SIMPLE_HDR_LENGTH;
12636 
12637 	/* packet does not contain complete IP & UDP headers */
12638 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12639 		goto udppullup;
12640 
12641 	/* up points to UDP header */
12642 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12643 #define	iphs    ((uint16_t *)ipha)
12644 
12645 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12646 	if (up[3] != 0) {
12647 		mblk_t *mp1 = mp->b_cont;
12648 		boolean_t cksum_err;
12649 		uint16_t hck_flags = 0;
12650 
12651 		/* Pseudo-header checksum */
12652 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12653 		    iphs[9] + up[2];
12654 
12655 		/*
12656 		 * Revert to software checksum calculation if the interface
12657 		 * isn't capable of checksum offload or if IPsec is present.
12658 		 */
12659 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12660 			hck_flags = DB_CKSUMFLAGS(mp);
12661 
12662 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12663 			IP_STAT(ipst, ip_in_sw_cksum);
12664 
12665 		IP_CKSUM_RECV(hck_flags, u1,
12666 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12667 		    (int32_t)((uchar_t *)up - rptr),
12668 		    mp, mp1, cksum_err);
12669 
12670 		if (cksum_err) {
12671 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12672 			if (hck_flags & HCK_FULLCKSUM)
12673 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12674 			else if (hck_flags & HCK_PARTIALCKSUM)
12675 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12676 			else
12677 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12678 
12679 			freemsg(first_mp);
12680 			return;
12681 		}
12682 	}
12683 
12684 	/* Non-fragmented broadcast or multicast packet? */
12685 	if (ire->ire_type == IRE_BROADCAST)
12686 		goto udpslowpath;
12687 
12688 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12689 	    ire->ire_zoneid, ipst)) != NULL) {
12690 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12691 		IP_STAT(ipst, ip_udp_fast_path);
12692 
12693 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12694 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12695 			freemsg(mp);
12696 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12697 		} else {
12698 			if (!mctl_present) {
12699 				BUMP_MIB(ill->ill_ip_mib,
12700 				    ipIfStatsHCInDelivers);
12701 			}
12702 			/*
12703 			 * mp and first_mp can change.
12704 			 */
12705 			if (ip_udp_check(q, connp, recv_ill,
12706 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12707 				/* Send it upstream */
12708 				(connp->conn_recv)(connp, mp, NULL);
12709 			}
12710 		}
12711 		/*
12712 		 * freeb() cannot deal with null mblk being passed
12713 		 * in and first_mp can be set to null in the call
12714 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12715 		 */
12716 		if (mctl_present && first_mp != NULL) {
12717 			freeb(first_mp);
12718 		}
12719 		CONN_DEC_REF(connp);
12720 		return;
12721 	}
12722 
12723 	/*
12724 	 * if we got here we know the packet is not fragmented and
12725 	 * has no options. The classifier could not find a conn_t and
12726 	 * most likely its an icmp packet so send it through slow path.
12727 	 */
12728 
12729 	goto udpslowpath;
12730 
12731 ipoptions:
12732 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12733 		goto slow_done;
12734 	}
12735 
12736 	UPDATE_IB_PKT_COUNT(ire);
12737 	ire->ire_last_used_time = lbolt;
12738 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12739 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12740 fragmented:
12741 		/*
12742 		 * "sum" and "reass_hck_flags" are non-zero if the
12743 		 * reassembled packet has a valid hardware computed
12744 		 * checksum information associated with it.
12745 		 */
12746 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12747 		    &reass_hck_flags)) {
12748 			goto slow_done;
12749 		}
12750 
12751 		/*
12752 		 * Make sure that first_mp points back to mp as
12753 		 * the mp we came in with could have changed in
12754 		 * ip_rput_fragment().
12755 		 */
12756 		ASSERT(!mctl_present);
12757 		ipha = (ipha_t *)mp->b_rptr;
12758 		first_mp = mp;
12759 	}
12760 
12761 	/* Now we have a complete datagram, destined for this machine. */
12762 	u1 = IPH_HDR_LENGTH(ipha);
12763 	/* Pull up the UDP header, if necessary. */
12764 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12765 udppullup:
12766 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12767 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12768 			freemsg(first_mp);
12769 			goto slow_done;
12770 		}
12771 		ipha = (ipha_t *)mp->b_rptr;
12772 	}
12773 
12774 	/*
12775 	 * Validate the checksum for the reassembled packet; for the
12776 	 * pullup case we calculate the payload checksum in software.
12777 	 */
12778 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12779 	if (up[3] != 0) {
12780 		boolean_t cksum_err;
12781 
12782 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12783 			IP_STAT(ipst, ip_in_sw_cksum);
12784 
12785 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12786 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12787 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12788 		    iphs[9] + up[2], sum, cksum_err);
12789 
12790 		if (cksum_err) {
12791 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12792 
12793 			if (reass_hck_flags & HCK_FULLCKSUM)
12794 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12795 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12796 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12797 			else
12798 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12799 
12800 			freemsg(first_mp);
12801 			goto slow_done;
12802 		}
12803 	}
12804 udpslowpath:
12805 
12806 	/* Clear hardware checksum flag to be safe */
12807 	DB_CKSUMFLAGS(mp) = 0;
12808 
12809 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12810 	    (ire->ire_type == IRE_BROADCAST),
12811 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12812 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12813 
12814 slow_done:
12815 	IP_STAT(ipst, ip_udp_slow_path);
12816 	return;
12817 
12818 #undef  iphs
12819 #undef  rptr
12820 }
12821 
12822 static boolean_t
12823 ip_iptun_input(mblk_t *ipsec_mp, mblk_t *data_mp, ipha_t *ipha, ill_t *ill,
12824     ire_t *ire, ip_stack_t *ipst)
12825 {
12826 	conn_t	*connp;
12827 
12828 	ASSERT(ipsec_mp == NULL || ipsec_mp->b_cont == data_mp);
12829 
12830 	if ((connp = ipcl_classify_v4(data_mp, ipha->ipha_protocol,
12831 	    IP_SIMPLE_HDR_LENGTH, ire->ire_zoneid, ipst)) != NULL) {
12832 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12833 		connp->conn_recv(connp, ipsec_mp != NULL ? ipsec_mp : data_mp,
12834 		    NULL);
12835 		CONN_DEC_REF(connp);
12836 		return (B_TRUE);
12837 	}
12838 	return (B_FALSE);
12839 }
12840 
12841 /* ARGSUSED */
12842 static mblk_t *
12843 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12844     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12845     ill_rx_ring_t *ill_ring)
12846 {
12847 	conn_t		*connp;
12848 	uint32_t	sum;
12849 	uint32_t	u1;
12850 	uint16_t	*up;
12851 	int		offset;
12852 	ssize_t		len;
12853 	mblk_t		*mp1;
12854 	boolean_t	syn_present = B_FALSE;
12855 	tcph_t		*tcph;
12856 	uint_t		tcph_flags;
12857 	uint_t		ip_hdr_len;
12858 	ill_t		*ill = (ill_t *)q->q_ptr;
12859 	zoneid_t	zoneid = ire->ire_zoneid;
12860 	boolean_t	cksum_err;
12861 	uint16_t	hck_flags = 0;
12862 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12863 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12864 
12865 #define	rptr	((uchar_t *)ipha)
12866 
12867 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12868 	ASSERT(ill != NULL);
12869 
12870 	/*
12871 	 * FAST PATH for tcp packets
12872 	 */
12873 
12874 	/* u1 is # words of IP options */
12875 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12876 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12877 
12878 	/* IP options present */
12879 	if (u1) {
12880 		goto ipoptions;
12881 	} else if (!mctl_present) {
12882 		/* Check the IP header checksum.  */
12883 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12884 			/* Clear the IP header h/w cksum flag */
12885 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12886 		} else if (!mctl_present) {
12887 			/*
12888 			 * Don't verify header checksum if this packet
12889 			 * is coming back from AH/ESP as we already did it.
12890 			 */
12891 #define	uph	((uint16_t *)ipha)
12892 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12893 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12894 #undef	uph
12895 			/* finish doing IP checksum */
12896 			sum = (sum & 0xFFFF) + (sum >> 16);
12897 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12898 			if (sum != 0 && sum != 0xFFFF) {
12899 				BUMP_MIB(ill->ill_ip_mib,
12900 				    ipIfStatsInCksumErrs);
12901 				goto error;
12902 			}
12903 		}
12904 	}
12905 
12906 	if (!mctl_present) {
12907 		UPDATE_IB_PKT_COUNT(ire);
12908 		ire->ire_last_used_time = lbolt;
12909 	}
12910 
12911 	/* packet part of fragmented IP packet? */
12912 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12913 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12914 		goto fragmented;
12915 	}
12916 
12917 	/* u1 = IP header length (20 bytes) */
12918 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12919 
12920 	/* does packet contain IP+TCP headers? */
12921 	len = mp->b_wptr - rptr;
12922 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12923 		IP_STAT(ipst, ip_tcppullup);
12924 		goto tcppullup;
12925 	}
12926 
12927 	/* TCP options present? */
12928 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12929 
12930 	/*
12931 	 * If options need to be pulled up, then goto tcpoptions.
12932 	 * otherwise we are still in the fast path
12933 	 */
12934 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12935 		IP_STAT(ipst, ip_tcpoptions);
12936 		goto tcpoptions;
12937 	}
12938 
12939 	/* multiple mblks of tcp data? */
12940 	if ((mp1 = mp->b_cont) != NULL) {
12941 		IP_STAT(ipst, ip_multipkttcp);
12942 		len += msgdsize(mp1);
12943 	}
12944 
12945 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12946 
12947 	/* part of pseudo checksum */
12948 
12949 	/* TCP datagram length */
12950 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12951 
12952 #define	iphs    ((uint16_t *)ipha)
12953 
12954 #ifdef	_BIG_ENDIAN
12955 	u1 += IPPROTO_TCP;
12956 #else
12957 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12958 #endif
12959 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12960 
12961 	/*
12962 	 * Revert to software checksum calculation if the interface
12963 	 * isn't capable of checksum offload or if IPsec is present.
12964 	 */
12965 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12966 		hck_flags = DB_CKSUMFLAGS(mp);
12967 
12968 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12969 		IP_STAT(ipst, ip_in_sw_cksum);
12970 
12971 	IP_CKSUM_RECV(hck_flags, u1,
12972 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12973 	    (int32_t)((uchar_t *)up - rptr),
12974 	    mp, mp1, cksum_err);
12975 
12976 	if (cksum_err) {
12977 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12978 
12979 		if (hck_flags & HCK_FULLCKSUM)
12980 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12981 		else if (hck_flags & HCK_PARTIALCKSUM)
12982 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12983 		else
12984 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12985 
12986 		goto error;
12987 	}
12988 
12989 try_again:
12990 
12991 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12992 	    zoneid, ipst)) == NULL) {
12993 		/* Send the TH_RST */
12994 		goto no_conn;
12995 	}
12996 
12997 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12998 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
12999 
13000 	/*
13001 	 * TCP FAST PATH for AF_INET socket.
13002 	 *
13003 	 * TCP fast path to avoid extra work. An AF_INET socket type
13004 	 * does not have facility to receive extra information via
13005 	 * ip_process or ip_add_info. Also, when the connection was
13006 	 * established, we made a check if this connection is impacted
13007 	 * by any global IPsec policy or per connection policy (a
13008 	 * policy that comes in effect later will not apply to this
13009 	 * connection). Since all this can be determined at the
13010 	 * connection establishment time, a quick check of flags
13011 	 * can avoid extra work.
13012 	 */
13013 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13014 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13015 		ASSERT(first_mp == mp);
13016 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13017 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13018 			SET_SQUEUE(mp, tcp_rput_data, connp);
13019 			return (mp);
13020 		}
13021 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13022 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13023 		SET_SQUEUE(mp, tcp_input, connp);
13024 		return (mp);
13025 	}
13026 
13027 	if (tcph_flags == TH_SYN) {
13028 		if (IPCL_IS_TCP(connp)) {
13029 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13030 			DB_CKSUMSTART(mp) =
13031 			    (intptr_t)ip_squeue_get(ill_ring);
13032 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13033 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13034 				BUMP_MIB(ill->ill_ip_mib,
13035 				    ipIfStatsHCInDelivers);
13036 				SET_SQUEUE(mp, connp->conn_recv, connp);
13037 				return (mp);
13038 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13039 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13040 				BUMP_MIB(ill->ill_ip_mib,
13041 				    ipIfStatsHCInDelivers);
13042 				ip_squeue_enter_unbound++;
13043 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13044 				    connp);
13045 				return (mp);
13046 			}
13047 			syn_present = B_TRUE;
13048 		}
13049 	}
13050 
13051 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13052 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13053 
13054 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13055 		/* No need to send this packet to TCP */
13056 		if ((flags & TH_RST) || (flags & TH_URG)) {
13057 			CONN_DEC_REF(connp);
13058 			freemsg(first_mp);
13059 			return (NULL);
13060 		}
13061 		if (flags & TH_ACK) {
13062 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13063 			    ipst->ips_netstack->netstack_tcp, connp);
13064 			CONN_DEC_REF(connp);
13065 			return (NULL);
13066 		}
13067 
13068 		CONN_DEC_REF(connp);
13069 		freemsg(first_mp);
13070 		return (NULL);
13071 	}
13072 
13073 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13074 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13075 		    ipha, NULL, mctl_present);
13076 		if (first_mp == NULL) {
13077 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13078 			CONN_DEC_REF(connp);
13079 			return (NULL);
13080 		}
13081 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13082 			ASSERT(syn_present);
13083 			if (mctl_present) {
13084 				ASSERT(first_mp != mp);
13085 				first_mp->b_datap->db_struioflag |=
13086 				    STRUIO_POLICY;
13087 			} else {
13088 				ASSERT(first_mp == mp);
13089 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13090 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13091 			}
13092 		} else {
13093 			/*
13094 			 * Discard first_mp early since we're dealing with a
13095 			 * fully-connected conn_t and tcp doesn't do policy in
13096 			 * this case.
13097 			 */
13098 			if (mctl_present) {
13099 				freeb(first_mp);
13100 				mctl_present = B_FALSE;
13101 			}
13102 			first_mp = mp;
13103 		}
13104 	}
13105 
13106 	/* Initiate IPPF processing for fastpath */
13107 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13108 		uint32_t	ill_index;
13109 
13110 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13111 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13112 		if (mp == NULL) {
13113 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13114 			    "deferred/dropped during IPPF processing\n"));
13115 			CONN_DEC_REF(connp);
13116 			if (mctl_present)
13117 				freeb(first_mp);
13118 			return (NULL);
13119 		} else if (mctl_present) {
13120 			/*
13121 			 * ip_process might return a new mp.
13122 			 */
13123 			ASSERT(first_mp != mp);
13124 			first_mp->b_cont = mp;
13125 		} else {
13126 			first_mp = mp;
13127 		}
13128 
13129 	}
13130 
13131 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13132 		/*
13133 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13134 		 * make sure IPF_RECVIF is passed to ip_add_info.
13135 		 */
13136 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13137 		    IPCL_ZONEID(connp), ipst);
13138 		if (mp == NULL) {
13139 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13140 			CONN_DEC_REF(connp);
13141 			if (mctl_present)
13142 				freeb(first_mp);
13143 			return (NULL);
13144 		} else if (mctl_present) {
13145 			/*
13146 			 * ip_add_info might return a new mp.
13147 			 */
13148 			ASSERT(first_mp != mp);
13149 			first_mp->b_cont = mp;
13150 		} else {
13151 			first_mp = mp;
13152 		}
13153 	}
13154 
13155 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13156 	if (IPCL_IS_TCP(connp)) {
13157 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13158 		return (first_mp);
13159 	} else {
13160 		/* SOCK_RAW, IPPROTO_TCP case */
13161 		(connp->conn_recv)(connp, first_mp, NULL);
13162 		CONN_DEC_REF(connp);
13163 		return (NULL);
13164 	}
13165 
13166 no_conn:
13167 	/* Initiate IPPf processing, if needed. */
13168 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13169 		uint32_t ill_index;
13170 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13171 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13172 		if (first_mp == NULL) {
13173 			return (NULL);
13174 		}
13175 	}
13176 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13177 
13178 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13179 	    ipst->ips_netstack->netstack_tcp, NULL);
13180 	return (NULL);
13181 ipoptions:
13182 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13183 		goto slow_done;
13184 	}
13185 
13186 	UPDATE_IB_PKT_COUNT(ire);
13187 	ire->ire_last_used_time = lbolt;
13188 
13189 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13190 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13191 fragmented:
13192 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13193 			if (mctl_present)
13194 				freeb(first_mp);
13195 			goto slow_done;
13196 		}
13197 		/*
13198 		 * Make sure that first_mp points back to mp as
13199 		 * the mp we came in with could have changed in
13200 		 * ip_rput_fragment().
13201 		 */
13202 		ASSERT(!mctl_present);
13203 		ipha = (ipha_t *)mp->b_rptr;
13204 		first_mp = mp;
13205 	}
13206 
13207 	/* Now we have a complete datagram, destined for this machine. */
13208 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13209 
13210 	len = mp->b_wptr - mp->b_rptr;
13211 	/* Pull up a minimal TCP header, if necessary. */
13212 	if (len < (u1 + 20)) {
13213 tcppullup:
13214 		if (!pullupmsg(mp, u1 + 20)) {
13215 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13216 			goto error;
13217 		}
13218 		ipha = (ipha_t *)mp->b_rptr;
13219 		len = mp->b_wptr - mp->b_rptr;
13220 	}
13221 
13222 	/*
13223 	 * Extract the offset field from the TCP header.  As usual, we
13224 	 * try to help the compiler more than the reader.
13225 	 */
13226 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13227 	if (offset != 5) {
13228 tcpoptions:
13229 		if (offset < 5) {
13230 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13231 			goto error;
13232 		}
13233 		/*
13234 		 * There must be TCP options.
13235 		 * Make sure we can grab them.
13236 		 */
13237 		offset <<= 2;
13238 		offset += u1;
13239 		if (len < offset) {
13240 			if (!pullupmsg(mp, offset)) {
13241 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13242 				goto error;
13243 			}
13244 			ipha = (ipha_t *)mp->b_rptr;
13245 			len = mp->b_wptr - rptr;
13246 		}
13247 	}
13248 
13249 	/* Get the total packet length in len, including headers. */
13250 	if (mp->b_cont)
13251 		len = msgdsize(mp);
13252 
13253 	/*
13254 	 * Check the TCP checksum by pulling together the pseudo-
13255 	 * header checksum, and passing it to ip_csum to be added in
13256 	 * with the TCP datagram.
13257 	 *
13258 	 * Since we are not using the hwcksum if available we must
13259 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13260 	 * If either of these fails along the way the mblk is freed.
13261 	 * If this logic ever changes and mblk is reused to say send
13262 	 * ICMP's back, then this flag may need to be cleared in
13263 	 * other places as well.
13264 	 */
13265 	DB_CKSUMFLAGS(mp) = 0;
13266 
13267 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13268 
13269 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13270 #ifdef	_BIG_ENDIAN
13271 	u1 += IPPROTO_TCP;
13272 #else
13273 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13274 #endif
13275 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13276 	/*
13277 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13278 	 */
13279 	IP_STAT(ipst, ip_in_sw_cksum);
13280 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13281 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13282 		goto error;
13283 	}
13284 
13285 	IP_STAT(ipst, ip_tcp_slow_path);
13286 	goto try_again;
13287 #undef  iphs
13288 #undef  rptr
13289 
13290 error:
13291 	freemsg(first_mp);
13292 slow_done:
13293 	return (NULL);
13294 }
13295 
13296 /* ARGSUSED */
13297 static void
13298 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13299     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13300 {
13301 	conn_t		*connp;
13302 	uint32_t	sum;
13303 	uint32_t	u1;
13304 	ssize_t		len;
13305 	sctp_hdr_t	*sctph;
13306 	zoneid_t	zoneid = ire->ire_zoneid;
13307 	uint32_t	pktsum;
13308 	uint32_t	calcsum;
13309 	uint32_t	ports;
13310 	in6_addr_t	map_src, map_dst;
13311 	ill_t		*ill = (ill_t *)q->q_ptr;
13312 	ip_stack_t	*ipst;
13313 	sctp_stack_t	*sctps;
13314 	boolean_t	sctp_csum_err = B_FALSE;
13315 
13316 	ASSERT(recv_ill != NULL);
13317 	ipst = recv_ill->ill_ipst;
13318 	sctps = ipst->ips_netstack->netstack_sctp;
13319 
13320 #define	rptr	((uchar_t *)ipha)
13321 
13322 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13323 	ASSERT(ill != NULL);
13324 
13325 	/* u1 is # words of IP options */
13326 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13327 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13328 
13329 	/* IP options present */
13330 	if (u1 > 0) {
13331 		goto ipoptions;
13332 	} else {
13333 		/* Check the IP header checksum.  */
13334 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13335 		    !mctl_present) {
13336 #define	uph	((uint16_t *)ipha)
13337 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13338 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13339 #undef	uph
13340 			/* finish doing IP checksum */
13341 			sum = (sum & 0xFFFF) + (sum >> 16);
13342 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13343 			/*
13344 			 * Don't verify header checksum if this packet
13345 			 * is coming back from AH/ESP as we already did it.
13346 			 */
13347 			if (sum != 0 && sum != 0xFFFF) {
13348 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13349 				goto error;
13350 			}
13351 		}
13352 		/*
13353 		 * Since there is no SCTP h/w cksum support yet, just
13354 		 * clear the flag.
13355 		 */
13356 		DB_CKSUMFLAGS(mp) = 0;
13357 	}
13358 
13359 	/*
13360 	 * Don't verify header checksum if this packet is coming
13361 	 * back from AH/ESP as we already did it.
13362 	 */
13363 	if (!mctl_present) {
13364 		UPDATE_IB_PKT_COUNT(ire);
13365 		ire->ire_last_used_time = lbolt;
13366 	}
13367 
13368 	/* packet part of fragmented IP packet? */
13369 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13370 	if (u1 & (IPH_MF | IPH_OFFSET))
13371 		goto fragmented;
13372 
13373 	/* u1 = IP header length (20 bytes) */
13374 	u1 = IP_SIMPLE_HDR_LENGTH;
13375 
13376 find_sctp_client:
13377 	/* Pullup if we don't have the sctp common header. */
13378 	len = MBLKL(mp);
13379 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13380 		if (mp->b_cont == NULL ||
13381 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13382 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13383 			goto error;
13384 		}
13385 		ipha = (ipha_t *)mp->b_rptr;
13386 		len = MBLKL(mp);
13387 	}
13388 
13389 	sctph = (sctp_hdr_t *)(rptr + u1);
13390 #ifdef	DEBUG
13391 	if (!skip_sctp_cksum) {
13392 #endif
13393 		pktsum = sctph->sh_chksum;
13394 		sctph->sh_chksum = 0;
13395 		calcsum = sctp_cksum(mp, u1);
13396 		sctph->sh_chksum = pktsum;
13397 		if (calcsum != pktsum)
13398 			sctp_csum_err = B_TRUE;
13399 #ifdef	DEBUG	/* skip_sctp_cksum */
13400 	}
13401 #endif
13402 	/* get the ports */
13403 	ports = *(uint32_t *)&sctph->sh_sport;
13404 
13405 	IRE_REFRELE(ire);
13406 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13407 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13408 	if (sctp_csum_err) {
13409 		/*
13410 		 * No potential sctp checksum errors go to the Sun
13411 		 * sctp stack however they might be Adler-32 summed
13412 		 * packets a userland stack bound to a raw IP socket
13413 		 * could reasonably use. Note though that Adler-32 is
13414 		 * a long deprecated algorithm and customer sctp
13415 		 * networks should eventually migrate to CRC-32 at
13416 		 * which time this facility should be removed.
13417 		 */
13418 		flags |= IP_FF_SCTP_CSUM_ERR;
13419 		goto no_conn;
13420 	}
13421 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13422 	    sctps)) == NULL) {
13423 		/* Check for raw socket or OOTB handling */
13424 		goto no_conn;
13425 	}
13426 
13427 	/* Found a client; up it goes */
13428 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13429 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13430 	return;
13431 
13432 no_conn:
13433 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13434 	    ports, mctl_present, flags, B_TRUE, zoneid);
13435 	return;
13436 
13437 ipoptions:
13438 	DB_CKSUMFLAGS(mp) = 0;
13439 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13440 		goto slow_done;
13441 
13442 	UPDATE_IB_PKT_COUNT(ire);
13443 	ire->ire_last_used_time = lbolt;
13444 
13445 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13446 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13447 fragmented:
13448 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13449 			goto slow_done;
13450 		/*
13451 		 * Make sure that first_mp points back to mp as
13452 		 * the mp we came in with could have changed in
13453 		 * ip_rput_fragment().
13454 		 */
13455 		ASSERT(!mctl_present);
13456 		ipha = (ipha_t *)mp->b_rptr;
13457 		first_mp = mp;
13458 	}
13459 
13460 	/* Now we have a complete datagram, destined for this machine. */
13461 	u1 = IPH_HDR_LENGTH(ipha);
13462 	goto find_sctp_client;
13463 #undef  iphs
13464 #undef  rptr
13465 
13466 error:
13467 	freemsg(first_mp);
13468 slow_done:
13469 	IRE_REFRELE(ire);
13470 }
13471 
13472 #define	VER_BITS	0xF0
13473 #define	VERSION_6	0x60
13474 
13475 static boolean_t
13476 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13477     ipaddr_t *dstp, ip_stack_t *ipst)
13478 {
13479 	uint_t	opt_len;
13480 	ipha_t *ipha;
13481 	ssize_t len;
13482 	uint_t	pkt_len;
13483 
13484 	ASSERT(ill != NULL);
13485 	IP_STAT(ipst, ip_ipoptions);
13486 	ipha = *iphapp;
13487 
13488 #define	rptr    ((uchar_t *)ipha)
13489 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13490 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13491 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13492 		freemsg(mp);
13493 		return (B_FALSE);
13494 	}
13495 
13496 	/* multiple mblk or too short */
13497 	pkt_len = ntohs(ipha->ipha_length);
13498 
13499 	/* Get the number of words of IP options in the IP header. */
13500 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13501 	if (opt_len) {
13502 		/* IP Options present!  Validate and process. */
13503 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13504 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13505 			goto done;
13506 		}
13507 		/*
13508 		 * Recompute complete header length and make sure we
13509 		 * have access to all of it.
13510 		 */
13511 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13512 		if (len > (mp->b_wptr - rptr)) {
13513 			if (len > pkt_len) {
13514 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13515 				goto done;
13516 			}
13517 			if (!pullupmsg(mp, len)) {
13518 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13519 				goto done;
13520 			}
13521 			ipha = (ipha_t *)mp->b_rptr;
13522 		}
13523 		/*
13524 		 * Go off to ip_rput_options which returns the next hop
13525 		 * destination address, which may have been affected
13526 		 * by source routing.
13527 		 */
13528 		IP_STAT(ipst, ip_opt);
13529 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13530 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13531 			return (B_FALSE);
13532 		}
13533 	}
13534 	*iphapp = ipha;
13535 	return (B_TRUE);
13536 done:
13537 	/* clear b_prev - used by ip_mroute_decap */
13538 	mp->b_prev = NULL;
13539 	freemsg(mp);
13540 	return (B_FALSE);
13541 #undef  rptr
13542 }
13543 
13544 /*
13545  * Deal with the fact that there is no ire for the destination.
13546  */
13547 static ire_t *
13548 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13549 {
13550 	ipha_t	*ipha;
13551 	ill_t	*ill;
13552 	ire_t	*ire;
13553 	ip_stack_t *ipst;
13554 	enum	ire_forward_action ret_action;
13555 
13556 	ipha = (ipha_t *)mp->b_rptr;
13557 	ill = (ill_t *)q->q_ptr;
13558 
13559 	ASSERT(ill != NULL);
13560 	ipst = ill->ill_ipst;
13561 
13562 	/*
13563 	 * No IRE for this destination, so it can't be for us.
13564 	 * Unless we are forwarding, drop the packet.
13565 	 * We have to let source routed packets through
13566 	 * since we don't yet know if they are 'ping -l'
13567 	 * packets i.e. if they will go out over the
13568 	 * same interface as they came in on.
13569 	 */
13570 	if (ll_multicast) {
13571 		freemsg(mp);
13572 		return (NULL);
13573 	}
13574 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13575 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13576 		freemsg(mp);
13577 		return (NULL);
13578 	}
13579 
13580 	/*
13581 	 * Mark this packet as having originated externally.
13582 	 *
13583 	 * For non-forwarding code path, ire_send later double
13584 	 * checks this interface to see if it is still exists
13585 	 * post-ARP resolution.
13586 	 *
13587 	 * Also, IPQOS uses this to differentiate between
13588 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13589 	 * QOS packet processing in ip_wput_attach_llhdr().
13590 	 * The QoS module can mark the b_band for a fastpath message
13591 	 * or the dl_priority field in a unitdata_req header for
13592 	 * CoS marking. This info can only be found in
13593 	 * ip_wput_attach_llhdr().
13594 	 */
13595 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13596 	/*
13597 	 * Clear the indication that this may have a hardware checksum
13598 	 * as we are not using it
13599 	 */
13600 	DB_CKSUMFLAGS(mp) = 0;
13601 
13602 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13603 	    msg_getlabel(mp), ipst);
13604 
13605 	if (ire == NULL && ret_action == Forward_check_multirt) {
13606 		/* Let ip_newroute handle CGTP  */
13607 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13608 		return (NULL);
13609 	}
13610 
13611 	if (ire != NULL)
13612 		return (ire);
13613 
13614 	mp->b_prev = mp->b_next = 0;
13615 
13616 	if (ret_action == Forward_blackhole) {
13617 		freemsg(mp);
13618 		return (NULL);
13619 	}
13620 	/* send icmp unreachable */
13621 	q = WR(q);
13622 	/* Sent by forwarding path, and router is global zone */
13623 	if (ip_source_routed(ipha, ipst)) {
13624 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13625 		    GLOBAL_ZONEID, ipst);
13626 	} else {
13627 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13628 		    ipst);
13629 	}
13630 
13631 	return (NULL);
13632 
13633 }
13634 
13635 /*
13636  * check ip header length and align it.
13637  */
13638 static boolean_t
13639 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13640 {
13641 	ssize_t len;
13642 	ill_t *ill;
13643 	ipha_t	*ipha;
13644 
13645 	len = MBLKL(mp);
13646 
13647 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13648 		ill = (ill_t *)q->q_ptr;
13649 
13650 		if (!OK_32PTR(mp->b_rptr))
13651 			IP_STAT(ipst, ip_notaligned1);
13652 		else
13653 			IP_STAT(ipst, ip_notaligned2);
13654 		/* Guard against bogus device drivers */
13655 		if (len < 0) {
13656 			/* clear b_prev - used by ip_mroute_decap */
13657 			mp->b_prev = NULL;
13658 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13659 			freemsg(mp);
13660 			return (B_FALSE);
13661 		}
13662 
13663 		if (ip_rput_pullups++ == 0) {
13664 			ipha = (ipha_t *)mp->b_rptr;
13665 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13666 			    "ip_check_and_align_header: %s forced us to "
13667 			    " pullup pkt, hdr len %ld, hdr addr %p",
13668 			    ill->ill_name, len, (void *)ipha);
13669 		}
13670 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13671 			/* clear b_prev - used by ip_mroute_decap */
13672 			mp->b_prev = NULL;
13673 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13674 			freemsg(mp);
13675 			return (B_FALSE);
13676 		}
13677 	}
13678 	return (B_TRUE);
13679 }
13680 
13681 /*
13682  * Handle the situation where a packet came in on `ill' but matched an IRE
13683  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13684  * for interface statistics.
13685  */
13686 ire_t *
13687 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13688 {
13689 	ire_t		*new_ire;
13690 	ill_t		*ire_ill;
13691 	uint_t		ifindex;
13692 	ip_stack_t	*ipst = ill->ill_ipst;
13693 	boolean_t	strict_check = B_FALSE;
13694 
13695 	/*
13696 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13697 	 * issue (e.g. packet received on an underlying interface matched an
13698 	 * IRE_LOCAL on its associated group interface).
13699 	 */
13700 	if (ire->ire_rfq != NULL &&
13701 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13702 		return (ire);
13703 	}
13704 
13705 	/*
13706 	 * Do another ire lookup here, using the ingress ill, to see if the
13707 	 * interface is in a usesrc group.
13708 	 * As long as the ills belong to the same group, we don't consider
13709 	 * them to be arriving on the wrong interface. Thus, if the switch
13710 	 * is doing inbound load spreading, we won't drop packets when the
13711 	 * ip*_strict_dst_multihoming switch is on.
13712 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13713 	 * where the local address may not be unique. In this case we were
13714 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13715 	 * actually returned. The new lookup, which is more specific, should
13716 	 * only find the IRE_LOCAL associated with the ingress ill if one
13717 	 * exists.
13718 	 */
13719 
13720 	if (ire->ire_ipversion == IPV4_VERSION) {
13721 		if (ipst->ips_ip_strict_dst_multihoming)
13722 			strict_check = B_TRUE;
13723 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13724 		    ill->ill_ipif, ALL_ZONES, NULL,
13725 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13726 	} else {
13727 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13728 		if (ipst->ips_ipv6_strict_dst_multihoming)
13729 			strict_check = B_TRUE;
13730 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13731 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13732 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13733 	}
13734 	/*
13735 	 * If the same ire that was returned in ip_input() is found then this
13736 	 * is an indication that usesrc groups are in use. The packet
13737 	 * arrived on a different ill in the group than the one associated with
13738 	 * the destination address.  If a different ire was found then the same
13739 	 * IP address must be hosted on multiple ills. This is possible with
13740 	 * unnumbered point2point interfaces. We switch to use this new ire in
13741 	 * order to have accurate interface statistics.
13742 	 */
13743 	if (new_ire != NULL) {
13744 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13745 			ire_refrele(ire);
13746 			ire = new_ire;
13747 		} else {
13748 			ire_refrele(new_ire);
13749 		}
13750 		return (ire);
13751 	} else if ((ire->ire_rfq == NULL) &&
13752 	    (ire->ire_ipversion == IPV4_VERSION)) {
13753 		/*
13754 		 * The best match could have been the original ire which
13755 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13756 		 * the strict multihoming checks are irrelevant as we consider
13757 		 * local addresses hosted on lo0 to be interface agnostic. We
13758 		 * only expect a null ire_rfq on IREs which are associated with
13759 		 * lo0 hence we can return now.
13760 		 */
13761 		return (ire);
13762 	}
13763 
13764 	/*
13765 	 * Chase pointers once and store locally.
13766 	 */
13767 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13768 	    (ill_t *)(ire->ire_rfq->q_ptr);
13769 	ifindex = ill->ill_usesrc_ifindex;
13770 
13771 	/*
13772 	 * Check if it's a legal address on the 'usesrc' interface.
13773 	 */
13774 	if ((ifindex != 0) && (ire_ill != NULL) &&
13775 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13776 		return (ire);
13777 	}
13778 
13779 	/*
13780 	 * If the ip*_strict_dst_multihoming switch is on then we can
13781 	 * only accept this packet if the interface is marked as routing.
13782 	 */
13783 	if (!(strict_check))
13784 		return (ire);
13785 
13786 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13787 	    ILLF_ROUTER) != 0) {
13788 		return (ire);
13789 	}
13790 
13791 	ire_refrele(ire);
13792 	return (NULL);
13793 }
13794 
13795 /*
13796  *
13797  * This is the fast forward path. If we are here, we dont need to
13798  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13799  * needed to find the nexthop in this case is much simpler
13800  */
13801 ire_t *
13802 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13803 {
13804 	ipha_t	*ipha;
13805 	ire_t	*src_ire;
13806 	ill_t	*stq_ill;
13807 	uint_t	hlen;
13808 	uint_t	pkt_len;
13809 	uint32_t sum;
13810 	queue_t	*dev_q;
13811 	ip_stack_t *ipst = ill->ill_ipst;
13812 	mblk_t *fpmp;
13813 	enum	ire_forward_action ret_action;
13814 
13815 	ipha = (ipha_t *)mp->b_rptr;
13816 
13817 	if (ire != NULL &&
13818 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13819 	    ire->ire_zoneid != ALL_ZONES) {
13820 		/*
13821 		 * Should only use IREs that are visible to the global
13822 		 * zone for forwarding.
13823 		 */
13824 		ire_refrele(ire);
13825 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13826 		/*
13827 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13828 		 * transient cases. In such case, just drop the packet
13829 		 */
13830 		if (ire != NULL && ire->ire_type != IRE_CACHE)
13831 			goto indiscard;
13832 	}
13833 
13834 	/*
13835 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13836 	 * The loopback address check for both src and dst has already
13837 	 * been checked in ip_input
13838 	 */
13839 
13840 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13841 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13842 		goto drop;
13843 	}
13844 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13845 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13846 
13847 	if (src_ire != NULL) {
13848 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13849 		ire_refrele(src_ire);
13850 		goto drop;
13851 	}
13852 
13853 	/* No ire cache of nexthop. So first create one  */
13854 	if (ire == NULL) {
13855 
13856 		ire = ire_forward_simple(dst, &ret_action, ipst);
13857 
13858 		/*
13859 		 * We only come to ip_fast_forward if ip_cgtp_filter
13860 		 * is not set. So ire_forward() should not return with
13861 		 * Forward_check_multirt as the next action.
13862 		 */
13863 		ASSERT(ret_action != Forward_check_multirt);
13864 		if (ire == NULL) {
13865 			/* An attempt was made to forward the packet */
13866 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13867 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13868 			mp->b_prev = mp->b_next = 0;
13869 			/* send icmp unreachable */
13870 			/* Sent by forwarding path, and router is global zone */
13871 			if (ret_action == Forward_ret_icmp_err) {
13872 				if (ip_source_routed(ipha, ipst)) {
13873 					icmp_unreachable(ill->ill_wq, mp,
13874 					    ICMP_SOURCE_ROUTE_FAILED,
13875 					    GLOBAL_ZONEID, ipst);
13876 				} else {
13877 					icmp_unreachable(ill->ill_wq, mp,
13878 					    ICMP_HOST_UNREACHABLE,
13879 					    GLOBAL_ZONEID, ipst);
13880 				}
13881 			} else {
13882 				freemsg(mp);
13883 			}
13884 			return (NULL);
13885 		}
13886 	}
13887 
13888 	/*
13889 	 * Forwarding fastpath exception case:
13890 	 * If any of the following are true, we take the slowpath:
13891 	 *	o forwarding is not enabled
13892 	 *	o incoming and outgoing interface are the same, or in the same
13893 	 *	  IPMP group.
13894 	 *	o corresponding ire is in incomplete state
13895 	 *	o packet needs fragmentation
13896 	 *	o ARP cache is not resolved
13897 	 *
13898 	 * The codeflow from here on is thus:
13899 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13900 	 */
13901 	pkt_len = ntohs(ipha->ipha_length);
13902 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13903 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13904 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13905 	    (ire->ire_nce == NULL) ||
13906 	    (pkt_len > ire->ire_max_frag) ||
13907 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13908 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13909 	    ipha->ipha_ttl <= 1) {
13910 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13911 		    ipha, ill, B_FALSE, B_TRUE);
13912 		return (ire);
13913 	}
13914 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13915 
13916 	DTRACE_PROBE4(ip4__forwarding__start,
13917 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13918 
13919 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13920 	    ipst->ips_ipv4firewall_forwarding,
13921 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13922 
13923 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13924 
13925 	if (mp == NULL)
13926 		goto drop;
13927 
13928 	mp->b_datap->db_struioun.cksum.flags = 0;
13929 	/* Adjust the checksum to reflect the ttl decrement. */
13930 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13931 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13932 	ipha->ipha_ttl--;
13933 
13934 	/*
13935 	 * Write the link layer header.  We can do this safely here,
13936 	 * because we have already tested to make sure that the IP
13937 	 * policy is not set, and that we have a fast path destination
13938 	 * header.
13939 	 */
13940 	mp->b_rptr -= hlen;
13941 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13942 
13943 	UPDATE_IB_PKT_COUNT(ire);
13944 	ire->ire_last_used_time = lbolt;
13945 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13946 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13947 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13948 
13949 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13950 		dev_q = ire->ire_stq->q_next;
13951 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13952 			goto indiscard;
13953 	}
13954 
13955 	DTRACE_PROBE4(ip4__physical__out__start,
13956 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13957 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13958 	    ipst->ips_ipv4firewall_physical_out,
13959 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13960 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13961 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13962 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13963 	    ip6_t *, NULL, int, 0);
13964 
13965 	if (mp != NULL) {
13966 		if (ipst->ips_ip4_observe.he_interested) {
13967 			zoneid_t szone;
13968 
13969 			/*
13970 			 * Both of these functions expect b_rptr to be
13971 			 * where the IP header starts, so advance past the
13972 			 * link layer header if present.
13973 			 */
13974 			mp->b_rptr += hlen;
13975 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13976 			    ipst, ALL_ZONES);
13977 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
13978 			    ALL_ZONES, ill, ipst);
13979 			mp->b_rptr -= hlen;
13980 		}
13981 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
13982 	}
13983 	return (ire);
13984 
13985 indiscard:
13986 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13987 drop:
13988 	if (mp != NULL)
13989 		freemsg(mp);
13990 	return (ire);
13991 
13992 }
13993 
13994 /*
13995  * This function is called in the forwarding slowpath, when
13996  * either the ire lacks the link-layer address, or the packet needs
13997  * further processing(eg. fragmentation), before transmission.
13998  */
13999 
14000 static void
14001 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14002     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14003 {
14004 	queue_t		*dev_q;
14005 	ire_t		*src_ire;
14006 	ip_stack_t	*ipst = ill->ill_ipst;
14007 	boolean_t	same_illgrp = B_FALSE;
14008 
14009 	ASSERT(ire->ire_stq != NULL);
14010 
14011 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14012 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14013 
14014 	/*
14015 	 * If the caller of this function is ip_fast_forward() skip the
14016 	 * next three checks as it does not apply.
14017 	 */
14018 	if (from_ip_fast_forward)
14019 		goto skip;
14020 
14021 	if (ll_multicast != 0) {
14022 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14023 		goto drop_pkt;
14024 	}
14025 
14026 	/*
14027 	 * check if ipha_src is a broadcast address. Note that this
14028 	 * check is redundant when we get here from ip_fast_forward()
14029 	 * which has already done this check. However, since we can
14030 	 * also get here from ip_rput_process_broadcast() or, for
14031 	 * for the slow path through ip_fast_forward(), we perform
14032 	 * the check again for code-reusability
14033 	 */
14034 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14035 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14036 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14037 		if (src_ire != NULL)
14038 			ire_refrele(src_ire);
14039 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14040 		ip2dbg(("ip_rput_process_forward: Received packet with"
14041 		    " bad src/dst address on %s\n", ill->ill_name));
14042 		goto drop_pkt;
14043 	}
14044 
14045 	/*
14046 	 * Check if we want to forward this one at this time.
14047 	 * We allow source routed packets on a host provided that
14048 	 * they go out the same ill or illgrp as they came in on.
14049 	 *
14050 	 * XXX To be quicker, we may wish to not chase pointers to
14051 	 * get the ILLF_ROUTER flag and instead store the
14052 	 * forwarding policy in the ire.  An unfortunate
14053 	 * side-effect of that would be requiring an ire flush
14054 	 * whenever the ILLF_ROUTER flag changes.
14055 	 */
14056 skip:
14057 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14058 
14059 	if (((ill->ill_flags &
14060 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14061 	    !(ip_source_routed(ipha, ipst) &&
14062 	    (ire->ire_rfq == q || same_illgrp))) {
14063 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14064 		if (ip_source_routed(ipha, ipst)) {
14065 			q = WR(q);
14066 			/*
14067 			 * Clear the indication that this may have
14068 			 * hardware checksum as we are not using it.
14069 			 */
14070 			DB_CKSUMFLAGS(mp) = 0;
14071 			/* Sent by forwarding path, and router is global zone */
14072 			icmp_unreachable(q, mp,
14073 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14074 			return;
14075 		}
14076 		goto drop_pkt;
14077 	}
14078 
14079 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14080 
14081 	/* Packet is being forwarded. Turning off hwcksum flag. */
14082 	DB_CKSUMFLAGS(mp) = 0;
14083 	if (ipst->ips_ip_g_send_redirects) {
14084 		/*
14085 		 * Check whether the incoming interface and outgoing
14086 		 * interface is part of the same group. If so,
14087 		 * send redirects.
14088 		 *
14089 		 * Check the source address to see if it originated
14090 		 * on the same logical subnet it is going back out on.
14091 		 * If so, we should be able to send it a redirect.
14092 		 * Avoid sending a redirect if the destination
14093 		 * is directly connected (i.e., ipha_dst is the same
14094 		 * as ire_gateway_addr or the ire_addr of the
14095 		 * nexthop IRE_CACHE ), or if the packet was source
14096 		 * routed out this interface.
14097 		 */
14098 		ipaddr_t src, nhop;
14099 		mblk_t	*mp1;
14100 		ire_t	*nhop_ire = NULL;
14101 
14102 		/*
14103 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14104 		 * If so, send redirects.
14105 		 */
14106 		if ((ire->ire_rfq == q || same_illgrp) &&
14107 		    !ip_source_routed(ipha, ipst)) {
14108 
14109 			nhop = (ire->ire_gateway_addr != 0 ?
14110 			    ire->ire_gateway_addr : ire->ire_addr);
14111 
14112 			if (ipha->ipha_dst == nhop) {
14113 				/*
14114 				 * We avoid sending a redirect if the
14115 				 * destination is directly connected
14116 				 * because it is possible that multiple
14117 				 * IP subnets may have been configured on
14118 				 * the link, and the source may not
14119 				 * be on the same subnet as ip destination,
14120 				 * even though they are on the same
14121 				 * physical link.
14122 				 */
14123 				goto sendit;
14124 			}
14125 
14126 			src = ipha->ipha_src;
14127 
14128 			/*
14129 			 * We look up the interface ire for the nexthop,
14130 			 * to see if ipha_src is in the same subnet
14131 			 * as the nexthop.
14132 			 *
14133 			 * Note that, if, in the future, IRE_CACHE entries
14134 			 * are obsoleted,  this lookup will not be needed,
14135 			 * as the ire passed to this function will be the
14136 			 * same as the nhop_ire computed below.
14137 			 */
14138 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14139 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14140 			    0, NULL, MATCH_IRE_TYPE, ipst);
14141 
14142 			if (nhop_ire != NULL) {
14143 				if ((src & nhop_ire->ire_mask) ==
14144 				    (nhop & nhop_ire->ire_mask)) {
14145 					/*
14146 					 * The source is directly connected.
14147 					 * Just copy the ip header (which is
14148 					 * in the first mblk)
14149 					 */
14150 					mp1 = copyb(mp);
14151 					if (mp1 != NULL) {
14152 						icmp_send_redirect(WR(q), mp1,
14153 						    nhop, ipst);
14154 					}
14155 				}
14156 				ire_refrele(nhop_ire);
14157 			}
14158 		}
14159 	}
14160 sendit:
14161 	dev_q = ire->ire_stq->q_next;
14162 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14163 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14164 		freemsg(mp);
14165 		return;
14166 	}
14167 
14168 	ip_rput_forward(ire, ipha, mp, ill);
14169 	return;
14170 
14171 drop_pkt:
14172 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14173 	freemsg(mp);
14174 }
14175 
14176 ire_t *
14177 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14178     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14179 {
14180 	queue_t		*q;
14181 	uint16_t	hcksumflags;
14182 	ip_stack_t	*ipst = ill->ill_ipst;
14183 
14184 	q = *qp;
14185 
14186 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14187 
14188 	/*
14189 	 * Clear the indication that this may have hardware
14190 	 * checksum as we are not using it for forwarding.
14191 	 */
14192 	hcksumflags = DB_CKSUMFLAGS(mp);
14193 	DB_CKSUMFLAGS(mp) = 0;
14194 
14195 	/*
14196 	 * Directed broadcast forwarding: if the packet came in over a
14197 	 * different interface then it is routed out over we can forward it.
14198 	 */
14199 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14200 		ire_refrele(ire);
14201 		freemsg(mp);
14202 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14203 		return (NULL);
14204 	}
14205 	/*
14206 	 * For multicast we have set dst to be INADDR_BROADCAST
14207 	 * for delivering to all STREAMS.
14208 	 */
14209 	if (!CLASSD(ipha->ipha_dst)) {
14210 		ire_t *new_ire;
14211 		ipif_t *ipif;
14212 
14213 		ipif = ipif_get_next_ipif(NULL, ill);
14214 		if (ipif == NULL) {
14215 discard:		ire_refrele(ire);
14216 			freemsg(mp);
14217 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14218 			return (NULL);
14219 		}
14220 		new_ire = ire_ctable_lookup(dst, 0, 0,
14221 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14222 		ipif_refrele(ipif);
14223 
14224 		if (new_ire != NULL) {
14225 			/*
14226 			 * If the matching IRE_BROADCAST is part of an IPMP
14227 			 * group, then drop the packet unless our ill has been
14228 			 * nominated to receive for the group.
14229 			 */
14230 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14231 			    new_ire->ire_rfq != q) {
14232 				ire_refrele(new_ire);
14233 				goto discard;
14234 			}
14235 
14236 			/*
14237 			 * In the special case of multirouted broadcast
14238 			 * packets, we unconditionally need to "gateway"
14239 			 * them to the appropriate interface here.
14240 			 * In the normal case, this cannot happen, because
14241 			 * there is no broadcast IRE tagged with the
14242 			 * RTF_MULTIRT flag.
14243 			 */
14244 			if (new_ire->ire_flags & RTF_MULTIRT) {
14245 				ire_refrele(new_ire);
14246 				if (ire->ire_rfq != NULL) {
14247 					q = ire->ire_rfq;
14248 					*qp = q;
14249 				}
14250 			} else {
14251 				ire_refrele(ire);
14252 				ire = new_ire;
14253 			}
14254 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14255 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14256 				/*
14257 				 * Free the message if
14258 				 * ip_g_forward_directed_bcast is turned
14259 				 * off for non-local broadcast.
14260 				 */
14261 				ire_refrele(ire);
14262 				freemsg(mp);
14263 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14264 				return (NULL);
14265 			}
14266 		} else {
14267 			/*
14268 			 * This CGTP packet successfully passed the
14269 			 * CGTP filter, but the related CGTP
14270 			 * broadcast IRE has not been found,
14271 			 * meaning that the redundant ipif is
14272 			 * probably down. However, if we discarded
14273 			 * this packet, its duplicate would be
14274 			 * filtered out by the CGTP filter so none
14275 			 * of them would get through. So we keep
14276 			 * going with this one.
14277 			 */
14278 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14279 			if (ire->ire_rfq != NULL) {
14280 				q = ire->ire_rfq;
14281 				*qp = q;
14282 			}
14283 		}
14284 	}
14285 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14286 		/*
14287 		 * Verify that there are not more then one
14288 		 * IRE_BROADCAST with this broadcast address which
14289 		 * has ire_stq set.
14290 		 * TODO: simplify, loop over all IRE's
14291 		 */
14292 		ire_t	*ire1;
14293 		int	num_stq = 0;
14294 		mblk_t	*mp1;
14295 
14296 		/* Find the first one with ire_stq set */
14297 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14298 		for (ire1 = ire; ire1 &&
14299 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14300 		    ire1 = ire1->ire_next)
14301 			;
14302 		if (ire1) {
14303 			ire_refrele(ire);
14304 			ire = ire1;
14305 			IRE_REFHOLD(ire);
14306 		}
14307 
14308 		/* Check if there are additional ones with stq set */
14309 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14310 			if (ire->ire_addr != ire1->ire_addr)
14311 				break;
14312 			if (ire1->ire_stq) {
14313 				num_stq++;
14314 				break;
14315 			}
14316 		}
14317 		rw_exit(&ire->ire_bucket->irb_lock);
14318 		if (num_stq == 1 && ire->ire_stq != NULL) {
14319 			ip1dbg(("ip_rput_process_broadcast: directed "
14320 			    "broadcast to 0x%x\n",
14321 			    ntohl(ire->ire_addr)));
14322 			mp1 = copymsg(mp);
14323 			if (mp1) {
14324 				switch (ipha->ipha_protocol) {
14325 				case IPPROTO_UDP:
14326 					ip_udp_input(q, mp1, ipha, ire, ill);
14327 					break;
14328 				default:
14329 					ip_proto_input(q, mp1, ipha, ire, ill,
14330 					    0);
14331 					break;
14332 				}
14333 			}
14334 			/*
14335 			 * Adjust ttl to 2 (1+1 - the forward engine
14336 			 * will decrement it by one.
14337 			 */
14338 			if (ip_csum_hdr(ipha)) {
14339 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14340 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14341 				freemsg(mp);
14342 				ire_refrele(ire);
14343 				return (NULL);
14344 			}
14345 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14346 			ipha->ipha_hdr_checksum = 0;
14347 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14348 			ip_rput_process_forward(q, mp, ire, ipha,
14349 			    ill, ll_multicast, B_FALSE);
14350 			ire_refrele(ire);
14351 			return (NULL);
14352 		}
14353 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14354 		    ntohl(ire->ire_addr)));
14355 	}
14356 
14357 	/* Restore any hardware checksum flags */
14358 	DB_CKSUMFLAGS(mp) = hcksumflags;
14359 	return (ire);
14360 }
14361 
14362 /* ARGSUSED */
14363 static boolean_t
14364 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14365     int *ll_multicast, ipaddr_t *dstp)
14366 {
14367 	ip_stack_t	*ipst = ill->ill_ipst;
14368 
14369 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14370 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14371 	    ntohs(ipha->ipha_length));
14372 
14373 	/*
14374 	 * So that we don't end up with dups, only one ill in an IPMP group is
14375 	 * nominated to receive multicast traffic.
14376 	 */
14377 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14378 		goto drop_pkt;
14379 
14380 	/*
14381 	 * Forward packets only if we have joined the allmulti
14382 	 * group on this interface.
14383 	 */
14384 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14385 		int retval;
14386 
14387 		/*
14388 		 * Clear the indication that this may have hardware
14389 		 * checksum as we are not using it.
14390 		 */
14391 		DB_CKSUMFLAGS(mp) = 0;
14392 		retval = ip_mforward(ill, ipha, mp);
14393 		/* ip_mforward updates mib variables if needed */
14394 		/* clear b_prev - used by ip_mroute_decap */
14395 		mp->b_prev = NULL;
14396 
14397 		switch (retval) {
14398 		case 0:
14399 			/*
14400 			 * pkt is okay and arrived on phyint.
14401 			 *
14402 			 * If we are running as a multicast router
14403 			 * we need to see all IGMP and/or PIM packets.
14404 			 */
14405 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14406 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14407 				goto done;
14408 			}
14409 			break;
14410 		case -1:
14411 			/* pkt is mal-formed, toss it */
14412 			goto drop_pkt;
14413 		case 1:
14414 			/* pkt is okay and arrived on a tunnel */
14415 			/*
14416 			 * If we are running a multicast router
14417 			 *  we need to see all igmp packets.
14418 			 */
14419 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14420 				*dstp = INADDR_BROADCAST;
14421 				*ll_multicast = 1;
14422 				return (B_FALSE);
14423 			}
14424 
14425 			goto drop_pkt;
14426 		}
14427 	}
14428 
14429 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14430 		/*
14431 		 * This might just be caused by the fact that
14432 		 * multiple IP Multicast addresses map to the same
14433 		 * link layer multicast - no need to increment counter!
14434 		 */
14435 		freemsg(mp);
14436 		return (B_TRUE);
14437 	}
14438 done:
14439 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14440 	/*
14441 	 * This assumes the we deliver to all streams for multicast
14442 	 * and broadcast packets.
14443 	 */
14444 	*dstp = INADDR_BROADCAST;
14445 	*ll_multicast = 1;
14446 	return (B_FALSE);
14447 drop_pkt:
14448 	ip2dbg(("ip_rput: drop pkt\n"));
14449 	freemsg(mp);
14450 	return (B_TRUE);
14451 }
14452 
14453 /*
14454  * This function is used to both return an indication of whether or not
14455  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14456  * and in doing so, determine whether or not it is broadcast vs multicast.
14457  * For it to be a broadcast packet, we must have the appropriate mblk_t
14458  * hanging off the ill_t.  If this is either not present or doesn't match
14459  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14460  * to be multicast.  Thus NICs that have no broadcast address (or no
14461  * capability for one, such as point to point links) cannot return as
14462  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14463  * the return values simplifies the current use of the return value of this
14464  * function, which is to pass through the multicast/broadcast characteristic
14465  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14466  * changing the return value to some other symbol demands the appropriate
14467  * "translation" when hpe_flags is set prior to calling hook_run() for
14468  * packet events.
14469  */
14470 int
14471 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14472 {
14473 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14474 	mblk_t *bmp;
14475 
14476 	if (ind->dl_group_address) {
14477 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14478 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14479 		    MBLKL(mb) &&
14480 		    (bmp = ill->ill_bcast_mp) != NULL) {
14481 			dl_unitdata_req_t *dlur;
14482 			uint8_t *bphys_addr;
14483 
14484 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14485 			if (ill->ill_sap_length < 0)
14486 				bphys_addr = (uchar_t *)dlur +
14487 				    dlur->dl_dest_addr_offset;
14488 			else
14489 				bphys_addr = (uchar_t *)dlur +
14490 				    dlur->dl_dest_addr_offset +
14491 				    ill->ill_sap_length;
14492 
14493 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14494 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14495 				return (HPE_BROADCAST);
14496 			}
14497 			return (HPE_MULTICAST);
14498 		}
14499 		return (HPE_MULTICAST);
14500 	}
14501 	return (0);
14502 }
14503 
14504 static boolean_t
14505 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14506     int *ll_multicast, mblk_t **mpp)
14507 {
14508 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14509 	boolean_t must_copy = B_FALSE;
14510 	struct iocblk   *iocp;
14511 	ipha_t		*ipha;
14512 	ip_stack_t	*ipst = ill->ill_ipst;
14513 
14514 #define	rptr    ((uchar_t *)ipha)
14515 
14516 	first_mp = *first_mpp;
14517 	mp = *mpp;
14518 
14519 	ASSERT(first_mp == mp);
14520 
14521 	/*
14522 	 * if db_ref > 1 then copymsg and free original. Packet may be
14523 	 * changed and do not want other entity who has a reference to this
14524 	 * message to trip over the changes. This is a blind change because
14525 	 * trying to catch all places that might change packet is too
14526 	 * difficult (since it may be a module above this one)
14527 	 *
14528 	 * This corresponds to the non-fast path case. We walk down the full
14529 	 * chain in this case, and check the db_ref count of all the dblks,
14530 	 * and do a copymsg if required. It is possible that the db_ref counts
14531 	 * of the data blocks in the mblk chain can be different.
14532 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14533 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14534 	 * 'snoop' is running.
14535 	 */
14536 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14537 		if (mp1->b_datap->db_ref > 1) {
14538 			must_copy = B_TRUE;
14539 			break;
14540 		}
14541 	}
14542 
14543 	if (must_copy) {
14544 		mp1 = copymsg(mp);
14545 		if (mp1 == NULL) {
14546 			for (mp1 = mp; mp1 != NULL;
14547 			    mp1 = mp1->b_cont) {
14548 				mp1->b_next = NULL;
14549 				mp1->b_prev = NULL;
14550 			}
14551 			freemsg(mp);
14552 			if (ill != NULL) {
14553 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14554 			} else {
14555 				BUMP_MIB(&ipst->ips_ip_mib,
14556 				    ipIfStatsInDiscards);
14557 			}
14558 			return (B_TRUE);
14559 		}
14560 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14561 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14562 			/* Copy b_prev - used by ip_mroute_decap */
14563 			to_mp->b_prev = from_mp->b_prev;
14564 			from_mp->b_prev = NULL;
14565 		}
14566 		*first_mpp = first_mp = mp1;
14567 		freemsg(mp);
14568 		mp = mp1;
14569 		*mpp = mp1;
14570 	}
14571 
14572 	ipha = (ipha_t *)mp->b_rptr;
14573 
14574 	/*
14575 	 * previous code has a case for M_DATA.
14576 	 * We want to check how that happens.
14577 	 */
14578 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14579 	switch (first_mp->b_datap->db_type) {
14580 	case M_PROTO:
14581 	case M_PCPROTO:
14582 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14583 		    DL_UNITDATA_IND) {
14584 			/* Go handle anything other than data elsewhere. */
14585 			ip_rput_dlpi(q, mp);
14586 			return (B_TRUE);
14587 		}
14588 
14589 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14590 		/* Ditch the DLPI header. */
14591 		mp1 = mp->b_cont;
14592 		ASSERT(first_mp == mp);
14593 		*first_mpp = mp1;
14594 		freeb(mp);
14595 		*mpp = mp1;
14596 		return (B_FALSE);
14597 	case M_IOCACK:
14598 		ip1dbg(("got iocack "));
14599 		iocp = (struct iocblk *)mp->b_rptr;
14600 		switch (iocp->ioc_cmd) {
14601 		case DL_IOC_HDR_INFO:
14602 			ill = (ill_t *)q->q_ptr;
14603 			ill_fastpath_ack(ill, mp);
14604 			return (B_TRUE);
14605 		default:
14606 			putnext(q, mp);
14607 			return (B_TRUE);
14608 		}
14609 		/* FALLTHRU */
14610 	case M_ERROR:
14611 	case M_HANGUP:
14612 		/*
14613 		 * Since this is on the ill stream we unconditionally
14614 		 * bump up the refcount
14615 		 */
14616 		ill_refhold(ill);
14617 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14618 		return (B_TRUE);
14619 	case M_CTL:
14620 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14621 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14622 		    IPHADA_M_CTL)) {
14623 			/*
14624 			 * It's an IPsec accelerated packet.
14625 			 * Make sure that the ill from which we received the
14626 			 * packet has enabled IPsec hardware acceleration.
14627 			 */
14628 			if (!(ill->ill_capabilities &
14629 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14630 				/* IPsec kstats: bean counter */
14631 				freemsg(mp);
14632 				return (B_TRUE);
14633 			}
14634 
14635 			/*
14636 			 * Make mp point to the mblk following the M_CTL,
14637 			 * then process according to type of mp.
14638 			 * After this processing, first_mp will point to
14639 			 * the data-attributes and mp to the pkt following
14640 			 * the M_CTL.
14641 			 */
14642 			mp = first_mp->b_cont;
14643 			if (mp == NULL) {
14644 				freemsg(first_mp);
14645 				return (B_TRUE);
14646 			}
14647 			/*
14648 			 * A Hardware Accelerated packet can only be M_DATA
14649 			 * ESP or AH packet.
14650 			 */
14651 			if (mp->b_datap->db_type != M_DATA) {
14652 				/* non-M_DATA IPsec accelerated packet */
14653 				IPSECHW_DEBUG(IPSECHW_PKT,
14654 				    ("non-M_DATA IPsec accelerated pkt\n"));
14655 				freemsg(first_mp);
14656 				return (B_TRUE);
14657 			}
14658 			ipha = (ipha_t *)mp->b_rptr;
14659 			if (ipha->ipha_protocol != IPPROTO_AH &&
14660 			    ipha->ipha_protocol != IPPROTO_ESP) {
14661 				IPSECHW_DEBUG(IPSECHW_PKT,
14662 				    ("non-M_DATA IPsec accelerated pkt\n"));
14663 				freemsg(first_mp);
14664 				return (B_TRUE);
14665 			}
14666 			*mpp = mp;
14667 			return (B_FALSE);
14668 		}
14669 		putnext(q, mp);
14670 		return (B_TRUE);
14671 	case M_IOCNAK:
14672 		ip1dbg(("got iocnak "));
14673 		iocp = (struct iocblk *)mp->b_rptr;
14674 		switch (iocp->ioc_cmd) {
14675 		case DL_IOC_HDR_INFO:
14676 			ip_rput_other(NULL, q, mp, NULL);
14677 			return (B_TRUE);
14678 		default:
14679 			break;
14680 		}
14681 		/* FALLTHRU */
14682 	default:
14683 		putnext(q, mp);
14684 		return (B_TRUE);
14685 	}
14686 }
14687 
14688 /* Read side put procedure.  Packets coming from the wire arrive here. */
14689 void
14690 ip_rput(queue_t *q, mblk_t *mp)
14691 {
14692 	ill_t	*ill;
14693 	union DL_primitives *dl;
14694 
14695 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14696 
14697 	ill = (ill_t *)q->q_ptr;
14698 
14699 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14700 		/*
14701 		 * If things are opening or closing, only accept high-priority
14702 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14703 		 * created; on close, things hanging off the ill may have been
14704 		 * freed already.)
14705 		 */
14706 		dl = (union DL_primitives *)mp->b_rptr;
14707 		if (DB_TYPE(mp) != M_PCPROTO ||
14708 		    dl->dl_primitive == DL_UNITDATA_IND) {
14709 			inet_freemsg(mp);
14710 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14711 			    "ip_rput_end: q %p (%S)", q, "uninit");
14712 			return;
14713 		}
14714 	}
14715 
14716 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14717 	    "ip_rput_end: q %p (%S)", q, "end");
14718 
14719 	ip_input(ill, NULL, mp, NULL);
14720 }
14721 
14722 static mblk_t *
14723 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14724 {
14725 	mblk_t *mp1;
14726 	boolean_t adjusted = B_FALSE;
14727 	ip_stack_t *ipst = ill->ill_ipst;
14728 
14729 	IP_STAT(ipst, ip_db_ref);
14730 	/*
14731 	 * The IP_RECVSLLA option depends on having the
14732 	 * link layer header. First check that:
14733 	 * a> the underlying device is of type ether,
14734 	 * since this option is currently supported only
14735 	 * over ethernet.
14736 	 * b> there is enough room to copy over the link
14737 	 * layer header.
14738 	 *
14739 	 * Once the checks are done, adjust rptr so that
14740 	 * the link layer header will be copied via
14741 	 * copymsg. Note that, IFT_ETHER may be returned
14742 	 * by some non-ethernet drivers but in this case
14743 	 * the second check will fail.
14744 	 */
14745 	if (ill->ill_type == IFT_ETHER &&
14746 	    (mp->b_rptr - mp->b_datap->db_base) >=
14747 	    sizeof (struct ether_header)) {
14748 		mp->b_rptr -= sizeof (struct ether_header);
14749 		adjusted = B_TRUE;
14750 	}
14751 	mp1 = copymsg(mp);
14752 
14753 	if (mp1 == NULL) {
14754 		mp->b_next = NULL;
14755 		/* clear b_prev - used by ip_mroute_decap */
14756 		mp->b_prev = NULL;
14757 		freemsg(mp);
14758 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14759 		return (NULL);
14760 	}
14761 
14762 	if (adjusted) {
14763 		/*
14764 		 * Copy is done. Restore the pointer in
14765 		 * the _new_ mblk
14766 		 */
14767 		mp1->b_rptr += sizeof (struct ether_header);
14768 	}
14769 
14770 	/* Copy b_prev - used by ip_mroute_decap */
14771 	mp1->b_prev = mp->b_prev;
14772 	mp->b_prev = NULL;
14773 
14774 	/* preserve the hardware checksum flags and data, if present */
14775 	if (DB_CKSUMFLAGS(mp) != 0) {
14776 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14777 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14778 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14779 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14780 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14781 	}
14782 
14783 	freemsg(mp);
14784 	return (mp1);
14785 }
14786 
14787 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14788 	if (tail != NULL)					\
14789 		tail->b_next = mp;				\
14790 	else							\
14791 		head = mp;					\
14792 	tail = mp;						\
14793 	cnt++;							\
14794 }
14795 
14796 /*
14797  * Direct read side procedure capable of dealing with chains. GLDv3 based
14798  * drivers call this function directly with mblk chains while STREAMS
14799  * read side procedure ip_rput() calls this for single packet with ip_ring
14800  * set to NULL to process one packet at a time.
14801  *
14802  * The ill will always be valid if this function is called directly from
14803  * the driver.
14804  *
14805  * If ip_input() is called from GLDv3:
14806  *
14807  *   - This must be a non-VLAN IP stream.
14808  *   - 'mp' is either an untagged or a special priority-tagged packet.
14809  *   - Any VLAN tag that was in the MAC header has been stripped.
14810  *
14811  * If the IP header in packet is not 32-bit aligned, every message in the
14812  * chain will be aligned before further operations. This is required on SPARC
14813  * platform.
14814  */
14815 /* ARGSUSED */
14816 void
14817 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14818     struct mac_header_info_s *mhip)
14819 {
14820 	ipaddr_t		dst = NULL;
14821 	ipaddr_t		prev_dst;
14822 	ire_t			*ire = NULL;
14823 	ipha_t			*ipha;
14824 	uint_t			pkt_len;
14825 	ssize_t			len;
14826 	uint_t			opt_len;
14827 	int			ll_multicast;
14828 	int			cgtp_flt_pkt;
14829 	queue_t			*q = ill->ill_rq;
14830 	squeue_t		*curr_sqp = NULL;
14831 	mblk_t 			*head = NULL;
14832 	mblk_t			*tail = NULL;
14833 	mblk_t			*first_mp;
14834 	int			cnt = 0;
14835 	ip_stack_t		*ipst = ill->ill_ipst;
14836 	mblk_t			*mp;
14837 	mblk_t			*dmp;
14838 	uint8_t			tag;
14839 	ilb_stack_t		*ilbs;
14840 	ipaddr_t		lb_dst;
14841 
14842 	ASSERT(mp_chain != NULL);
14843 	ASSERT(ill != NULL);
14844 
14845 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14846 
14847 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14848 
14849 #define	rptr	((uchar_t *)ipha)
14850 
14851 	ilbs = ipst->ips_netstack->netstack_ilb;
14852 	while (mp_chain != NULL) {
14853 		mp = mp_chain;
14854 		mp_chain = mp_chain->b_next;
14855 		mp->b_next = NULL;
14856 		ll_multicast = 0;
14857 
14858 		/*
14859 		 * We do ire caching from one iteration to
14860 		 * another. In the event the packet chain contains
14861 		 * all packets from the same dst, this caching saves
14862 		 * an ire_cache_lookup for each of the succeeding
14863 		 * packets in a packet chain.
14864 		 */
14865 		prev_dst = dst;
14866 
14867 		/*
14868 		 * if db_ref > 1 then copymsg and free original. Packet
14869 		 * may be changed and we do not want the other entity
14870 		 * who has a reference to this message to trip over the
14871 		 * changes. This is a blind change because trying to
14872 		 * catch all places that might change the packet is too
14873 		 * difficult.
14874 		 *
14875 		 * This corresponds to the fast path case, where we have
14876 		 * a chain of M_DATA mblks.  We check the db_ref count
14877 		 * of only the 1st data block in the mblk chain. There
14878 		 * doesn't seem to be a reason why a device driver would
14879 		 * send up data with varying db_ref counts in the mblk
14880 		 * chain. In any case the Fast path is a private
14881 		 * interface, and our drivers don't do such a thing.
14882 		 * Given the above assumption, there is no need to walk
14883 		 * down the entire mblk chain (which could have a
14884 		 * potential performance problem)
14885 		 *
14886 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14887 		 * to here because of exclusive ip stacks and vnics.
14888 		 * Packets transmitted from exclusive stack over vnic
14889 		 * can have db_ref > 1 and when it gets looped back to
14890 		 * another vnic in a different zone, you have ip_input()
14891 		 * getting dblks with db_ref > 1. So if someone
14892 		 * complains of TCP performance under this scenario,
14893 		 * take a serious look here on the impact of copymsg().
14894 		 */
14895 
14896 		if (DB_REF(mp) > 1) {
14897 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14898 				continue;
14899 		}
14900 
14901 		/*
14902 		 * Check and align the IP header.
14903 		 */
14904 		first_mp = mp;
14905 		if (DB_TYPE(mp) == M_DATA) {
14906 			dmp = mp;
14907 		} else if (DB_TYPE(mp) == M_PROTO &&
14908 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14909 			dmp = mp->b_cont;
14910 		} else {
14911 			dmp = NULL;
14912 		}
14913 		if (dmp != NULL) {
14914 			/*
14915 			 * IP header ptr not aligned?
14916 			 * OR IP header not complete in first mblk
14917 			 */
14918 			if (!OK_32PTR(dmp->b_rptr) ||
14919 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14920 				if (!ip_check_and_align_header(q, dmp, ipst))
14921 					continue;
14922 			}
14923 		}
14924 
14925 		/*
14926 		 * ip_input fast path
14927 		 */
14928 
14929 		/* mblk type is not M_DATA */
14930 		if (DB_TYPE(mp) != M_DATA) {
14931 			if (ip_rput_process_notdata(q, &first_mp, ill,
14932 			    &ll_multicast, &mp))
14933 				continue;
14934 
14935 			/*
14936 			 * The only way we can get here is if we had a
14937 			 * packet that was either a DL_UNITDATA_IND or
14938 			 * an M_CTL for an IPsec accelerated packet.
14939 			 *
14940 			 * In either case, the first_mp will point to
14941 			 * the leading M_PROTO or M_CTL.
14942 			 */
14943 			ASSERT(first_mp != NULL);
14944 		} else if (mhip != NULL) {
14945 			/*
14946 			 * ll_multicast is set here so that it is ready
14947 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14948 			 * manipulates ll_multicast in the same fashion when
14949 			 * called from ip_rput_process_notdata.
14950 			 */
14951 			switch (mhip->mhi_dsttype) {
14952 			case MAC_ADDRTYPE_MULTICAST :
14953 				ll_multicast = HPE_MULTICAST;
14954 				break;
14955 			case MAC_ADDRTYPE_BROADCAST :
14956 				ll_multicast = HPE_BROADCAST;
14957 				break;
14958 			default :
14959 				break;
14960 			}
14961 		}
14962 
14963 		/* Only M_DATA can come here and it is always aligned */
14964 		ASSERT(DB_TYPE(mp) == M_DATA);
14965 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14966 
14967 		ipha = (ipha_t *)mp->b_rptr;
14968 		len = mp->b_wptr - rptr;
14969 		pkt_len = ntohs(ipha->ipha_length);
14970 
14971 		/*
14972 		 * We must count all incoming packets, even if they end
14973 		 * up being dropped later on.
14974 		 */
14975 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14976 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14977 
14978 		/* multiple mblk or too short */
14979 		len -= pkt_len;
14980 		if (len != 0) {
14981 			/*
14982 			 * Make sure we have data length consistent
14983 			 * with the IP header.
14984 			 */
14985 			if (mp->b_cont == NULL) {
14986 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14987 					BUMP_MIB(ill->ill_ip_mib,
14988 					    ipIfStatsInHdrErrors);
14989 					ip2dbg(("ip_input: drop pkt\n"));
14990 					freemsg(mp);
14991 					continue;
14992 				}
14993 				mp->b_wptr = rptr + pkt_len;
14994 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14995 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14996 					BUMP_MIB(ill->ill_ip_mib,
14997 					    ipIfStatsInHdrErrors);
14998 					ip2dbg(("ip_input: drop pkt\n"));
14999 					freemsg(mp);
15000 					continue;
15001 				}
15002 				(void) adjmsg(mp, -len);
15003 				/*
15004 				 * adjmsg may have freed an mblk from the chain,
15005 				 * hence invalidate any hw checksum here. This
15006 				 * will force IP to calculate the checksum in
15007 				 * sw, but only for this packet.
15008 				 */
15009 				DB_CKSUMFLAGS(mp) = 0;
15010 				IP_STAT(ipst, ip_multimblk3);
15011 			}
15012 		}
15013 
15014 		/* Obtain the dst of the current packet */
15015 		dst = ipha->ipha_dst;
15016 
15017 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15018 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15019 		    ipha, ip6_t *, NULL, int, 0);
15020 
15021 		/*
15022 		 * The following test for loopback is faster than
15023 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15024 		 * operations.
15025 		 * Note that these addresses are always in network byte order
15026 		 */
15027 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15028 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15029 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15030 			freemsg(mp);
15031 			continue;
15032 		}
15033 
15034 		/*
15035 		 * The event for packets being received from a 'physical'
15036 		 * interface is placed after validation of the source and/or
15037 		 * destination address as being local so that packets can be
15038 		 * redirected to loopback addresses using ipnat.
15039 		 */
15040 		DTRACE_PROBE4(ip4__physical__in__start,
15041 		    ill_t *, ill, ill_t *, NULL,
15042 		    ipha_t *, ipha, mblk_t *, first_mp);
15043 
15044 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15045 		    ipst->ips_ipv4firewall_physical_in,
15046 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15047 
15048 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15049 
15050 		if (first_mp == NULL) {
15051 			continue;
15052 		}
15053 		dst = ipha->ipha_dst;
15054 		/*
15055 		 * Attach any necessary label information to
15056 		 * this packet
15057 		 */
15058 		if (is_system_labeled() &&
15059 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15060 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15061 			freemsg(mp);
15062 			continue;
15063 		}
15064 
15065 		if (ipst->ips_ip4_observe.he_interested) {
15066 			zoneid_t dzone;
15067 
15068 			/*
15069 			 * On the inbound path the src zone will be unknown as
15070 			 * this packet has come from the wire.
15071 			 */
15072 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15073 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15074 			    ill, ipst);
15075 		}
15076 
15077 		/*
15078 		 * Here we check to see if we machine is setup as
15079 		 * L3 loadbalancer and if the incoming packet is for a VIP
15080 		 *
15081 		 * Check the following:
15082 		 * - there is at least a rule
15083 		 * - protocol of the packet is supported
15084 		 */
15085 		if (ilb_has_rules(ilbs) && ILB_SUPP_L4(ipha->ipha_protocol)) {
15086 			int lb_ret;
15087 
15088 			/* For convenience, we pull up the mblk. */
15089 			if (mp->b_cont != NULL) {
15090 				if (pullupmsg(mp, -1) == 0) {
15091 					BUMP_MIB(ill->ill_ip_mib,
15092 					    ipIfStatsInDiscards);
15093 					freemsg(first_mp);
15094 					continue;
15095 				}
15096 				ipha = (ipha_t *)mp->b_rptr;
15097 			}
15098 
15099 			/*
15100 			 * We just drop all fragments going to any VIP, at
15101 			 * least for now....
15102 			 */
15103 			if (ntohs(ipha->ipha_fragment_offset_and_flags) &
15104 			    (IPH_MF | IPH_OFFSET)) {
15105 				if (!ilb_rule_match_vip_v4(ilbs,
15106 				    ipha->ipha_dst, NULL)) {
15107 					goto after_ilb;
15108 				}
15109 
15110 				ILB_KSTAT_UPDATE(ilbs, ip_frag_in, 1);
15111 				ILB_KSTAT_UPDATE(ilbs, ip_frag_dropped, 1);
15112 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15113 				freemsg(first_mp);
15114 				continue;
15115 			}
15116 			lb_ret = ilb_check_v4(ilbs, ill, mp, ipha,
15117 			    ipha->ipha_protocol, (uint8_t *)ipha +
15118 			    IPH_HDR_LENGTH(ipha), &lb_dst);
15119 
15120 			if (lb_ret == ILB_DROPPED) {
15121 				/* Is this the right counter to increase? */
15122 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15123 				freemsg(first_mp);
15124 				continue;
15125 			} else if (lb_ret == ILB_BALANCED) {
15126 				/* Set the dst to that of the chosen server */
15127 				dst = lb_dst;
15128 				DB_CKSUMFLAGS(mp) = 0;
15129 			}
15130 		}
15131 
15132 after_ilb:
15133 		/*
15134 		 * Reuse the cached ire only if the ipha_dst of the previous
15135 		 * packet is the same as the current packet AND it is not
15136 		 * INADDR_ANY.
15137 		 */
15138 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15139 		    (ire != NULL)) {
15140 			ire_refrele(ire);
15141 			ire = NULL;
15142 		}
15143 
15144 		opt_len = ipha->ipha_version_and_hdr_length -
15145 		    IP_SIMPLE_HDR_VERSION;
15146 
15147 		/*
15148 		 * Check to see if we can take the fastpath.
15149 		 * That is possible if the following conditions are met
15150 		 *	o Tsol disabled
15151 		 *	o CGTP disabled
15152 		 *	o ipp_action_count is 0
15153 		 *	o no options in the packet
15154 		 *	o not a RSVP packet
15155 		 * 	o not a multicast packet
15156 		 *	o ill not in IP_DHCPINIT_IF mode
15157 		 */
15158 		if (!is_system_labeled() &&
15159 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15160 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15161 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15162 			if (ire == NULL)
15163 				ire = ire_cache_lookup_simple(dst, ipst);
15164 			/*
15165 			 * Unless forwarding is enabled, dont call
15166 			 * ip_fast_forward(). Incoming packet is for forwarding
15167 			 */
15168 			if ((ill->ill_flags & ILLF_ROUTER) &&
15169 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15170 				ire = ip_fast_forward(ire, dst, ill, mp);
15171 				continue;
15172 			}
15173 			/* incoming packet is for local consumption */
15174 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15175 				goto local;
15176 		}
15177 
15178 		/*
15179 		 * Disable ire caching for anything more complex
15180 		 * than the simple fast path case we checked for above.
15181 		 */
15182 		if (ire != NULL) {
15183 			ire_refrele(ire);
15184 			ire = NULL;
15185 		}
15186 
15187 		/*
15188 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15189 		 * server to unicast DHCP packets to a DHCP client using the
15190 		 * IP address it is offering to the client.  This can be
15191 		 * disabled through the "broadcast bit", but not all DHCP
15192 		 * servers honor that bit.  Therefore, to interoperate with as
15193 		 * many DHCP servers as possible, the DHCP client allows the
15194 		 * server to unicast, but we treat those packets as broadcast
15195 		 * here.  Note that we don't rewrite the packet itself since
15196 		 * (a) that would mess up the checksums and (b) the DHCP
15197 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15198 		 * hand it the packet regardless.
15199 		 */
15200 		if (ill->ill_dhcpinit != 0 &&
15201 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15202 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15203 			udpha_t *udpha;
15204 
15205 			/*
15206 			 * Reload ipha since pullupmsg() can change b_rptr.
15207 			 */
15208 			ipha = (ipha_t *)mp->b_rptr;
15209 			udpha = (udpha_t *)&ipha[1];
15210 
15211 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15212 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15213 				    mblk_t *, mp);
15214 				dst = INADDR_BROADCAST;
15215 			}
15216 		}
15217 
15218 		/* Full-blown slow path */
15219 		if (opt_len != 0) {
15220 			if (len != 0)
15221 				IP_STAT(ipst, ip_multimblk4);
15222 			else
15223 				IP_STAT(ipst, ip_ipoptions);
15224 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15225 			    &dst, ipst))
15226 				continue;
15227 		}
15228 
15229 		/*
15230 		 * Invoke the CGTP (multirouting) filtering module to process
15231 		 * the incoming packet. Packets identified as duplicates
15232 		 * must be discarded. Filtering is active only if the
15233 		 * the ip_cgtp_filter ndd variable is non-zero.
15234 		 */
15235 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15236 		if (ipst->ips_ip_cgtp_filter &&
15237 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15238 			netstackid_t stackid;
15239 
15240 			stackid = ipst->ips_netstack->netstack_stackid;
15241 			cgtp_flt_pkt =
15242 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15243 			    ill->ill_phyint->phyint_ifindex, mp);
15244 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15245 				freemsg(first_mp);
15246 				continue;
15247 			}
15248 		}
15249 
15250 		/*
15251 		 * If rsvpd is running, let RSVP daemon handle its processing
15252 		 * and forwarding of RSVP multicast/unicast packets.
15253 		 * If rsvpd is not running but mrouted is running, RSVP
15254 		 * multicast packets are forwarded as multicast traffic
15255 		 * and RSVP unicast packets are forwarded by unicast router.
15256 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15257 		 * packets are not forwarded, but the unicast packets are
15258 		 * forwarded like unicast traffic.
15259 		 */
15260 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15261 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15262 		    NULL) {
15263 			/* RSVP packet and rsvpd running. Treat as ours */
15264 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15265 			/*
15266 			 * This assumes that we deliver to all streams for
15267 			 * multicast and broadcast packets.
15268 			 * We have to force ll_multicast to 1 to handle the
15269 			 * M_DATA messages passed in from ip_mroute_decap.
15270 			 */
15271 			dst = INADDR_BROADCAST;
15272 			ll_multicast = 1;
15273 		} else if (CLASSD(dst)) {
15274 			/* packet is multicast */
15275 			mp->b_next = NULL;
15276 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15277 			    &ll_multicast, &dst))
15278 				continue;
15279 		}
15280 
15281 		if (ire == NULL) {
15282 			ire = ire_cache_lookup(dst, ALL_ZONES,
15283 			    msg_getlabel(mp), ipst);
15284 		}
15285 
15286 		if (ire != NULL && ire->ire_stq != NULL &&
15287 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15288 		    ire->ire_zoneid != ALL_ZONES) {
15289 			/*
15290 			 * Should only use IREs that are visible from the
15291 			 * global zone for forwarding.
15292 			 */
15293 			ire_refrele(ire);
15294 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15295 			    msg_getlabel(mp), ipst);
15296 		}
15297 
15298 		if (ire == NULL) {
15299 			/*
15300 			 * No IRE for this destination, so it can't be for us.
15301 			 * Unless we are forwarding, drop the packet.
15302 			 * We have to let source routed packets through
15303 			 * since we don't yet know if they are 'ping -l'
15304 			 * packets i.e. if they will go out over the
15305 			 * same interface as they came in on.
15306 			 */
15307 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15308 			if (ire == NULL)
15309 				continue;
15310 		}
15311 
15312 		/*
15313 		 * Broadcast IRE may indicate either broadcast or
15314 		 * multicast packet
15315 		 */
15316 		if (ire->ire_type == IRE_BROADCAST) {
15317 			/*
15318 			 * Skip broadcast checks if packet is UDP multicast;
15319 			 * we'd rather not enter ip_rput_process_broadcast()
15320 			 * unless the packet is broadcast for real, since
15321 			 * that routine is a no-op for multicast.
15322 			 */
15323 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15324 			    !CLASSD(ipha->ipha_dst)) {
15325 				ire = ip_rput_process_broadcast(&q, mp,
15326 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15327 				    ll_multicast);
15328 				if (ire == NULL)
15329 					continue;
15330 			}
15331 		} else if (ire->ire_stq != NULL) {
15332 			/* fowarding? */
15333 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15334 			    ll_multicast, B_FALSE);
15335 			/* ip_rput_process_forward consumed the packet */
15336 			continue;
15337 		}
15338 
15339 local:
15340 		/*
15341 		 * If the queue in the ire is different to the ingress queue
15342 		 * then we need to check to see if we can accept the packet.
15343 		 * Note that for multicast packets and broadcast packets sent
15344 		 * to a broadcast address which is shared between multiple
15345 		 * interfaces we should not do this since we just got a random
15346 		 * broadcast ire.
15347 		 */
15348 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15349 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15350 			if (ire == NULL) {
15351 				/* Drop packet */
15352 				BUMP_MIB(ill->ill_ip_mib,
15353 				    ipIfStatsForwProhibits);
15354 				freemsg(mp);
15355 				continue;
15356 			}
15357 			if (ire->ire_rfq != NULL)
15358 				q = ire->ire_rfq;
15359 		}
15360 
15361 		switch (ipha->ipha_protocol) {
15362 		case IPPROTO_TCP:
15363 			ASSERT(first_mp == mp);
15364 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15365 			    mp, 0, q, ip_ring)) != NULL) {
15366 				if (curr_sqp == NULL) {
15367 					curr_sqp = GET_SQUEUE(mp);
15368 					ASSERT(cnt == 0);
15369 					cnt++;
15370 					head = tail = mp;
15371 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15372 					ASSERT(tail != NULL);
15373 					cnt++;
15374 					tail->b_next = mp;
15375 					tail = mp;
15376 				} else {
15377 					/*
15378 					 * A different squeue. Send the
15379 					 * chain for the previous squeue on
15380 					 * its way. This shouldn't happen
15381 					 * often unless interrupt binding
15382 					 * changes.
15383 					 */
15384 					IP_STAT(ipst, ip_input_multi_squeue);
15385 					SQUEUE_ENTER(curr_sqp, head,
15386 					    tail, cnt, SQ_PROCESS, tag);
15387 					curr_sqp = GET_SQUEUE(mp);
15388 					head = mp;
15389 					tail = mp;
15390 					cnt = 1;
15391 				}
15392 			}
15393 			continue;
15394 		case IPPROTO_UDP:
15395 			ASSERT(first_mp == mp);
15396 			ip_udp_input(q, mp, ipha, ire, ill);
15397 			continue;
15398 		case IPPROTO_SCTP:
15399 			ASSERT(first_mp == mp);
15400 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15401 			    q, dst);
15402 			/* ire has been released by ip_sctp_input */
15403 			ire = NULL;
15404 			continue;
15405 		case IPPROTO_ENCAP:
15406 		case IPPROTO_IPV6:
15407 			ASSERT(first_mp == mp);
15408 			if (ip_iptun_input(NULL, mp, ipha, ill, ire, ipst))
15409 				break;
15410 			/*
15411 			 * If there was no IP tunnel data-link bound to
15412 			 * receive this packet, then we fall through to
15413 			 * allow potential raw sockets bound to either of
15414 			 * these protocols to pick it up.
15415 			 */
15416 		default:
15417 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15418 			continue;
15419 		}
15420 	}
15421 
15422 	if (ire != NULL)
15423 		ire_refrele(ire);
15424 
15425 	if (head != NULL)
15426 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15427 
15428 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15429 	    "ip_input_end: q %p (%S)", q, "end");
15430 #undef  rptr
15431 }
15432 
15433 /*
15434  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15435  * a chain of packets in the poll mode. The packets have gone through the
15436  * data link processing but not IP processing. For performance and latency
15437  * reasons, the squeue wants to process the chain in line instead of feeding
15438  * it back via ip_input path.
15439  *
15440  * So this is a light weight function which checks to see if the packets
15441  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15442  * but we still do the paranoid check) meant for local machine and we don't
15443  * have labels etc enabled. Packets that meet the criterion are returned to
15444  * the squeue and processed inline while the rest go via ip_input path.
15445  */
15446 /*ARGSUSED*/
15447 mblk_t *
15448 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15449     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15450 {
15451 	mblk_t 		*mp;
15452 	ipaddr_t	dst = NULL;
15453 	ipaddr_t	prev_dst;
15454 	ire_t		*ire = NULL;
15455 	ipha_t		*ipha;
15456 	uint_t		pkt_len;
15457 	ssize_t		len;
15458 	uint_t		opt_len;
15459 	queue_t		*q = ill->ill_rq;
15460 	squeue_t	*curr_sqp;
15461 	mblk_t 		*ahead = NULL;	/* Accepted head */
15462 	mblk_t		*atail = NULL;	/* Accepted tail */
15463 	uint_t		acnt = 0;	/* Accepted count */
15464 	mblk_t		*utail = NULL;	/* Unaccepted head */
15465 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15466 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15467 	ip_stack_t	*ipst = ill->ill_ipst;
15468 	ilb_stack_t	*ilbs = ipst->ips_netstack->netstack_ilb;
15469 
15470 	*cnt = 0;
15471 
15472 	ASSERT(ill != NULL);
15473 	ASSERT(ip_ring != NULL);
15474 
15475 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15476 
15477 	/* If ILB is enabled, don't do fast processing. */
15478 	if (ilb_has_rules(ilbs)) {
15479 		uhead = mp_chain;
15480 		goto all_reject;
15481 	}
15482 
15483 #define	rptr	((uchar_t *)ipha)
15484 
15485 	while (mp_chain != NULL) {
15486 		mp = mp_chain;
15487 		mp_chain = mp_chain->b_next;
15488 		mp->b_next = NULL;
15489 
15490 		/*
15491 		 * We do ire caching from one iteration to
15492 		 * another. In the event the packet chain contains
15493 		 * all packets from the same dst, this caching saves
15494 		 * an ire_cache_lookup for each of the succeeding
15495 		 * packets in a packet chain.
15496 		 */
15497 		prev_dst = dst;
15498 
15499 		ipha = (ipha_t *)mp->b_rptr;
15500 		len = mp->b_wptr - rptr;
15501 
15502 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15503 
15504 		/*
15505 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15506 		 * or doesn't have min len, reject.
15507 		 */
15508 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15509 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15510 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15511 			continue;
15512 		}
15513 
15514 		pkt_len = ntohs(ipha->ipha_length);
15515 		if (len != pkt_len) {
15516 			if (len > pkt_len) {
15517 				mp->b_wptr = rptr + pkt_len;
15518 			} else {
15519 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15520 				continue;
15521 			}
15522 		}
15523 
15524 		opt_len = ipha->ipha_version_and_hdr_length -
15525 		    IP_SIMPLE_HDR_VERSION;
15526 		dst = ipha->ipha_dst;
15527 
15528 		/* IP version bad or there are IP options */
15529 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15530 		    mp, &ipha, &dst, ipst)))
15531 			continue;
15532 
15533 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15534 		    (ipst->ips_ip_cgtp_filter &&
15535 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15536 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15537 			continue;
15538 		}
15539 
15540 		/*
15541 		 * Reuse the cached ire only if the ipha_dst of the previous
15542 		 * packet is the same as the current packet AND it is not
15543 		 * INADDR_ANY.
15544 		 */
15545 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15546 		    (ire != NULL)) {
15547 			ire_refrele(ire);
15548 			ire = NULL;
15549 		}
15550 
15551 		if (ire == NULL)
15552 			ire = ire_cache_lookup_simple(dst, ipst);
15553 
15554 		/*
15555 		 * Unless forwarding is enabled, dont call
15556 		 * ip_fast_forward(). Incoming packet is for forwarding
15557 		 */
15558 		if ((ill->ill_flags & ILLF_ROUTER) &&
15559 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15560 
15561 			DTRACE_PROBE4(ip4__physical__in__start,
15562 			    ill_t *, ill, ill_t *, NULL,
15563 			    ipha_t *, ipha, mblk_t *, mp);
15564 
15565 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15566 			    ipst->ips_ipv4firewall_physical_in,
15567 			    ill, NULL, ipha, mp, mp, 0, ipst);
15568 
15569 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15570 
15571 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15572 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15573 			    pkt_len);
15574 
15575 			if (mp != NULL)
15576 				ire = ip_fast_forward(ire, dst, ill, mp);
15577 			continue;
15578 		}
15579 
15580 		/* incoming packet is for local consumption */
15581 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15582 			goto local_accept;
15583 
15584 		/*
15585 		 * Disable ire caching for anything more complex
15586 		 * than the simple fast path case we checked for above.
15587 		 */
15588 		if (ire != NULL) {
15589 			ire_refrele(ire);
15590 			ire = NULL;
15591 		}
15592 
15593 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15594 		    ipst);
15595 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15596 		    ire->ire_stq != NULL) {
15597 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15598 			if (ire != NULL) {
15599 				ire_refrele(ire);
15600 				ire = NULL;
15601 			}
15602 			continue;
15603 		}
15604 
15605 local_accept:
15606 
15607 		if (ire->ire_rfq != q) {
15608 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15609 			if (ire != NULL) {
15610 				ire_refrele(ire);
15611 				ire = NULL;
15612 			}
15613 			continue;
15614 		}
15615 
15616 		/*
15617 		 * The event for packets being received from a 'physical'
15618 		 * interface is placed after validation of the source and/or
15619 		 * destination address as being local so that packets can be
15620 		 * redirected to loopback addresses using ipnat.
15621 		 */
15622 		DTRACE_PROBE4(ip4__physical__in__start,
15623 		    ill_t *, ill, ill_t *, NULL,
15624 		    ipha_t *, ipha, mblk_t *, mp);
15625 
15626 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15627 		    ipst->ips_ipv4firewall_physical_in,
15628 		    ill, NULL, ipha, mp, mp, 0, ipst);
15629 
15630 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15631 
15632 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15633 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15634 
15635 		if (mp != NULL &&
15636 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15637 		    0, q, ip_ring)) != NULL) {
15638 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15639 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15640 			} else {
15641 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15642 				    SQ_FILL, SQTAG_IP_INPUT);
15643 			}
15644 		}
15645 	}
15646 
15647 	if (ire != NULL)
15648 		ire_refrele(ire);
15649 
15650 all_reject:
15651 	if (uhead != NULL)
15652 		ip_input(ill, ip_ring, uhead, NULL);
15653 
15654 	if (ahead != NULL) {
15655 		*last = atail;
15656 		*cnt = acnt;
15657 		return (ahead);
15658 	}
15659 
15660 	return (NULL);
15661 #undef  rptr
15662 }
15663 
15664 static void
15665 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15666     t_uscalar_t err)
15667 {
15668 	if (dl_err == DL_SYSERR) {
15669 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15670 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15671 		    ill->ill_name, dl_primstr(prim), err);
15672 		return;
15673 	}
15674 
15675 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15676 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15677 	    dl_errstr(dl_err));
15678 }
15679 
15680 /*
15681  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15682  * than DL_UNITDATA_IND messages. If we need to process this message
15683  * exclusively, we call qwriter_ip, in which case we also need to call
15684  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15685  */
15686 void
15687 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15688 {
15689 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15690 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15691 	ill_t		*ill = q->q_ptr;
15692 	t_uscalar_t	prim = dloa->dl_primitive;
15693 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15694 
15695 	ip1dbg(("ip_rput_dlpi"));
15696 
15697 	/*
15698 	 * If we received an ACK but didn't send a request for it, then it
15699 	 * can't be part of any pending operation; discard up-front.
15700 	 */
15701 	switch (prim) {
15702 	case DL_ERROR_ACK:
15703 		reqprim = dlea->dl_error_primitive;
15704 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15705 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15706 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15707 		    dlea->dl_unix_errno));
15708 		break;
15709 	case DL_OK_ACK:
15710 		reqprim = dloa->dl_correct_primitive;
15711 		break;
15712 	case DL_INFO_ACK:
15713 		reqprim = DL_INFO_REQ;
15714 		break;
15715 	case DL_BIND_ACK:
15716 		reqprim = DL_BIND_REQ;
15717 		break;
15718 	case DL_PHYS_ADDR_ACK:
15719 		reqprim = DL_PHYS_ADDR_REQ;
15720 		break;
15721 	case DL_NOTIFY_ACK:
15722 		reqprim = DL_NOTIFY_REQ;
15723 		break;
15724 	case DL_CONTROL_ACK:
15725 		reqprim = DL_CONTROL_REQ;
15726 		break;
15727 	case DL_CAPABILITY_ACK:
15728 		reqprim = DL_CAPABILITY_REQ;
15729 		break;
15730 	}
15731 
15732 	if (prim != DL_NOTIFY_IND) {
15733 		if (reqprim == DL_PRIM_INVAL ||
15734 		    !ill_dlpi_pending(ill, reqprim)) {
15735 			/* Not a DLPI message we support or expected */
15736 			freemsg(mp);
15737 			return;
15738 		}
15739 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15740 		    dl_primstr(reqprim)));
15741 	}
15742 
15743 	switch (reqprim) {
15744 	case DL_UNBIND_REQ:
15745 		/*
15746 		 * NOTE: we mark the unbind as complete even if we got a
15747 		 * DL_ERROR_ACK, since there's not much else we can do.
15748 		 */
15749 		mutex_enter(&ill->ill_lock);
15750 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15751 		cv_signal(&ill->ill_cv);
15752 		mutex_exit(&ill->ill_lock);
15753 		break;
15754 
15755 	case DL_ENABMULTI_REQ:
15756 		if (prim == DL_OK_ACK) {
15757 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15758 				ill->ill_dlpi_multicast_state = IDS_OK;
15759 		}
15760 		break;
15761 	}
15762 
15763 	/*
15764 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15765 	 * need to become writer to continue to process it.  Because an
15766 	 * exclusive operation doesn't complete until replies to all queued
15767 	 * DLPI messages have been received, we know we're in the middle of an
15768 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15769 	 *
15770 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15771 	 * Since this is on the ill stream we unconditionally bump up the
15772 	 * refcount without doing ILL_CAN_LOOKUP().
15773 	 */
15774 	ill_refhold(ill);
15775 	if (prim == DL_NOTIFY_IND)
15776 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15777 	else
15778 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15779 }
15780 
15781 /*
15782  * Handling of DLPI messages that require exclusive access to the ipsq.
15783  *
15784  * Need to do ill_pending_mp_release on ioctl completion, which could
15785  * happen here. (along with mi_copy_done)
15786  */
15787 /* ARGSUSED */
15788 static void
15789 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15790 {
15791 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15792 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15793 	int		err = 0;
15794 	ill_t		*ill;
15795 	ipif_t		*ipif = NULL;
15796 	mblk_t		*mp1 = NULL;
15797 	conn_t		*connp = NULL;
15798 	t_uscalar_t	paddrreq;
15799 	mblk_t		*mp_hw;
15800 	boolean_t	success;
15801 	boolean_t	ioctl_aborted = B_FALSE;
15802 	boolean_t	log = B_TRUE;
15803 	ip_stack_t		*ipst;
15804 
15805 	ip1dbg(("ip_rput_dlpi_writer .."));
15806 	ill = (ill_t *)q->q_ptr;
15807 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15808 	ASSERT(IAM_WRITER_ILL(ill));
15809 
15810 	ipst = ill->ill_ipst;
15811 
15812 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15813 	/*
15814 	 * The current ioctl could have been aborted by the user and a new
15815 	 * ioctl to bring up another ill could have started. We could still
15816 	 * get a response from the driver later.
15817 	 */
15818 	if (ipif != NULL && ipif->ipif_ill != ill)
15819 		ioctl_aborted = B_TRUE;
15820 
15821 	switch (dloa->dl_primitive) {
15822 	case DL_ERROR_ACK:
15823 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15824 		    dl_primstr(dlea->dl_error_primitive)));
15825 
15826 		switch (dlea->dl_error_primitive) {
15827 		case DL_DISABMULTI_REQ:
15828 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15829 			break;
15830 		case DL_PROMISCON_REQ:
15831 		case DL_PROMISCOFF_REQ:
15832 		case DL_UNBIND_REQ:
15833 		case DL_ATTACH_REQ:
15834 		case DL_INFO_REQ:
15835 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15836 			break;
15837 		case DL_NOTIFY_REQ:
15838 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15839 			log = B_FALSE;
15840 			break;
15841 		case DL_PHYS_ADDR_REQ:
15842 			/*
15843 			 * For IPv6 only, there are two additional
15844 			 * phys_addr_req's sent to the driver to get the
15845 			 * IPv6 token and lla. This allows IP to acquire
15846 			 * the hardware address format for a given interface
15847 			 * without having built in knowledge of the hardware
15848 			 * address. ill_phys_addr_pend keeps track of the last
15849 			 * DL_PAR sent so we know which response we are
15850 			 * dealing with. ill_dlpi_done will update
15851 			 * ill_phys_addr_pend when it sends the next req.
15852 			 * We don't complete the IOCTL until all three DL_PARs
15853 			 * have been attempted, so set *_len to 0 and break.
15854 			 */
15855 			paddrreq = ill->ill_phys_addr_pend;
15856 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15857 			if (paddrreq == DL_IPV6_TOKEN) {
15858 				ill->ill_token_length = 0;
15859 				log = B_FALSE;
15860 				break;
15861 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15862 				ill->ill_nd_lla_len = 0;
15863 				log = B_FALSE;
15864 				break;
15865 			}
15866 			/*
15867 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15868 			 * We presumably have an IOCTL hanging out waiting
15869 			 * for completion. Find it and complete the IOCTL
15870 			 * with the error noted.
15871 			 * However, ill_dl_phys was called on an ill queue
15872 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15873 			 * set. But the ioctl is known to be pending on ill_wq.
15874 			 */
15875 			if (!ill->ill_ifname_pending)
15876 				break;
15877 			ill->ill_ifname_pending = 0;
15878 			if (!ioctl_aborted)
15879 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15880 			if (mp1 != NULL) {
15881 				/*
15882 				 * This operation (SIOCSLIFNAME) must have
15883 				 * happened on the ill. Assert there is no conn
15884 				 */
15885 				ASSERT(connp == NULL);
15886 				q = ill->ill_wq;
15887 			}
15888 			break;
15889 		case DL_BIND_REQ:
15890 			ill_dlpi_done(ill, DL_BIND_REQ);
15891 			if (ill->ill_ifname_pending)
15892 				break;
15893 			/*
15894 			 * Something went wrong with the bind.  We presumably
15895 			 * have an IOCTL hanging out waiting for completion.
15896 			 * Find it, take down the interface that was coming
15897 			 * up, and complete the IOCTL with the error noted.
15898 			 */
15899 			if (!ioctl_aborted)
15900 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15901 			if (mp1 != NULL) {
15902 				/*
15903 				 * This might be a result of a DL_NOTE_REPLUMB
15904 				 * notification. In that case, connp is NULL.
15905 				 */
15906 				if (connp != NULL)
15907 					q = CONNP_TO_WQ(connp);
15908 
15909 				(void) ipif_down(ipif, NULL, NULL);
15910 				/* error is set below the switch */
15911 			}
15912 			break;
15913 		case DL_ENABMULTI_REQ:
15914 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15915 
15916 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15917 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15918 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15919 				ipif_t *ipif;
15920 
15921 				printf("ip: joining multicasts failed (%d)"
15922 				    " on %s - will use link layer "
15923 				    "broadcasts for multicast\n",
15924 				    dlea->dl_errno, ill->ill_name);
15925 
15926 				/*
15927 				 * Set up the multicast mapping alone.
15928 				 * writer, so ok to access ill->ill_ipif
15929 				 * without any lock.
15930 				 */
15931 				ipif = ill->ill_ipif;
15932 				mutex_enter(&ill->ill_phyint->phyint_lock);
15933 				ill->ill_phyint->phyint_flags |=
15934 				    PHYI_MULTI_BCAST;
15935 				mutex_exit(&ill->ill_phyint->phyint_lock);
15936 
15937 				if (!ill->ill_isv6) {
15938 					(void) ipif_arp_setup_multicast(ipif,
15939 					    NULL);
15940 				} else {
15941 					(void) ipif_ndp_setup_multicast(ipif,
15942 					    NULL);
15943 				}
15944 			}
15945 			freemsg(mp);	/* Don't want to pass this up */
15946 			return;
15947 		case DL_CONTROL_REQ:
15948 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15949 			    "DL_CONTROL_REQ\n"));
15950 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15951 			freemsg(mp);
15952 			return;
15953 		case DL_CAPABILITY_REQ:
15954 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15955 			    "DL_CAPABILITY REQ\n"));
15956 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15957 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15958 			ill_capability_done(ill);
15959 			freemsg(mp);
15960 			return;
15961 		}
15962 		/*
15963 		 * Note the error for IOCTL completion (mp1 is set when
15964 		 * ready to complete ioctl). If ill_ifname_pending_err is
15965 		 * set, an error occured during plumbing (ill_ifname_pending),
15966 		 * so we want to report that error.
15967 		 *
15968 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15969 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15970 		 * expected to get errack'd if the driver doesn't support
15971 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15972 		 * if these error conditions are encountered.
15973 		 */
15974 		if (mp1 != NULL) {
15975 			if (ill->ill_ifname_pending_err != 0)  {
15976 				err = ill->ill_ifname_pending_err;
15977 				ill->ill_ifname_pending_err = 0;
15978 			} else {
15979 				err = dlea->dl_unix_errno ?
15980 				    dlea->dl_unix_errno : ENXIO;
15981 			}
15982 		/*
15983 		 * If we're plumbing an interface and an error hasn't already
15984 		 * been saved, set ill_ifname_pending_err to the error passed
15985 		 * up. Ignore the error if log is B_FALSE (see comment above).
15986 		 */
15987 		} else if (log && ill->ill_ifname_pending &&
15988 		    ill->ill_ifname_pending_err == 0) {
15989 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15990 			    dlea->dl_unix_errno : ENXIO;
15991 		}
15992 
15993 		if (log)
15994 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15995 			    dlea->dl_errno, dlea->dl_unix_errno);
15996 		break;
15997 	case DL_CAPABILITY_ACK:
15998 		ill_capability_ack(ill, mp);
15999 		/*
16000 		 * The message has been handed off to ill_capability_ack
16001 		 * and must not be freed below
16002 		 */
16003 		mp = NULL;
16004 		break;
16005 
16006 	case DL_CONTROL_ACK:
16007 		/* We treat all of these as "fire and forget" */
16008 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16009 		break;
16010 	case DL_INFO_ACK:
16011 		/* Call a routine to handle this one. */
16012 		ill_dlpi_done(ill, DL_INFO_REQ);
16013 		ip_ll_subnet_defaults(ill, mp);
16014 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16015 		return;
16016 	case DL_BIND_ACK:
16017 		/*
16018 		 * We should have an IOCTL waiting on this unless
16019 		 * sent by ill_dl_phys, in which case just return
16020 		 */
16021 		ill_dlpi_done(ill, DL_BIND_REQ);
16022 		if (ill->ill_ifname_pending)
16023 			break;
16024 
16025 		if (!ioctl_aborted)
16026 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16027 		if (mp1 == NULL)
16028 			break;
16029 		/*
16030 		 * mp1 was added by ill_dl_up(). if that is a result of
16031 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16032 		 */
16033 		if (connp != NULL)
16034 			q = CONNP_TO_WQ(connp);
16035 
16036 		/*
16037 		 * We are exclusive. So nothing can change even after
16038 		 * we get the pending mp. If need be we can put it back
16039 		 * and restart, as in calling ipif_arp_up()  below.
16040 		 */
16041 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16042 
16043 		mutex_enter(&ill->ill_lock);
16044 		ill->ill_dl_up = 1;
16045 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16046 		mutex_exit(&ill->ill_lock);
16047 
16048 		/*
16049 		 * Now bring up the resolver; when that is complete, we'll
16050 		 * create IREs.  Note that we intentionally mirror what
16051 		 * ipif_up() would have done, because we got here by way of
16052 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16053 		 */
16054 		if (ill->ill_isv6) {
16055 			if (ill->ill_flags & ILLF_XRESOLV) {
16056 				if (connp != NULL)
16057 					mutex_enter(&connp->conn_lock);
16058 				mutex_enter(&ill->ill_lock);
16059 				success = ipsq_pending_mp_add(connp, ipif, q,
16060 				    mp1, 0);
16061 				mutex_exit(&ill->ill_lock);
16062 				if (connp != NULL)
16063 					mutex_exit(&connp->conn_lock);
16064 				if (success) {
16065 					err = ipif_resolver_up(ipif,
16066 					    Res_act_initial);
16067 					if (err == EINPROGRESS) {
16068 						freemsg(mp);
16069 						return;
16070 					}
16071 					ASSERT(err != 0);
16072 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16073 					ASSERT(mp1 != NULL);
16074 				} else {
16075 					/* conn has started closing */
16076 					err = EINTR;
16077 				}
16078 			} else { /* Non XRESOLV interface */
16079 				(void) ipif_resolver_up(ipif, Res_act_initial);
16080 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16081 					err = ipif_up_done_v6(ipif);
16082 			}
16083 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16084 			/*
16085 			 * ARP and other v4 external resolvers.
16086 			 * Leave the pending mblk intact so that
16087 			 * the ioctl completes in ip_rput().
16088 			 */
16089 			if (connp != NULL)
16090 				mutex_enter(&connp->conn_lock);
16091 			mutex_enter(&ill->ill_lock);
16092 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16093 			mutex_exit(&ill->ill_lock);
16094 			if (connp != NULL)
16095 				mutex_exit(&connp->conn_lock);
16096 			if (success) {
16097 				err = ipif_resolver_up(ipif, Res_act_initial);
16098 				if (err == EINPROGRESS) {
16099 					freemsg(mp);
16100 					return;
16101 				}
16102 				ASSERT(err != 0);
16103 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16104 			} else {
16105 				/* The conn has started closing */
16106 				err = EINTR;
16107 			}
16108 		} else {
16109 			/*
16110 			 * This one is complete. Reply to pending ioctl.
16111 			 */
16112 			(void) ipif_resolver_up(ipif, Res_act_initial);
16113 			err = ipif_up_done(ipif);
16114 		}
16115 
16116 		if ((err == 0) && (ill->ill_up_ipifs)) {
16117 			err = ill_up_ipifs(ill, q, mp1);
16118 			if (err == EINPROGRESS) {
16119 				freemsg(mp);
16120 				return;
16121 			}
16122 		}
16123 
16124 		/*
16125 		 * If we have a moved ipif to bring up, and everything has
16126 		 * succeeded to this point, bring it up on the IPMP ill.
16127 		 * Otherwise, leave it down -- the admin can try to bring it
16128 		 * up by hand if need be.
16129 		 */
16130 		if (ill->ill_move_ipif != NULL) {
16131 			if (err != 0) {
16132 				ill->ill_move_ipif = NULL;
16133 			} else {
16134 				ipif = ill->ill_move_ipif;
16135 				ill->ill_move_ipif = NULL;
16136 				err = ipif_up(ipif, q, mp1);
16137 				if (err == EINPROGRESS) {
16138 					freemsg(mp);
16139 					return;
16140 				}
16141 			}
16142 		}
16143 		break;
16144 
16145 	case DL_NOTIFY_IND: {
16146 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16147 		ire_t *ire;
16148 		uint_t orig_mtu;
16149 		boolean_t need_ire_walk_v4 = B_FALSE;
16150 		boolean_t need_ire_walk_v6 = B_FALSE;
16151 
16152 		switch (notify->dl_notification) {
16153 		case DL_NOTE_PHYS_ADDR:
16154 			err = ill_set_phys_addr(ill, mp);
16155 			break;
16156 
16157 		case DL_NOTE_REPLUMB:
16158 			/*
16159 			 * Directly return after calling ill_replumb().
16160 			 * Note that we should not free mp as it is reused
16161 			 * in the ill_replumb() function.
16162 			 */
16163 			err = ill_replumb(ill, mp);
16164 			return;
16165 
16166 		case DL_NOTE_FASTPATH_FLUSH:
16167 			ill_fastpath_flush(ill);
16168 			break;
16169 
16170 		case DL_NOTE_SDU_SIZE:
16171 			/*
16172 			 * Change the MTU size of the interface, of all
16173 			 * attached ipif's, and of all relevant ire's.  The
16174 			 * new value's a uint32_t at notify->dl_data.
16175 			 * Mtu change Vs. new ire creation - protocol below.
16176 			 *
16177 			 * a Mark the ipif as IPIF_CHANGING.
16178 			 * b Set the new mtu in the ipif.
16179 			 * c Change the ire_max_frag on all affected ires
16180 			 * d Unmark the IPIF_CHANGING
16181 			 *
16182 			 * To see how the protocol works, assume an interface
16183 			 * route is also being added simultaneously by
16184 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16185 			 * the ire. If the ire is created before step a,
16186 			 * it will be cleaned up by step c. If the ire is
16187 			 * created after step d, it will see the new value of
16188 			 * ipif_mtu. Any attempt to create the ire between
16189 			 * steps a to d will fail because of the IPIF_CHANGING
16190 			 * flag. Note that ire_create() is passed a pointer to
16191 			 * the ipif_mtu, and not the value. During ire_add
16192 			 * under the bucket lock, the ire_max_frag of the
16193 			 * new ire being created is set from the ipif/ire from
16194 			 * which it is being derived.
16195 			 */
16196 			mutex_enter(&ill->ill_lock);
16197 
16198 			orig_mtu = ill->ill_max_mtu;
16199 			ill->ill_max_frag = (uint_t)notify->dl_data;
16200 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16201 
16202 			/*
16203 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16204 			 * clamp ill_max_mtu at it.
16205 			 */
16206 			if (ill->ill_user_mtu != 0 &&
16207 			    ill->ill_user_mtu < ill->ill_max_mtu)
16208 				ill->ill_max_mtu = ill->ill_user_mtu;
16209 
16210 			/*
16211 			 * If the MTU is unchanged, we're done.
16212 			 */
16213 			if (orig_mtu == ill->ill_max_mtu) {
16214 				mutex_exit(&ill->ill_lock);
16215 				break;
16216 			}
16217 
16218 			if (ill->ill_isv6) {
16219 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16220 					ill->ill_max_mtu = IPV6_MIN_MTU;
16221 			} else {
16222 				if (ill->ill_max_mtu < IP_MIN_MTU)
16223 					ill->ill_max_mtu = IP_MIN_MTU;
16224 			}
16225 			for (ipif = ill->ill_ipif; ipif != NULL;
16226 			    ipif = ipif->ipif_next) {
16227 				/*
16228 				 * Don't override the mtu if the user
16229 				 * has explicitly set it.
16230 				 */
16231 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16232 					continue;
16233 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16234 				if (ipif->ipif_isv6)
16235 					ire = ipif_to_ire_v6(ipif);
16236 				else
16237 					ire = ipif_to_ire(ipif);
16238 				if (ire != NULL) {
16239 					ire->ire_max_frag = ipif->ipif_mtu;
16240 					ire_refrele(ire);
16241 				}
16242 				if (ipif->ipif_flags & IPIF_UP) {
16243 					if (ill->ill_isv6)
16244 						need_ire_walk_v6 = B_TRUE;
16245 					else
16246 						need_ire_walk_v4 = B_TRUE;
16247 				}
16248 			}
16249 			mutex_exit(&ill->ill_lock);
16250 			if (need_ire_walk_v4)
16251 				ire_walk_v4(ill_mtu_change, (char *)ill,
16252 				    ALL_ZONES, ipst);
16253 			if (need_ire_walk_v6)
16254 				ire_walk_v6(ill_mtu_change, (char *)ill,
16255 				    ALL_ZONES, ipst);
16256 
16257 			/*
16258 			 * Refresh IPMP meta-interface MTU if necessary.
16259 			 */
16260 			if (IS_UNDER_IPMP(ill))
16261 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16262 			break;
16263 
16264 		case DL_NOTE_LINK_UP:
16265 		case DL_NOTE_LINK_DOWN: {
16266 			/*
16267 			 * We are writer. ill / phyint / ipsq assocs stable.
16268 			 * The RUNNING flag reflects the state of the link.
16269 			 */
16270 			phyint_t *phyint = ill->ill_phyint;
16271 			uint64_t new_phyint_flags;
16272 			boolean_t changed = B_FALSE;
16273 			boolean_t went_up;
16274 
16275 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16276 			mutex_enter(&phyint->phyint_lock);
16277 
16278 			new_phyint_flags = went_up ?
16279 			    phyint->phyint_flags | PHYI_RUNNING :
16280 			    phyint->phyint_flags & ~PHYI_RUNNING;
16281 
16282 			if (IS_IPMP(ill)) {
16283 				new_phyint_flags = went_up ?
16284 				    new_phyint_flags & ~PHYI_FAILED :
16285 				    new_phyint_flags | PHYI_FAILED;
16286 			}
16287 
16288 			if (new_phyint_flags != phyint->phyint_flags) {
16289 				phyint->phyint_flags = new_phyint_flags;
16290 				changed = B_TRUE;
16291 			}
16292 			mutex_exit(&phyint->phyint_lock);
16293 			/*
16294 			 * ill_restart_dad handles the DAD restart and routing
16295 			 * socket notification logic.
16296 			 */
16297 			if (changed) {
16298 				ill_restart_dad(phyint->phyint_illv4, went_up);
16299 				ill_restart_dad(phyint->phyint_illv6, went_up);
16300 			}
16301 			break;
16302 		}
16303 		case DL_NOTE_PROMISC_ON_PHYS: {
16304 			phyint_t *phyint = ill->ill_phyint;
16305 
16306 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16307 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16308 			mutex_enter(&phyint->phyint_lock);
16309 			phyint->phyint_flags |= PHYI_PROMISC;
16310 			mutex_exit(&phyint->phyint_lock);
16311 			break;
16312 		}
16313 		case DL_NOTE_PROMISC_OFF_PHYS: {
16314 			phyint_t *phyint = ill->ill_phyint;
16315 
16316 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16317 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16318 			mutex_enter(&phyint->phyint_lock);
16319 			phyint->phyint_flags &= ~PHYI_PROMISC;
16320 			mutex_exit(&phyint->phyint_lock);
16321 			break;
16322 		}
16323 		case DL_NOTE_CAPAB_RENEG:
16324 			/*
16325 			 * Something changed on the driver side.
16326 			 * It wants us to renegotiate the capabilities
16327 			 * on this ill. One possible cause is the aggregation
16328 			 * interface under us where a port got added or
16329 			 * went away.
16330 			 *
16331 			 * If the capability negotiation is already done
16332 			 * or is in progress, reset the capabilities and
16333 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16334 			 * so that when the ack comes back, we can start
16335 			 * the renegotiation process.
16336 			 *
16337 			 * Note that if ill_capab_reneg is already B_TRUE
16338 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16339 			 * the capability resetting request has been sent
16340 			 * and the renegotiation has not been started yet;
16341 			 * nothing needs to be done in this case.
16342 			 */
16343 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16344 			ill_capability_reset(ill, B_TRUE);
16345 			ipsq_current_finish(ipsq);
16346 			break;
16347 		default:
16348 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16349 			    "type 0x%x for DL_NOTIFY_IND\n",
16350 			    notify->dl_notification));
16351 			break;
16352 		}
16353 
16354 		/*
16355 		 * As this is an asynchronous operation, we
16356 		 * should not call ill_dlpi_done
16357 		 */
16358 		break;
16359 	}
16360 	case DL_NOTIFY_ACK: {
16361 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16362 
16363 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16364 			ill->ill_note_link = 1;
16365 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16366 		break;
16367 	}
16368 	case DL_PHYS_ADDR_ACK: {
16369 		/*
16370 		 * As part of plumbing the interface via SIOCSLIFNAME,
16371 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16372 		 * whose answers we receive here.  As each answer is received,
16373 		 * we call ill_dlpi_done() to dispatch the next request as
16374 		 * we're processing the current one.  Once all answers have
16375 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16376 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16377 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16378 		 * available, but we know the ioctl is pending on ill_wq.)
16379 		 */
16380 		uint_t	paddrlen, paddroff;
16381 		uint8_t	*addr;
16382 
16383 		paddrreq = ill->ill_phys_addr_pend;
16384 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16385 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16386 		addr = mp->b_rptr + paddroff;
16387 
16388 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16389 		if (paddrreq == DL_IPV6_TOKEN) {
16390 			/*
16391 			 * bcopy to low-order bits of ill_token
16392 			 *
16393 			 * XXX Temporary hack - currently, all known tokens
16394 			 * are 64 bits, so I'll cheat for the moment.
16395 			 */
16396 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
16397 			ill->ill_token_length = paddrlen;
16398 			break;
16399 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16400 			ASSERT(ill->ill_nd_lla_mp == NULL);
16401 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16402 			mp = NULL;
16403 			break;
16404 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
16405 			ASSERT(ill->ill_dest_addr_mp == NULL);
16406 			ill->ill_dest_addr_mp = mp;
16407 			ill->ill_dest_addr = addr;
16408 			mp = NULL;
16409 			if (ill->ill_isv6) {
16410 				ill_setdesttoken(ill);
16411 				ipif_setdestlinklocal(ill->ill_ipif);
16412 			}
16413 			break;
16414 		}
16415 
16416 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16417 		ASSERT(ill->ill_phys_addr_mp == NULL);
16418 		if (!ill->ill_ifname_pending)
16419 			break;
16420 		ill->ill_ifname_pending = 0;
16421 		if (!ioctl_aborted)
16422 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16423 		if (mp1 != NULL) {
16424 			ASSERT(connp == NULL);
16425 			q = ill->ill_wq;
16426 		}
16427 		/*
16428 		 * If any error acks received during the plumbing sequence,
16429 		 * ill_ifname_pending_err will be set. Break out and send up
16430 		 * the error to the pending ioctl.
16431 		 */
16432 		if (ill->ill_ifname_pending_err != 0) {
16433 			err = ill->ill_ifname_pending_err;
16434 			ill->ill_ifname_pending_err = 0;
16435 			break;
16436 		}
16437 
16438 		ill->ill_phys_addr_mp = mp;
16439 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
16440 		mp = NULL;
16441 
16442 		/*
16443 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
16444 		 * provider doesn't support physical addresses.  We check both
16445 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
16446 		 * not have physical addresses, but historically adversises a
16447 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
16448 		 * its DL_PHYS_ADDR_ACK.
16449 		 */
16450 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
16451 			ill->ill_phys_addr = NULL;
16452 		} else if (paddrlen != ill->ill_phys_addr_length) {
16453 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16454 			    paddrlen, ill->ill_phys_addr_length));
16455 			err = EINVAL;
16456 			break;
16457 		}
16458 
16459 		if (ill->ill_nd_lla_mp == NULL) {
16460 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16461 				err = ENOMEM;
16462 				break;
16463 			}
16464 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16465 		}
16466 
16467 		if (ill->ill_isv6) {
16468 			ill_setdefaulttoken(ill);
16469 			ipif_setlinklocal(ill->ill_ipif);
16470 		}
16471 		break;
16472 	}
16473 	case DL_OK_ACK:
16474 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16475 		    dl_primstr((int)dloa->dl_correct_primitive),
16476 		    dloa->dl_correct_primitive));
16477 		switch (dloa->dl_correct_primitive) {
16478 		case DL_ENABMULTI_REQ:
16479 		case DL_DISABMULTI_REQ:
16480 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16481 			break;
16482 		case DL_PROMISCON_REQ:
16483 		case DL_PROMISCOFF_REQ:
16484 		case DL_UNBIND_REQ:
16485 		case DL_ATTACH_REQ:
16486 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16487 			break;
16488 		}
16489 		break;
16490 	default:
16491 		break;
16492 	}
16493 
16494 	freemsg(mp);
16495 	if (mp1 == NULL)
16496 		return;
16497 
16498 	/*
16499 	 * The operation must complete without EINPROGRESS since
16500 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16501 	 * the operation will be stuck forever inside the IPSQ.
16502 	 */
16503 	ASSERT(err != EINPROGRESS);
16504 
16505 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16506 	case 0:
16507 		ipsq_current_finish(ipsq);
16508 		break;
16509 
16510 	case SIOCSLIFNAME:
16511 	case IF_UNITSEL: {
16512 		ill_t *ill_other = ILL_OTHER(ill);
16513 
16514 		/*
16515 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16516 		 * ill has a peer which is in an IPMP group, then place ill
16517 		 * into the same group.  One catch: although ifconfig plumbs
16518 		 * the appropriate IPMP meta-interface prior to plumbing this
16519 		 * ill, it is possible for multiple ifconfig applications to
16520 		 * race (or for another application to adjust plumbing), in
16521 		 * which case the IPMP meta-interface we need will be missing.
16522 		 * If so, kick the phyint out of the group.
16523 		 */
16524 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16525 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16526 			ipmp_illgrp_t	*illg;
16527 
16528 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16529 			if (illg == NULL)
16530 				ipmp_phyint_leave_grp(ill->ill_phyint);
16531 			else
16532 				ipmp_ill_join_illgrp(ill, illg);
16533 		}
16534 
16535 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16536 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16537 		else
16538 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16539 		break;
16540 	}
16541 	case SIOCLIFADDIF:
16542 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16543 		break;
16544 
16545 	default:
16546 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16547 		break;
16548 	}
16549 }
16550 
16551 /*
16552  * ip_rput_other is called by ip_rput to handle messages modifying the global
16553  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
16554  */
16555 /* ARGSUSED */
16556 void
16557 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16558 {
16559 	ill_t		*ill = q->q_ptr;
16560 	struct iocblk	*iocp;
16561 
16562 	ip1dbg(("ip_rput_other "));
16563 	if (ipsq != NULL) {
16564 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16565 		ASSERT(ipsq->ipsq_xop ==
16566 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16567 	}
16568 
16569 	switch (mp->b_datap->db_type) {
16570 	case M_ERROR:
16571 	case M_HANGUP:
16572 		/*
16573 		 * The device has a problem.  We force the ILL down.  It can
16574 		 * be brought up again manually using SIOCSIFFLAGS (via
16575 		 * ifconfig or equivalent).
16576 		 */
16577 		ASSERT(ipsq != NULL);
16578 		if (mp->b_rptr < mp->b_wptr)
16579 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16580 		if (ill->ill_error == 0)
16581 			ill->ill_error = ENXIO;
16582 		if (!ill_down_start(q, mp))
16583 			return;
16584 		ipif_all_down_tail(ipsq, q, mp, NULL);
16585 		break;
16586 	case M_IOCNAK: {
16587 		iocp = (struct iocblk *)mp->b_rptr;
16588 
16589 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
16590 		/*
16591 		 * If this was the first attempt, turn off the fastpath
16592 		 * probing.
16593 		 */
16594 		mutex_enter(&ill->ill_lock);
16595 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16596 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
16597 			mutex_exit(&ill->ill_lock);
16598 			ill_fastpath_nack(ill);
16599 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
16600 			    ill->ill_name));
16601 		} else {
16602 			mutex_exit(&ill->ill_lock);
16603 		}
16604 		freemsg(mp);
16605 		break;
16606 	}
16607 	default:
16608 		ASSERT(0);
16609 		break;
16610 	}
16611 }
16612 
16613 /*
16614  * NOTE : This function does not ire_refrele the ire argument passed in.
16615  *
16616  * IPQoS notes
16617  * IP policy is invoked twice for a forwarded packet, once on the read side
16618  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16619  * enabled. An additional parameter, in_ill, has been added for this purpose.
16620  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16621  * because ip_mroute drops this information.
16622  *
16623  */
16624 void
16625 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16626 {
16627 	uint32_t	old_pkt_len;
16628 	uint32_t	pkt_len;
16629 	queue_t	*q;
16630 	uint32_t	sum;
16631 #define	rptr	((uchar_t *)ipha)
16632 	uint32_t	max_frag;
16633 	uint32_t	ill_index;
16634 	ill_t		*out_ill;
16635 	mib2_ipIfStatsEntry_t *mibptr;
16636 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16637 
16638 	/* Get the ill_index of the incoming ILL */
16639 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16640 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16641 
16642 	/* Initiate Read side IPPF processing */
16643 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16644 		ip_process(IPP_FWD_IN, &mp, ill_index);
16645 		if (mp == NULL) {
16646 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16647 			    "during IPPF processing\n"));
16648 			return;
16649 		}
16650 	}
16651 
16652 	/* Adjust the checksum to reflect the ttl decrement. */
16653 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16654 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16655 
16656 	if (ipha->ipha_ttl-- <= 1) {
16657 		if (ip_csum_hdr(ipha)) {
16658 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16659 			goto drop_pkt;
16660 		}
16661 		/*
16662 		 * Note: ire_stq this will be NULL for multicast
16663 		 * datagrams using the long path through arp (the IRE
16664 		 * is not an IRE_CACHE). This should not cause
16665 		 * problems since we don't generate ICMP errors for
16666 		 * multicast packets.
16667 		 */
16668 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16669 		q = ire->ire_stq;
16670 		if (q != NULL) {
16671 			/* Sent by forwarding path, and router is global zone */
16672 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16673 			    GLOBAL_ZONEID, ipst);
16674 		} else
16675 			freemsg(mp);
16676 		return;
16677 	}
16678 
16679 	/*
16680 	 * Don't forward if the interface is down
16681 	 */
16682 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16683 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16684 		ip2dbg(("ip_rput_forward:interface is down\n"));
16685 		goto drop_pkt;
16686 	}
16687 
16688 	/* Get the ill_index of the outgoing ILL */
16689 	out_ill = ire_to_ill(ire);
16690 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16691 
16692 	DTRACE_PROBE4(ip4__forwarding__start,
16693 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16694 
16695 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16696 	    ipst->ips_ipv4firewall_forwarding,
16697 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16698 
16699 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16700 
16701 	if (mp == NULL)
16702 		return;
16703 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16704 
16705 	if (is_system_labeled()) {
16706 		mblk_t *mp1;
16707 
16708 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16709 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16710 			goto drop_pkt;
16711 		}
16712 		/* Size may have changed */
16713 		mp = mp1;
16714 		ipha = (ipha_t *)mp->b_rptr;
16715 		pkt_len = ntohs(ipha->ipha_length);
16716 	}
16717 
16718 	/* Check if there are options to update */
16719 	if (!IS_SIMPLE_IPH(ipha)) {
16720 		if (ip_csum_hdr(ipha)) {
16721 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16722 			goto drop_pkt;
16723 		}
16724 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16725 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16726 			return;
16727 		}
16728 
16729 		ipha->ipha_hdr_checksum = 0;
16730 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16731 	}
16732 	max_frag = ire->ire_max_frag;
16733 	if (pkt_len > max_frag) {
16734 		/*
16735 		 * It needs fragging on its way out.  We haven't
16736 		 * verified the header checksum yet.  Since we
16737 		 * are going to put a surely good checksum in the
16738 		 * outgoing header, we have to make sure that it
16739 		 * was good coming in.
16740 		 */
16741 		if (ip_csum_hdr(ipha)) {
16742 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16743 			goto drop_pkt;
16744 		}
16745 		/* Initiate Write side IPPF processing */
16746 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16747 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16748 			if (mp == NULL) {
16749 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16750 				    " during IPPF processing\n"));
16751 				return;
16752 			}
16753 		}
16754 		/*
16755 		 * Handle labeled packet resizing.
16756 		 *
16757 		 * If we have added a label, inform ip_wput_frag() of its
16758 		 * effect on the MTU for ICMP messages.
16759 		 */
16760 		if (pkt_len > old_pkt_len) {
16761 			uint32_t secopt_size;
16762 
16763 			secopt_size = pkt_len - old_pkt_len;
16764 			if (secopt_size < max_frag)
16765 				max_frag -= secopt_size;
16766 		}
16767 
16768 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16769 		    GLOBAL_ZONEID, ipst, NULL);
16770 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16771 		return;
16772 	}
16773 
16774 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16775 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16776 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16777 	    ipst->ips_ipv4firewall_physical_out,
16778 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16779 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16780 	if (mp == NULL)
16781 		return;
16782 
16783 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16784 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16785 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16786 	/* ip_xmit_v4 always consumes the packet */
16787 	return;
16788 
16789 drop_pkt:;
16790 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16791 	freemsg(mp);
16792 #undef	rptr
16793 }
16794 
16795 void
16796 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16797 {
16798 	ire_t	*ire;
16799 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16800 
16801 	ASSERT(!ipif->ipif_isv6);
16802 	/*
16803 	 * Find an IRE which matches the destination and the outgoing
16804 	 * queue in the cache table. All we need is an IRE_CACHE which
16805 	 * is pointing at ipif->ipif_ill.
16806 	 */
16807 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16808 		dst = ipif->ipif_pp_dst_addr;
16809 
16810 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16811 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16812 	if (ire == NULL) {
16813 		/*
16814 		 * Mark this packet to make it be delivered to
16815 		 * ip_rput_forward after the new ire has been
16816 		 * created.
16817 		 */
16818 		mp->b_prev = NULL;
16819 		mp->b_next = mp;
16820 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16821 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16822 	} else {
16823 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16824 		IRE_REFRELE(ire);
16825 	}
16826 }
16827 
16828 /* Update any source route, record route or timestamp options */
16829 static int
16830 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16831 {
16832 	ipoptp_t	opts;
16833 	uchar_t		*opt;
16834 	uint8_t		optval;
16835 	uint8_t		optlen;
16836 	ipaddr_t	dst;
16837 	uint32_t	ts;
16838 	ire_t		*dst_ire = NULL;
16839 	ire_t		*tmp_ire = NULL;
16840 	timestruc_t	now;
16841 
16842 	ip2dbg(("ip_rput_forward_options\n"));
16843 	dst = ipha->ipha_dst;
16844 	for (optval = ipoptp_first(&opts, ipha);
16845 	    optval != IPOPT_EOL;
16846 	    optval = ipoptp_next(&opts)) {
16847 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16848 		opt = opts.ipoptp_cur;
16849 		optlen = opts.ipoptp_len;
16850 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16851 		    optval, opts.ipoptp_len));
16852 		switch (optval) {
16853 			uint32_t off;
16854 		case IPOPT_SSRR:
16855 		case IPOPT_LSRR:
16856 			/* Check if adminstratively disabled */
16857 			if (!ipst->ips_ip_forward_src_routed) {
16858 				if (ire->ire_stq != NULL) {
16859 					/*
16860 					 * Sent by forwarding path, and router
16861 					 * is global zone
16862 					 */
16863 					icmp_unreachable(ire->ire_stq, mp,
16864 					    ICMP_SOURCE_ROUTE_FAILED,
16865 					    GLOBAL_ZONEID, ipst);
16866 				} else {
16867 					ip0dbg(("ip_rput_forward_options: "
16868 					    "unable to send unreach\n"));
16869 					freemsg(mp);
16870 				}
16871 				return (-1);
16872 			}
16873 
16874 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16875 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16876 			if (dst_ire == NULL) {
16877 				/*
16878 				 * Must be partial since ip_rput_options
16879 				 * checked for strict.
16880 				 */
16881 				break;
16882 			}
16883 			off = opt[IPOPT_OFFSET];
16884 			off--;
16885 		redo_srr:
16886 			if (optlen < IP_ADDR_LEN ||
16887 			    off > optlen - IP_ADDR_LEN) {
16888 				/* End of source route */
16889 				ip1dbg((
16890 				    "ip_rput_forward_options: end of SR\n"));
16891 				ire_refrele(dst_ire);
16892 				break;
16893 			}
16894 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16895 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16896 			    IP_ADDR_LEN);
16897 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16898 			    ntohl(dst)));
16899 
16900 			/*
16901 			 * Check if our address is present more than
16902 			 * once as consecutive hops in source route.
16903 			 */
16904 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16905 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16906 			if (tmp_ire != NULL) {
16907 				ire_refrele(tmp_ire);
16908 				off += IP_ADDR_LEN;
16909 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16910 				goto redo_srr;
16911 			}
16912 			ipha->ipha_dst = dst;
16913 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16914 			ire_refrele(dst_ire);
16915 			break;
16916 		case IPOPT_RR:
16917 			off = opt[IPOPT_OFFSET];
16918 			off--;
16919 			if (optlen < IP_ADDR_LEN ||
16920 			    off > optlen - IP_ADDR_LEN) {
16921 				/* No more room - ignore */
16922 				ip1dbg((
16923 				    "ip_rput_forward_options: end of RR\n"));
16924 				break;
16925 			}
16926 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16927 			    IP_ADDR_LEN);
16928 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16929 			break;
16930 		case IPOPT_TS:
16931 			/* Insert timestamp if there is room */
16932 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16933 			case IPOPT_TS_TSONLY:
16934 				off = IPOPT_TS_TIMELEN;
16935 				break;
16936 			case IPOPT_TS_PRESPEC:
16937 			case IPOPT_TS_PRESPEC_RFC791:
16938 				/* Verify that the address matched */
16939 				off = opt[IPOPT_OFFSET] - 1;
16940 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16941 				dst_ire = ire_ctable_lookup(dst, 0,
16942 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16943 				    MATCH_IRE_TYPE, ipst);
16944 				if (dst_ire == NULL) {
16945 					/* Not for us */
16946 					break;
16947 				}
16948 				ire_refrele(dst_ire);
16949 				/* FALLTHRU */
16950 			case IPOPT_TS_TSANDADDR:
16951 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16952 				break;
16953 			default:
16954 				/*
16955 				 * ip_*put_options should have already
16956 				 * dropped this packet.
16957 				 */
16958 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16959 				    "unknown IT - bug in ip_rput_options?\n");
16960 				return (0);	/* Keep "lint" happy */
16961 			}
16962 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16963 				/* Increase overflow counter */
16964 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16965 				opt[IPOPT_POS_OV_FLG] =
16966 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16967 				    (off << 4));
16968 				break;
16969 			}
16970 			off = opt[IPOPT_OFFSET] - 1;
16971 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16972 			case IPOPT_TS_PRESPEC:
16973 			case IPOPT_TS_PRESPEC_RFC791:
16974 			case IPOPT_TS_TSANDADDR:
16975 				bcopy(&ire->ire_src_addr,
16976 				    (char *)opt + off, IP_ADDR_LEN);
16977 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16978 				/* FALLTHRU */
16979 			case IPOPT_TS_TSONLY:
16980 				off = opt[IPOPT_OFFSET] - 1;
16981 				/* Compute # of milliseconds since midnight */
16982 				gethrestime(&now);
16983 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16984 				    now.tv_nsec / (NANOSEC / MILLISEC);
16985 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16986 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16987 				break;
16988 			}
16989 			break;
16990 		}
16991 	}
16992 	return (0);
16993 }
16994 
16995 /*
16996  * This is called after processing at least one of AH/ESP headers.
16997  *
16998  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16999  * the actual, physical interface on which the packet was received,
17000  * but, when ip_strict_dst_multihoming is set to 1, could be the
17001  * interface which had the ipha_dst configured when the packet went
17002  * through ip_rput. The ill_index corresponding to the recv_ill
17003  * is saved in ipsec_in_rill_index
17004  *
17005  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17006  * cannot assume "ire" points to valid data for any IPv6 cases.
17007  */
17008 void
17009 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17010 {
17011 	mblk_t *mp;
17012 	ipaddr_t dst;
17013 	in6_addr_t *v6dstp;
17014 	ipha_t *ipha;
17015 	ip6_t *ip6h;
17016 	ipsec_in_t *ii;
17017 	boolean_t ill_need_rele = B_FALSE;
17018 	boolean_t rill_need_rele = B_FALSE;
17019 	boolean_t ire_need_rele = B_FALSE;
17020 	netstack_t	*ns;
17021 	ip_stack_t	*ipst;
17022 
17023 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17024 	ASSERT(ii->ipsec_in_ill_index != 0);
17025 	ns = ii->ipsec_in_ns;
17026 	ASSERT(ii->ipsec_in_ns != NULL);
17027 	ipst = ns->netstack_ip;
17028 
17029 	mp = ipsec_mp->b_cont;
17030 	ASSERT(mp != NULL);
17031 
17032 	if (ill == NULL) {
17033 		ASSERT(recv_ill == NULL);
17034 		/*
17035 		 * We need to get the original queue on which ip_rput_local
17036 		 * or ip_rput_data_v6 was called.
17037 		 */
17038 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17039 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17040 		ill_need_rele = B_TRUE;
17041 
17042 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17043 			recv_ill = ill_lookup_on_ifindex(
17044 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17045 			    NULL, NULL, NULL, NULL, ipst);
17046 			rill_need_rele = B_TRUE;
17047 		} else {
17048 			recv_ill = ill;
17049 		}
17050 
17051 		if ((ill == NULL) || (recv_ill == NULL)) {
17052 			ip0dbg(("ip_fanout_proto_again: interface "
17053 			    "disappeared\n"));
17054 			if (ill != NULL)
17055 				ill_refrele(ill);
17056 			if (recv_ill != NULL)
17057 				ill_refrele(recv_ill);
17058 			freemsg(ipsec_mp);
17059 			return;
17060 		}
17061 	}
17062 
17063 	ASSERT(ill != NULL && recv_ill != NULL);
17064 
17065 	if (mp->b_datap->db_type == M_CTL) {
17066 		/*
17067 		 * AH/ESP is returning the ICMP message after
17068 		 * removing their headers. Fanout again till
17069 		 * it gets to the right protocol.
17070 		 */
17071 		if (ii->ipsec_in_v4) {
17072 			icmph_t *icmph;
17073 			int iph_hdr_length;
17074 			int hdr_length;
17075 
17076 			ipha = (ipha_t *)mp->b_rptr;
17077 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17078 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17079 			ipha = (ipha_t *)&icmph[1];
17080 			hdr_length = IPH_HDR_LENGTH(ipha);
17081 			/*
17082 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17083 			 * Reset the type to M_DATA.
17084 			 */
17085 			mp->b_datap->db_type = M_DATA;
17086 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17087 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17088 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17089 		} else {
17090 			icmp6_t *icmp6;
17091 			int hdr_length;
17092 
17093 			ip6h = (ip6_t *)mp->b_rptr;
17094 			/* Don't call hdr_length_v6() unless you have to. */
17095 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17096 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17097 			else
17098 				hdr_length = IPV6_HDR_LEN;
17099 
17100 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17101 			/*
17102 			 * icmp_inbound_error_fanout_v6 may need to do
17103 			 * pullupmsg.  Reset the type to M_DATA.
17104 			 */
17105 			mp->b_datap->db_type = M_DATA;
17106 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17107 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17108 			    ii->ipsec_in_zoneid);
17109 		}
17110 		if (ill_need_rele)
17111 			ill_refrele(ill);
17112 		if (rill_need_rele)
17113 			ill_refrele(recv_ill);
17114 		return;
17115 	}
17116 
17117 	if (ii->ipsec_in_v4) {
17118 		ipha = (ipha_t *)mp->b_rptr;
17119 		dst = ipha->ipha_dst;
17120 		if (CLASSD(dst)) {
17121 			/*
17122 			 * Multicast has to be delivered to all streams.
17123 			 */
17124 			dst = INADDR_BROADCAST;
17125 		}
17126 
17127 		if (ire == NULL) {
17128 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17129 			    msg_getlabel(mp), ipst);
17130 			if (ire == NULL) {
17131 				if (ill_need_rele)
17132 					ill_refrele(ill);
17133 				if (rill_need_rele)
17134 					ill_refrele(recv_ill);
17135 				ip1dbg(("ip_fanout_proto_again: "
17136 				    "IRE not found"));
17137 				freemsg(ipsec_mp);
17138 				return;
17139 			}
17140 			ire_need_rele = B_TRUE;
17141 		}
17142 
17143 		switch (ipha->ipha_protocol) {
17144 		case IPPROTO_UDP:
17145 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17146 			    recv_ill);
17147 			if (ire_need_rele)
17148 				ire_refrele(ire);
17149 			break;
17150 		case IPPROTO_TCP:
17151 			if (!ire_need_rele)
17152 				IRE_REFHOLD(ire);
17153 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17154 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17155 			IRE_REFRELE(ire);
17156 			if (mp != NULL) {
17157 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17158 				    mp, 1, SQ_PROCESS,
17159 				    SQTAG_IP_PROTO_AGAIN);
17160 			}
17161 			break;
17162 		case IPPROTO_SCTP:
17163 			if (!ire_need_rele)
17164 				IRE_REFHOLD(ire);
17165 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17166 			    ipsec_mp, 0, ill->ill_rq, dst);
17167 			break;
17168 		case IPPROTO_ENCAP:
17169 		case IPPROTO_IPV6:
17170 			if (ip_iptun_input(ipsec_mp, mp, ipha, ill, ire,
17171 			    ill->ill_ipst)) {
17172 				/*
17173 				 * If we made it here, we don't need to worry
17174 				 * about the raw-socket/protocol fanout.
17175 				 */
17176 				if (ire_need_rele)
17177 					ire_refrele(ire);
17178 				break;
17179 			}
17180 			/* else FALLTHRU */
17181 		default:
17182 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17183 			    recv_ill, 0);
17184 			if (ire_need_rele)
17185 				ire_refrele(ire);
17186 			break;
17187 		}
17188 	} else {
17189 		uint32_t rput_flags = 0;
17190 
17191 		ip6h = (ip6_t *)mp->b_rptr;
17192 		v6dstp = &ip6h->ip6_dst;
17193 		/*
17194 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17195 		 * address.
17196 		 *
17197 		 * Currently, we don't store that state in the IPSEC_IN
17198 		 * message, and we may need to.
17199 		 */
17200 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17201 		    IP6_IN_LLMCAST : 0);
17202 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17203 		    NULL, NULL);
17204 	}
17205 	if (ill_need_rele)
17206 		ill_refrele(ill);
17207 	if (rill_need_rele)
17208 		ill_refrele(recv_ill);
17209 }
17210 
17211 /*
17212  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17213  * returns 'true' if there are still fragments left on the queue, in
17214  * which case we restart the timer.
17215  */
17216 void
17217 ill_frag_timer(void *arg)
17218 {
17219 	ill_t	*ill = (ill_t *)arg;
17220 	boolean_t frag_pending;
17221 	ip_stack_t	*ipst = ill->ill_ipst;
17222 	time_t	timeout;
17223 
17224 	mutex_enter(&ill->ill_lock);
17225 	ASSERT(!ill->ill_fragtimer_executing);
17226 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17227 		ill->ill_frag_timer_id = 0;
17228 		mutex_exit(&ill->ill_lock);
17229 		return;
17230 	}
17231 	ill->ill_fragtimer_executing = 1;
17232 	mutex_exit(&ill->ill_lock);
17233 
17234 	if (ill->ill_isv6)
17235 		timeout = ipst->ips_ipv6_frag_timeout;
17236 	else
17237 		timeout = ipst->ips_ip_g_frag_timeout;
17238 
17239 	frag_pending = ill_frag_timeout(ill, timeout);
17240 
17241 	/*
17242 	 * Restart the timer, if we have fragments pending or if someone
17243 	 * wanted us to be scheduled again.
17244 	 */
17245 	mutex_enter(&ill->ill_lock);
17246 	ill->ill_fragtimer_executing = 0;
17247 	ill->ill_frag_timer_id = 0;
17248 	if (frag_pending || ill->ill_fragtimer_needrestart)
17249 		ill_frag_timer_start(ill);
17250 	mutex_exit(&ill->ill_lock);
17251 }
17252 
17253 void
17254 ill_frag_timer_start(ill_t *ill)
17255 {
17256 	ip_stack_t	*ipst = ill->ill_ipst;
17257 	clock_t	timeo_ms;
17258 
17259 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17260 
17261 	/* If the ill is closing or opening don't proceed */
17262 	if (ill->ill_state_flags & ILL_CONDEMNED)
17263 		return;
17264 
17265 	if (ill->ill_fragtimer_executing) {
17266 		/*
17267 		 * ill_frag_timer is currently executing. Just record the
17268 		 * the fact that we want the timer to be restarted.
17269 		 * ill_frag_timer will post a timeout before it returns,
17270 		 * ensuring it will be called again.
17271 		 */
17272 		ill->ill_fragtimer_needrestart = 1;
17273 		return;
17274 	}
17275 
17276 	if (ill->ill_frag_timer_id == 0) {
17277 		if (ill->ill_isv6)
17278 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17279 		else
17280 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17281 		/*
17282 		 * The timer is neither running nor is the timeout handler
17283 		 * executing. Post a timeout so that ill_frag_timer will be
17284 		 * called
17285 		 */
17286 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17287 		    MSEC_TO_TICK(timeo_ms >> 1));
17288 		ill->ill_fragtimer_needrestart = 0;
17289 	}
17290 }
17291 
17292 /*
17293  * This routine is needed for loopback when forwarding multicasts.
17294  *
17295  * IPQoS Notes:
17296  * IPPF processing is done in fanout routines.
17297  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17298  * processing for IPsec packets is done when it comes back in clear.
17299  * NOTE : The callers of this function need to do the ire_refrele for the
17300  *	  ire that is being passed in.
17301  */
17302 void
17303 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17304     ill_t *recv_ill, uint32_t esp_udp_ports)
17305 {
17306 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17307 	ill_t	*ill = (ill_t *)q->q_ptr;
17308 	uint32_t	sum;
17309 	uint32_t	u1;
17310 	uint32_t	u2;
17311 	int		hdr_length;
17312 	boolean_t	mctl_present;
17313 	mblk_t		*first_mp = mp;
17314 	mblk_t		*hada_mp = NULL;
17315 	ipha_t		*inner_ipha;
17316 	ip_stack_t	*ipst;
17317 
17318 	ASSERT(recv_ill != NULL);
17319 	ipst = recv_ill->ill_ipst;
17320 
17321 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17322 	    "ip_rput_locl_start: q %p", q);
17323 
17324 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17325 	ASSERT(ill != NULL);
17326 
17327 #define	rptr	((uchar_t *)ipha)
17328 #define	iphs	((uint16_t *)ipha)
17329 
17330 	/*
17331 	 * no UDP or TCP packet should come here anymore.
17332 	 */
17333 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17334 	    ipha->ipha_protocol != IPPROTO_UDP);
17335 
17336 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17337 	if (mctl_present &&
17338 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17339 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17340 
17341 		/*
17342 		 * It's an IPsec accelerated packet.
17343 		 * Keep a pointer to the data attributes around until
17344 		 * we allocate the ipsec_info_t.
17345 		 */
17346 		IPSECHW_DEBUG(IPSECHW_PKT,
17347 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17348 		hada_mp = first_mp;
17349 		hada_mp->b_cont = NULL;
17350 		/*
17351 		 * Since it is accelerated, it comes directly from
17352 		 * the ill and the data attributes is followed by
17353 		 * the packet data.
17354 		 */
17355 		ASSERT(mp->b_datap->db_type != M_CTL);
17356 		first_mp = mp;
17357 		mctl_present = B_FALSE;
17358 	}
17359 
17360 	/*
17361 	 * IF M_CTL is not present, then ipsec_in_is_secure
17362 	 * should return B_TRUE. There is a case where loopback
17363 	 * packets has an M_CTL in the front with all the
17364 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17365 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17366 	 * packets never comes here, it is safe to ASSERT the
17367 	 * following.
17368 	 */
17369 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17370 
17371 	/*
17372 	 * Also, we should never have an mctl_present if this is an
17373 	 * ESP-in-UDP packet.
17374 	 */
17375 	ASSERT(!mctl_present || !esp_in_udp_packet);
17376 
17377 	/* u1 is # words of IP options */
17378 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17379 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17380 
17381 	/*
17382 	 * Don't verify header checksum if we just removed UDP header or
17383 	 * packet is coming back from AH/ESP.
17384 	 */
17385 	if (!esp_in_udp_packet && !mctl_present) {
17386 		if (u1) {
17387 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17388 				if (hada_mp != NULL)
17389 					freemsg(hada_mp);
17390 				return;
17391 			}
17392 		} else {
17393 			/* Check the IP header checksum.  */
17394 #define	uph	((uint16_t *)ipha)
17395 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17396 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17397 #undef  uph
17398 			/* finish doing IP checksum */
17399 			sum = (sum & 0xFFFF) + (sum >> 16);
17400 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17401 			if (sum && sum != 0xFFFF) {
17402 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17403 				goto drop_pkt;
17404 			}
17405 		}
17406 	}
17407 
17408 	/*
17409 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17410 	 * might be called more than once for secure packets, count only
17411 	 * the first time.
17412 	 */
17413 	if (!mctl_present) {
17414 		UPDATE_IB_PKT_COUNT(ire);
17415 		ire->ire_last_used_time = lbolt;
17416 	}
17417 
17418 	/* Check for fragmentation offset. */
17419 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17420 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17421 	if (u1) {
17422 		/*
17423 		 * We re-assemble fragments before we do the AH/ESP
17424 		 * processing. Thus, M_CTL should not be present
17425 		 * while we are re-assembling.
17426 		 */
17427 		ASSERT(!mctl_present);
17428 		ASSERT(first_mp == mp);
17429 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17430 			return;
17431 
17432 		/*
17433 		 * Make sure that first_mp points back to mp as
17434 		 * the mp we came in with could have changed in
17435 		 * ip_rput_fragment().
17436 		 */
17437 		ipha = (ipha_t *)mp->b_rptr;
17438 		first_mp = mp;
17439 	}
17440 
17441 	/*
17442 	 * Clear hardware checksumming flag as it is currently only
17443 	 * used by TCP and UDP.
17444 	 */
17445 	DB_CKSUMFLAGS(mp) = 0;
17446 
17447 	/* Now we have a complete datagram, destined for this machine. */
17448 	u1 = IPH_HDR_LENGTH(ipha);
17449 	switch (ipha->ipha_protocol) {
17450 	case IPPROTO_ICMP: {
17451 		ire_t		*ire_zone;
17452 		ilm_t		*ilm;
17453 		mblk_t		*mp1;
17454 		zoneid_t	last_zoneid;
17455 		ilm_walker_t	ilw;
17456 
17457 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17458 			ASSERT(ire->ire_type == IRE_BROADCAST);
17459 
17460 			/*
17461 			 * In the multicast case, applications may have joined
17462 			 * the group from different zones, so we need to deliver
17463 			 * the packet to each of them. Loop through the
17464 			 * multicast memberships structures (ilm) on the receive
17465 			 * ill and send a copy of the packet up each matching
17466 			 * one. However, we don't do this for multicasts sent on
17467 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17468 			 * they must stay in the sender's zone.
17469 			 *
17470 			 * ilm_add_v6() ensures that ilms in the same zone are
17471 			 * contiguous in the ill_ilm list. We use this property
17472 			 * to avoid sending duplicates needed when two
17473 			 * applications in the same zone join the same group on
17474 			 * different logical interfaces: we ignore the ilm if
17475 			 * its zoneid is the same as the last matching one.
17476 			 * In addition, the sending of the packet for
17477 			 * ire_zoneid is delayed until all of the other ilms
17478 			 * have been exhausted.
17479 			 */
17480 			last_zoneid = -1;
17481 			ilm = ilm_walker_start(&ilw, recv_ill);
17482 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17483 				if (ipha->ipha_dst != ilm->ilm_addr ||
17484 				    ilm->ilm_zoneid == last_zoneid ||
17485 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17486 				    ilm->ilm_zoneid == ALL_ZONES ||
17487 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17488 					continue;
17489 				mp1 = ip_copymsg(first_mp);
17490 				if (mp1 == NULL)
17491 					continue;
17492 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17493 				    0, sum, mctl_present, B_TRUE,
17494 				    recv_ill, ilm->ilm_zoneid);
17495 				last_zoneid = ilm->ilm_zoneid;
17496 			}
17497 			ilm_walker_finish(&ilw);
17498 		} else if (ire->ire_type == IRE_BROADCAST) {
17499 			/*
17500 			 * In the broadcast case, there may be many zones
17501 			 * which need a copy of the packet delivered to them.
17502 			 * There is one IRE_BROADCAST per broadcast address
17503 			 * and per zone; we walk those using a helper function.
17504 			 * In addition, the sending of the packet for ire is
17505 			 * delayed until all of the other ires have been
17506 			 * processed.
17507 			 */
17508 			IRB_REFHOLD(ire->ire_bucket);
17509 			ire_zone = NULL;
17510 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17511 			    ire)) != NULL) {
17512 				mp1 = ip_copymsg(first_mp);
17513 				if (mp1 == NULL)
17514 					continue;
17515 
17516 				UPDATE_IB_PKT_COUNT(ire_zone);
17517 				ire_zone->ire_last_used_time = lbolt;
17518 				icmp_inbound(q, mp1, B_TRUE, ill,
17519 				    0, sum, mctl_present, B_TRUE,
17520 				    recv_ill, ire_zone->ire_zoneid);
17521 			}
17522 			IRB_REFRELE(ire->ire_bucket);
17523 		}
17524 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17525 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17526 		    ire->ire_zoneid);
17527 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17528 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17529 		return;
17530 	}
17531 	case IPPROTO_IGMP:
17532 		/*
17533 		 * If we are not willing to accept IGMP packets in clear,
17534 		 * then check with global policy.
17535 		 */
17536 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17537 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17538 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17539 			if (first_mp == NULL)
17540 				return;
17541 		}
17542 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17543 			freemsg(first_mp);
17544 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17545 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17546 			return;
17547 		}
17548 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17549 			/* Bad packet - discarded by igmp_input */
17550 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17551 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17552 			if (mctl_present)
17553 				freeb(first_mp);
17554 			return;
17555 		}
17556 		/*
17557 		 * igmp_input() may have returned the pulled up message.
17558 		 * So first_mp and ipha need to be reinitialized.
17559 		 */
17560 		ipha = (ipha_t *)mp->b_rptr;
17561 		if (mctl_present)
17562 			first_mp->b_cont = mp;
17563 		else
17564 			first_mp = mp;
17565 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17566 		    connf_head != NULL) {
17567 			/* No user-level listener for IGMP packets */
17568 			goto drop_pkt;
17569 		}
17570 		/* deliver to local raw users */
17571 		break;
17572 	case IPPROTO_PIM:
17573 		/*
17574 		 * If we are not willing to accept PIM packets in clear,
17575 		 * then check with global policy.
17576 		 */
17577 		if (ipst->ips_pim_accept_clear_messages == 0) {
17578 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17579 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17580 			if (first_mp == NULL)
17581 				return;
17582 		}
17583 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17584 			freemsg(first_mp);
17585 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17586 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17587 			return;
17588 		}
17589 		if (pim_input(q, mp, ill) != 0) {
17590 			/* Bad packet - discarded by pim_input */
17591 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17592 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17593 			if (mctl_present)
17594 				freeb(first_mp);
17595 			return;
17596 		}
17597 
17598 		/*
17599 		 * pim_input() may have pulled up the message so ipha needs to
17600 		 * be reinitialized.
17601 		 */
17602 		ipha = (ipha_t *)mp->b_rptr;
17603 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17604 		    connf_head != NULL) {
17605 			/* No user-level listener for PIM packets */
17606 			goto drop_pkt;
17607 		}
17608 		/* deliver to local raw users */
17609 		break;
17610 	case IPPROTO_ENCAP:
17611 		/*
17612 		 * Handle self-encapsulated packets (IP-in-IP where
17613 		 * the inner addresses == the outer addresses).
17614 		 */
17615 		hdr_length = IPH_HDR_LENGTH(ipha);
17616 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17617 		    mp->b_wptr) {
17618 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17619 			    sizeof (ipha_t) - mp->b_rptr)) {
17620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17621 				freemsg(first_mp);
17622 				return;
17623 			}
17624 			ipha = (ipha_t *)mp->b_rptr;
17625 		}
17626 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17627 		/*
17628 		 * Check the sanity of the inner IP header.
17629 		 */
17630 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17631 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17632 			freemsg(first_mp);
17633 			return;
17634 		}
17635 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17636 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17637 			freemsg(first_mp);
17638 			return;
17639 		}
17640 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17641 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17642 			ipsec_in_t *ii;
17643 
17644 			/*
17645 			 * Self-encapsulated tunnel packet. Remove
17646 			 * the outer IP header and fanout again.
17647 			 * We also need to make sure that the inner
17648 			 * header is pulled up until options.
17649 			 */
17650 			mp->b_rptr = (uchar_t *)inner_ipha;
17651 			ipha = inner_ipha;
17652 			hdr_length = IPH_HDR_LENGTH(ipha);
17653 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17654 				if (!pullupmsg(mp, (uchar_t *)ipha +
17655 				    + hdr_length - mp->b_rptr)) {
17656 					freemsg(first_mp);
17657 					return;
17658 				}
17659 				ipha = (ipha_t *)mp->b_rptr;
17660 			}
17661 			if (hdr_length > sizeof (ipha_t)) {
17662 				/* We got options on the inner packet. */
17663 				ipaddr_t dst = ipha->ipha_dst;
17664 
17665 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17666 				    -1) {
17667 					/* Bad options! */
17668 					return;
17669 				}
17670 				if (dst != ipha->ipha_dst) {
17671 					/*
17672 					 * Someone put a source-route in
17673 					 * the inside header of a self-
17674 					 * encapsulated packet.  Drop it
17675 					 * with extreme prejudice and let
17676 					 * the sender know.
17677 					 */
17678 					icmp_unreachable(q, first_mp,
17679 					    ICMP_SOURCE_ROUTE_FAILED,
17680 					    recv_ill->ill_zoneid, ipst);
17681 					return;
17682 				}
17683 			}
17684 			if (!mctl_present) {
17685 				ASSERT(first_mp == mp);
17686 				/*
17687 				 * This means that somebody is sending
17688 				 * Self-encapsualted packets without AH/ESP.
17689 				 * If AH/ESP was present, we would have already
17690 				 * allocated the first_mp.
17691 				 *
17692 				 * Send this packet to find a tunnel endpoint.
17693 				 * if I can't find one, an ICMP
17694 				 * PROTOCOL_UNREACHABLE will get sent.
17695 				 */
17696 				goto fanout;
17697 			}
17698 			/*
17699 			 * We generally store the ill_index if we need to
17700 			 * do IPsec processing as we lose the ill queue when
17701 			 * we come back. But in this case, we never should
17702 			 * have to store the ill_index here as it should have
17703 			 * been stored previously when we processed the
17704 			 * AH/ESP header in this routine or for non-ipsec
17705 			 * cases, we still have the queue. But for some bad
17706 			 * packets from the wire, we can get to IPsec after
17707 			 * this and we better store the index for that case.
17708 			 */
17709 			ill = (ill_t *)q->q_ptr;
17710 			ii = (ipsec_in_t *)first_mp->b_rptr;
17711 			ii->ipsec_in_ill_index =
17712 			    ill->ill_phyint->phyint_ifindex;
17713 			ii->ipsec_in_rill_index =
17714 			    recv_ill->ill_phyint->phyint_ifindex;
17715 			if (ii->ipsec_in_decaps) {
17716 				/*
17717 				 * This packet is self-encapsulated multiple
17718 				 * times. We don't want to recurse infinitely.
17719 				 * To keep it simple, drop the packet.
17720 				 */
17721 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17722 				freemsg(first_mp);
17723 				return;
17724 			}
17725 			ii->ipsec_in_decaps = B_TRUE;
17726 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17727 			    ire);
17728 			return;
17729 		}
17730 		break;
17731 	case IPPROTO_AH:
17732 	case IPPROTO_ESP: {
17733 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17734 
17735 		/*
17736 		 * Fast path for AH/ESP. If this is the first time
17737 		 * we are sending a datagram to AH/ESP, allocate
17738 		 * a IPSEC_IN message and prepend it. Otherwise,
17739 		 * just fanout.
17740 		 */
17741 
17742 		int ipsec_rc;
17743 		ipsec_in_t *ii;
17744 		netstack_t *ns = ipst->ips_netstack;
17745 
17746 		IP_STAT(ipst, ipsec_proto_ahesp);
17747 		if (!mctl_present) {
17748 			ASSERT(first_mp == mp);
17749 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17750 			if (first_mp == NULL) {
17751 				ip1dbg(("ip_proto_input: IPSEC_IN "
17752 				    "allocation failure.\n"));
17753 				freemsg(hada_mp); /* okay ifnull */
17754 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17755 				freemsg(mp);
17756 				return;
17757 			}
17758 			/*
17759 			 * Store the ill_index so that when we come back
17760 			 * from IPsec we ride on the same queue.
17761 			 */
17762 			ill = (ill_t *)q->q_ptr;
17763 			ii = (ipsec_in_t *)first_mp->b_rptr;
17764 			ii->ipsec_in_ill_index =
17765 			    ill->ill_phyint->phyint_ifindex;
17766 			ii->ipsec_in_rill_index =
17767 			    recv_ill->ill_phyint->phyint_ifindex;
17768 			first_mp->b_cont = mp;
17769 			/*
17770 			 * Cache hardware acceleration info.
17771 			 */
17772 			if (hada_mp != NULL) {
17773 				IPSECHW_DEBUG(IPSECHW_PKT,
17774 				    ("ip_rput_local: caching data attr.\n"));
17775 				ii->ipsec_in_accelerated = B_TRUE;
17776 				ii->ipsec_in_da = hada_mp;
17777 				hada_mp = NULL;
17778 			}
17779 		} else {
17780 			ii = (ipsec_in_t *)first_mp->b_rptr;
17781 		}
17782 
17783 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17784 
17785 		if (!ipsec_loaded(ipss)) {
17786 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17787 			    ire->ire_zoneid, ipst);
17788 			return;
17789 		}
17790 
17791 		ns = ipst->ips_netstack;
17792 		/* select inbound SA and have IPsec process the pkt */
17793 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17794 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17795 			boolean_t esp_in_udp_sa;
17796 			if (esph == NULL)
17797 				return;
17798 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17799 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17800 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17801 			    IPSA_F_NATT) != 0);
17802 			/*
17803 			 * The following is a fancy, but quick, way of saying:
17804 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17805 			 *    OR
17806 			 * ESP SA and ESP-in-UDP packet --> drop
17807 			 */
17808 			if (esp_in_udp_sa != esp_in_udp_packet) {
17809 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17810 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17811 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17812 				    &ns->netstack_ipsec->ipsec_dropper);
17813 				return;
17814 			}
17815 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17816 			    first_mp, esph);
17817 		} else {
17818 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17819 			if (ah == NULL)
17820 				return;
17821 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17822 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17823 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17824 			    first_mp, ah);
17825 		}
17826 
17827 		switch (ipsec_rc) {
17828 		case IPSEC_STATUS_SUCCESS:
17829 			break;
17830 		case IPSEC_STATUS_FAILED:
17831 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17832 			/* FALLTHRU */
17833 		case IPSEC_STATUS_PENDING:
17834 			return;
17835 		}
17836 		/* we're done with IPsec processing, send it up */
17837 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17838 		return;
17839 	}
17840 	default:
17841 		break;
17842 	}
17843 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17844 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17845 		    ire->ire_zoneid));
17846 		goto drop_pkt;
17847 	}
17848 	/*
17849 	 * Handle protocols with which IP is less intimate.  There
17850 	 * can be more than one stream bound to a particular
17851 	 * protocol.  When this is the case, each one gets a copy
17852 	 * of any incoming packets.
17853 	 */
17854 fanout:
17855 	ip_fanout_proto(q, first_mp, ill, ipha,
17856 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17857 	    B_TRUE, recv_ill, ire->ire_zoneid);
17858 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17859 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17860 	return;
17861 
17862 drop_pkt:
17863 	freemsg(first_mp);
17864 	if (hada_mp != NULL)
17865 		freeb(hada_mp);
17866 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17867 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17868 #undef	rptr
17869 #undef  iphs
17870 
17871 }
17872 
17873 /*
17874  * Update any source route, record route or timestamp options.
17875  * Check that we are at end of strict source route.
17876  * The options have already been checked for sanity in ip_rput_options().
17877  */
17878 static boolean_t
17879 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17880     ip_stack_t *ipst)
17881 {
17882 	ipoptp_t	opts;
17883 	uchar_t		*opt;
17884 	uint8_t		optval;
17885 	uint8_t		optlen;
17886 	ipaddr_t	dst;
17887 	uint32_t	ts;
17888 	ire_t		*dst_ire;
17889 	timestruc_t	now;
17890 	zoneid_t	zoneid;
17891 	ill_t		*ill;
17892 
17893 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17894 
17895 	ip2dbg(("ip_rput_local_options\n"));
17896 
17897 	for (optval = ipoptp_first(&opts, ipha);
17898 	    optval != IPOPT_EOL;
17899 	    optval = ipoptp_next(&opts)) {
17900 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17901 		opt = opts.ipoptp_cur;
17902 		optlen = opts.ipoptp_len;
17903 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17904 		    optval, optlen));
17905 		switch (optval) {
17906 			uint32_t off;
17907 		case IPOPT_SSRR:
17908 		case IPOPT_LSRR:
17909 			off = opt[IPOPT_OFFSET];
17910 			off--;
17911 			if (optlen < IP_ADDR_LEN ||
17912 			    off > optlen - IP_ADDR_LEN) {
17913 				/* End of source route */
17914 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17915 				break;
17916 			}
17917 			/*
17918 			 * This will only happen if two consecutive entries
17919 			 * in the source route contains our address or if
17920 			 * it is a packet with a loose source route which
17921 			 * reaches us before consuming the whole source route
17922 			 */
17923 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17924 			if (optval == IPOPT_SSRR) {
17925 				goto bad_src_route;
17926 			}
17927 			/*
17928 			 * Hack: instead of dropping the packet truncate the
17929 			 * source route to what has been used by filling the
17930 			 * rest with IPOPT_NOP.
17931 			 */
17932 			opt[IPOPT_OLEN] = (uint8_t)off;
17933 			while (off < optlen) {
17934 				opt[off++] = IPOPT_NOP;
17935 			}
17936 			break;
17937 		case IPOPT_RR:
17938 			off = opt[IPOPT_OFFSET];
17939 			off--;
17940 			if (optlen < IP_ADDR_LEN ||
17941 			    off > optlen - IP_ADDR_LEN) {
17942 				/* No more room - ignore */
17943 				ip1dbg((
17944 				    "ip_rput_local_options: end of RR\n"));
17945 				break;
17946 			}
17947 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17948 			    IP_ADDR_LEN);
17949 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17950 			break;
17951 		case IPOPT_TS:
17952 			/* Insert timestamp if there is romm */
17953 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17954 			case IPOPT_TS_TSONLY:
17955 				off = IPOPT_TS_TIMELEN;
17956 				break;
17957 			case IPOPT_TS_PRESPEC:
17958 			case IPOPT_TS_PRESPEC_RFC791:
17959 				/* Verify that the address matched */
17960 				off = opt[IPOPT_OFFSET] - 1;
17961 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17962 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17963 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17964 				    ipst);
17965 				if (dst_ire == NULL) {
17966 					/* Not for us */
17967 					break;
17968 				}
17969 				ire_refrele(dst_ire);
17970 				/* FALLTHRU */
17971 			case IPOPT_TS_TSANDADDR:
17972 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17973 				break;
17974 			default:
17975 				/*
17976 				 * ip_*put_options should have already
17977 				 * dropped this packet.
17978 				 */
17979 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17980 				    "unknown IT - bug in ip_rput_options?\n");
17981 				return (B_TRUE);	/* Keep "lint" happy */
17982 			}
17983 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17984 				/* Increase overflow counter */
17985 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17986 				opt[IPOPT_POS_OV_FLG] =
17987 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17988 				    (off << 4));
17989 				break;
17990 			}
17991 			off = opt[IPOPT_OFFSET] - 1;
17992 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17993 			case IPOPT_TS_PRESPEC:
17994 			case IPOPT_TS_PRESPEC_RFC791:
17995 			case IPOPT_TS_TSANDADDR:
17996 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17997 				    IP_ADDR_LEN);
17998 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17999 				/* FALLTHRU */
18000 			case IPOPT_TS_TSONLY:
18001 				off = opt[IPOPT_OFFSET] - 1;
18002 				/* Compute # of milliseconds since midnight */
18003 				gethrestime(&now);
18004 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18005 				    now.tv_nsec / (NANOSEC / MILLISEC);
18006 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18007 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18008 				break;
18009 			}
18010 			break;
18011 		}
18012 	}
18013 	return (B_TRUE);
18014 
18015 bad_src_route:
18016 	q = WR(q);
18017 	if (q->q_next != NULL)
18018 		ill = q->q_ptr;
18019 	else
18020 		ill = NULL;
18021 
18022 	/* make sure we clear any indication of a hardware checksum */
18023 	DB_CKSUMFLAGS(mp) = 0;
18024 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18025 	if (zoneid == ALL_ZONES)
18026 		freemsg(mp);
18027 	else
18028 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18029 	return (B_FALSE);
18030 
18031 }
18032 
18033 /*
18034  * Process IP options in an inbound packet.  If an option affects the
18035  * effective destination address, return the next hop address via dstp.
18036  * Returns -1 if something fails in which case an ICMP error has been sent
18037  * and mp freed.
18038  */
18039 static int
18040 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18041     ip_stack_t *ipst)
18042 {
18043 	ipoptp_t	opts;
18044 	uchar_t		*opt;
18045 	uint8_t		optval;
18046 	uint8_t		optlen;
18047 	ipaddr_t	dst;
18048 	intptr_t	code = 0;
18049 	ire_t		*ire = NULL;
18050 	zoneid_t	zoneid;
18051 	ill_t		*ill;
18052 
18053 	ip2dbg(("ip_rput_options\n"));
18054 	dst = ipha->ipha_dst;
18055 	for (optval = ipoptp_first(&opts, ipha);
18056 	    optval != IPOPT_EOL;
18057 	    optval = ipoptp_next(&opts)) {
18058 		opt = opts.ipoptp_cur;
18059 		optlen = opts.ipoptp_len;
18060 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18061 		    optval, optlen));
18062 		/*
18063 		 * Note: we need to verify the checksum before we
18064 		 * modify anything thus this routine only extracts the next
18065 		 * hop dst from any source route.
18066 		 */
18067 		switch (optval) {
18068 			uint32_t off;
18069 		case IPOPT_SSRR:
18070 		case IPOPT_LSRR:
18071 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18072 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18073 			if (ire == NULL) {
18074 				if (optval == IPOPT_SSRR) {
18075 					ip1dbg(("ip_rput_options: not next"
18076 					    " strict source route 0x%x\n",
18077 					    ntohl(dst)));
18078 					code = (char *)&ipha->ipha_dst -
18079 					    (char *)ipha;
18080 					goto param_prob; /* RouterReq's */
18081 				}
18082 				ip2dbg(("ip_rput_options: "
18083 				    "not next source route 0x%x\n",
18084 				    ntohl(dst)));
18085 				break;
18086 			}
18087 			ire_refrele(ire);
18088 
18089 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18090 				ip1dbg((
18091 				    "ip_rput_options: bad option offset\n"));
18092 				code = (char *)&opt[IPOPT_OLEN] -
18093 				    (char *)ipha;
18094 				goto param_prob;
18095 			}
18096 			off = opt[IPOPT_OFFSET];
18097 			off--;
18098 		redo_srr:
18099 			if (optlen < IP_ADDR_LEN ||
18100 			    off > optlen - IP_ADDR_LEN) {
18101 				/* End of source route */
18102 				ip1dbg(("ip_rput_options: end of SR\n"));
18103 				break;
18104 			}
18105 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18106 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18107 			    ntohl(dst)));
18108 
18109 			/*
18110 			 * Check if our address is present more than
18111 			 * once as consecutive hops in source route.
18112 			 * XXX verify per-interface ip_forwarding
18113 			 * for source route?
18114 			 */
18115 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18116 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18117 
18118 			if (ire != NULL) {
18119 				ire_refrele(ire);
18120 				off += IP_ADDR_LEN;
18121 				goto redo_srr;
18122 			}
18123 
18124 			if (dst == htonl(INADDR_LOOPBACK)) {
18125 				ip1dbg(("ip_rput_options: loopback addr in "
18126 				    "source route!\n"));
18127 				goto bad_src_route;
18128 			}
18129 			/*
18130 			 * For strict: verify that dst is directly
18131 			 * reachable.
18132 			 */
18133 			if (optval == IPOPT_SSRR) {
18134 				ire = ire_ftable_lookup(dst, 0, 0,
18135 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18136 				    msg_getlabel(mp),
18137 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18138 				if (ire == NULL) {
18139 					ip1dbg(("ip_rput_options: SSRR not "
18140 					    "directly reachable: 0x%x\n",
18141 					    ntohl(dst)));
18142 					goto bad_src_route;
18143 				}
18144 				ire_refrele(ire);
18145 			}
18146 			/*
18147 			 * Defer update of the offset and the record route
18148 			 * until the packet is forwarded.
18149 			 */
18150 			break;
18151 		case IPOPT_RR:
18152 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18153 				ip1dbg((
18154 				    "ip_rput_options: bad option offset\n"));
18155 				code = (char *)&opt[IPOPT_OLEN] -
18156 				    (char *)ipha;
18157 				goto param_prob;
18158 			}
18159 			break;
18160 		case IPOPT_TS:
18161 			/*
18162 			 * Verify that length >= 5 and that there is either
18163 			 * room for another timestamp or that the overflow
18164 			 * counter is not maxed out.
18165 			 */
18166 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18167 			if (optlen < IPOPT_MINLEN_IT) {
18168 				goto param_prob;
18169 			}
18170 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18171 				ip1dbg((
18172 				    "ip_rput_options: bad option offset\n"));
18173 				code = (char *)&opt[IPOPT_OFFSET] -
18174 				    (char *)ipha;
18175 				goto param_prob;
18176 			}
18177 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18178 			case IPOPT_TS_TSONLY:
18179 				off = IPOPT_TS_TIMELEN;
18180 				break;
18181 			case IPOPT_TS_TSANDADDR:
18182 			case IPOPT_TS_PRESPEC:
18183 			case IPOPT_TS_PRESPEC_RFC791:
18184 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18185 				break;
18186 			default:
18187 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18188 				    (char *)ipha;
18189 				goto param_prob;
18190 			}
18191 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18192 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18193 				/*
18194 				 * No room and the overflow counter is 15
18195 				 * already.
18196 				 */
18197 				goto param_prob;
18198 			}
18199 			break;
18200 		}
18201 	}
18202 
18203 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18204 		*dstp = dst;
18205 		return (0);
18206 	}
18207 
18208 	ip1dbg(("ip_rput_options: error processing IP options."));
18209 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18210 
18211 param_prob:
18212 	q = WR(q);
18213 	if (q->q_next != NULL)
18214 		ill = q->q_ptr;
18215 	else
18216 		ill = NULL;
18217 
18218 	/* make sure we clear any indication of a hardware checksum */
18219 	DB_CKSUMFLAGS(mp) = 0;
18220 	/* Don't know whether this is for non-global or global/forwarding */
18221 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18222 	if (zoneid == ALL_ZONES)
18223 		freemsg(mp);
18224 	else
18225 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18226 	return (-1);
18227 
18228 bad_src_route:
18229 	q = WR(q);
18230 	if (q->q_next != NULL)
18231 		ill = q->q_ptr;
18232 	else
18233 		ill = NULL;
18234 
18235 	/* make sure we clear any indication of a hardware checksum */
18236 	DB_CKSUMFLAGS(mp) = 0;
18237 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18238 	if (zoneid == ALL_ZONES)
18239 		freemsg(mp);
18240 	else
18241 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18242 	return (-1);
18243 }
18244 
18245 /*
18246  * IP & ICMP info in >=14 msg's ...
18247  *  - ip fixed part (mib2_ip_t)
18248  *  - icmp fixed part (mib2_icmp_t)
18249  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18250  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18251  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18252  *  - ipRouteAttributeTable (ip 102)	labeled routes
18253  *  - ip multicast membership (ip_member_t)
18254  *  - ip multicast source filtering (ip_grpsrc_t)
18255  *  - igmp fixed part (struct igmpstat)
18256  *  - multicast routing stats (struct mrtstat)
18257  *  - multicast routing vifs (array of struct vifctl)
18258  *  - multicast routing routes (array of struct mfcctl)
18259  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18260  *					One per ill plus one generic
18261  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18262  *					One per ill plus one generic
18263  *  - ipv6RouteEntry			all IPv6 IREs
18264  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18265  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18266  *  - ipv6AddrEntry			all IPv6 ipifs
18267  *  - ipv6 multicast membership (ipv6_member_t)
18268  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18269  *
18270  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18271  *
18272  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18273  * already filled in by the caller.
18274  * Return value of 0 indicates that no messages were sent and caller
18275  * should free mpctl.
18276  */
18277 int
18278 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18279 {
18280 	ip_stack_t *ipst;
18281 	sctp_stack_t *sctps;
18282 
18283 	if (q->q_next != NULL) {
18284 		ipst = ILLQ_TO_IPST(q);
18285 	} else {
18286 		ipst = CONNQ_TO_IPST(q);
18287 	}
18288 	ASSERT(ipst != NULL);
18289 	sctps = ipst->ips_netstack->netstack_sctp;
18290 
18291 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18292 		return (0);
18293 	}
18294 
18295 	/*
18296 	 * For the purposes of the (broken) packet shell use
18297 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18298 	 * to make TCP and UDP appear first in the list of mib items.
18299 	 * TBD: We could expand this and use it in netstat so that
18300 	 * the kernel doesn't have to produce large tables (connections,
18301 	 * routes, etc) when netstat only wants the statistics or a particular
18302 	 * table.
18303 	 */
18304 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18305 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18306 			return (1);
18307 		}
18308 	}
18309 
18310 	if (level != MIB2_TCP) {
18311 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18312 			return (1);
18313 		}
18314 	}
18315 
18316 	if (level != MIB2_UDP) {
18317 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18318 			return (1);
18319 		}
18320 	}
18321 
18322 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18323 	    ipst)) == NULL) {
18324 		return (1);
18325 	}
18326 
18327 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18328 		return (1);
18329 	}
18330 
18331 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18332 		return (1);
18333 	}
18334 
18335 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18336 		return (1);
18337 	}
18338 
18339 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18340 		return (1);
18341 	}
18342 
18343 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18344 		return (1);
18345 	}
18346 
18347 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18348 		return (1);
18349 	}
18350 
18351 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18352 		return (1);
18353 	}
18354 
18355 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18356 		return (1);
18357 	}
18358 
18359 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18360 		return (1);
18361 	}
18362 
18363 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18364 		return (1);
18365 	}
18366 
18367 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18368 		return (1);
18369 	}
18370 
18371 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18372 		return (1);
18373 	}
18374 
18375 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18376 		return (1);
18377 	}
18378 
18379 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18380 	if (mpctl == NULL)
18381 		return (1);
18382 
18383 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18384 	if (mpctl == NULL)
18385 		return (1);
18386 
18387 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18388 		return (1);
18389 	}
18390 	freemsg(mpctl);
18391 	return (1);
18392 }
18393 
18394 /* Get global (legacy) IPv4 statistics */
18395 static mblk_t *
18396 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18397     ip_stack_t *ipst)
18398 {
18399 	mib2_ip_t		old_ip_mib;
18400 	struct opthdr		*optp;
18401 	mblk_t			*mp2ctl;
18402 
18403 	/*
18404 	 * make a copy of the original message
18405 	 */
18406 	mp2ctl = copymsg(mpctl);
18407 
18408 	/* fixed length IP structure... */
18409 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18410 	optp->level = MIB2_IP;
18411 	optp->name = 0;
18412 	SET_MIB(old_ip_mib.ipForwarding,
18413 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18414 	SET_MIB(old_ip_mib.ipDefaultTTL,
18415 	    (uint32_t)ipst->ips_ip_def_ttl);
18416 	SET_MIB(old_ip_mib.ipReasmTimeout,
18417 	    ipst->ips_ip_g_frag_timeout);
18418 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18419 	    sizeof (mib2_ipAddrEntry_t));
18420 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18421 	    sizeof (mib2_ipRouteEntry_t));
18422 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18423 	    sizeof (mib2_ipNetToMediaEntry_t));
18424 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18425 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18426 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18427 	    sizeof (mib2_ipAttributeEntry_t));
18428 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18429 
18430 	/*
18431 	 * Grab the statistics from the new IP MIB
18432 	 */
18433 	SET_MIB(old_ip_mib.ipInReceives,
18434 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18435 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18436 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18437 	SET_MIB(old_ip_mib.ipForwDatagrams,
18438 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18439 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18440 	    ipmib->ipIfStatsInUnknownProtos);
18441 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18442 	SET_MIB(old_ip_mib.ipInDelivers,
18443 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18444 	SET_MIB(old_ip_mib.ipOutRequests,
18445 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18446 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18447 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18448 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18449 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18450 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18451 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18452 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18453 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18454 
18455 	/* ipRoutingDiscards is not being used */
18456 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18457 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18458 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18459 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18460 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18461 	    ipmib->ipIfStatsReasmDuplicates);
18462 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18463 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18464 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18465 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18466 	SET_MIB(old_ip_mib.rawipInOverflows,
18467 	    ipmib->rawipIfStatsInOverflows);
18468 
18469 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18470 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18471 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18472 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18473 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18474 	    ipmib->ipIfStatsOutSwitchIPVersion);
18475 
18476 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18477 	    (int)sizeof (old_ip_mib))) {
18478 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18479 		    (uint_t)sizeof (old_ip_mib)));
18480 	}
18481 
18482 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18483 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18484 	    (int)optp->level, (int)optp->name, (int)optp->len));
18485 	qreply(q, mpctl);
18486 	return (mp2ctl);
18487 }
18488 
18489 /* Per interface IPv4 statistics */
18490 static mblk_t *
18491 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18492 {
18493 	struct opthdr		*optp;
18494 	mblk_t			*mp2ctl;
18495 	ill_t			*ill;
18496 	ill_walk_context_t	ctx;
18497 	mblk_t			*mp_tail = NULL;
18498 	mib2_ipIfStatsEntry_t	global_ip_mib;
18499 
18500 	/*
18501 	 * Make a copy of the original message
18502 	 */
18503 	mp2ctl = copymsg(mpctl);
18504 
18505 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18506 	optp->level = MIB2_IP;
18507 	optp->name = MIB2_IP_TRAFFIC_STATS;
18508 	/* Include "unknown interface" ip_mib */
18509 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18510 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18511 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18512 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18513 	    (ipst->ips_ip_g_forward ? 1 : 2));
18514 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18515 	    (uint32_t)ipst->ips_ip_def_ttl);
18516 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18517 	    sizeof (mib2_ipIfStatsEntry_t));
18518 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18519 	    sizeof (mib2_ipAddrEntry_t));
18520 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18521 	    sizeof (mib2_ipRouteEntry_t));
18522 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18523 	    sizeof (mib2_ipNetToMediaEntry_t));
18524 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18525 	    sizeof (ip_member_t));
18526 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18527 	    sizeof (ip_grpsrc_t));
18528 
18529 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18530 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18531 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18532 		    "failed to allocate %u bytes\n",
18533 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18534 	}
18535 
18536 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18537 
18538 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18539 	ill = ILL_START_WALK_V4(&ctx, ipst);
18540 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18541 		ill->ill_ip_mib->ipIfStatsIfIndex =
18542 		    ill->ill_phyint->phyint_ifindex;
18543 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18544 		    (ipst->ips_ip_g_forward ? 1 : 2));
18545 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18546 		    (uint32_t)ipst->ips_ip_def_ttl);
18547 
18548 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18549 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18550 		    (char *)ill->ill_ip_mib,
18551 		    (int)sizeof (*ill->ill_ip_mib))) {
18552 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18553 			    "failed to allocate %u bytes\n",
18554 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18555 		}
18556 	}
18557 	rw_exit(&ipst->ips_ill_g_lock);
18558 
18559 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18560 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18561 	    "level %d, name %d, len %d\n",
18562 	    (int)optp->level, (int)optp->name, (int)optp->len));
18563 	qreply(q, mpctl);
18564 
18565 	if (mp2ctl == NULL)
18566 		return (NULL);
18567 
18568 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18569 }
18570 
18571 /* Global IPv4 ICMP statistics */
18572 static mblk_t *
18573 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18574 {
18575 	struct opthdr		*optp;
18576 	mblk_t			*mp2ctl;
18577 
18578 	/*
18579 	 * Make a copy of the original message
18580 	 */
18581 	mp2ctl = copymsg(mpctl);
18582 
18583 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18584 	optp->level = MIB2_ICMP;
18585 	optp->name = 0;
18586 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18587 	    (int)sizeof (ipst->ips_icmp_mib))) {
18588 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18589 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18590 	}
18591 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18592 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18593 	    (int)optp->level, (int)optp->name, (int)optp->len));
18594 	qreply(q, mpctl);
18595 	return (mp2ctl);
18596 }
18597 
18598 /* Global IPv4 IGMP statistics */
18599 static mblk_t *
18600 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18601 {
18602 	struct opthdr		*optp;
18603 	mblk_t			*mp2ctl;
18604 
18605 	/*
18606 	 * make a copy of the original message
18607 	 */
18608 	mp2ctl = copymsg(mpctl);
18609 
18610 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18611 	optp->level = EXPER_IGMP;
18612 	optp->name = 0;
18613 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18614 	    (int)sizeof (ipst->ips_igmpstat))) {
18615 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18616 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18617 	}
18618 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18619 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18620 	    (int)optp->level, (int)optp->name, (int)optp->len));
18621 	qreply(q, mpctl);
18622 	return (mp2ctl);
18623 }
18624 
18625 /* Global IPv4 Multicast Routing statistics */
18626 static mblk_t *
18627 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18628 {
18629 	struct opthdr		*optp;
18630 	mblk_t			*mp2ctl;
18631 
18632 	/*
18633 	 * make a copy of the original message
18634 	 */
18635 	mp2ctl = copymsg(mpctl);
18636 
18637 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18638 	optp->level = EXPER_DVMRP;
18639 	optp->name = 0;
18640 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18641 		ip0dbg(("ip_mroute_stats: failed\n"));
18642 	}
18643 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18644 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18645 	    (int)optp->level, (int)optp->name, (int)optp->len));
18646 	qreply(q, mpctl);
18647 	return (mp2ctl);
18648 }
18649 
18650 /* IPv4 address information */
18651 static mblk_t *
18652 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18653 {
18654 	struct opthdr		*optp;
18655 	mblk_t			*mp2ctl;
18656 	mblk_t			*mp_tail = NULL;
18657 	ill_t			*ill;
18658 	ipif_t			*ipif;
18659 	uint_t			bitval;
18660 	mib2_ipAddrEntry_t	mae;
18661 	zoneid_t		zoneid;
18662 	ill_walk_context_t ctx;
18663 
18664 	/*
18665 	 * make a copy of the original message
18666 	 */
18667 	mp2ctl = copymsg(mpctl);
18668 
18669 	/* ipAddrEntryTable */
18670 
18671 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18672 	optp->level = MIB2_IP;
18673 	optp->name = MIB2_IP_ADDR;
18674 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18675 
18676 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18677 	ill = ILL_START_WALK_V4(&ctx, ipst);
18678 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18679 		for (ipif = ill->ill_ipif; ipif != NULL;
18680 		    ipif = ipif->ipif_next) {
18681 			if (ipif->ipif_zoneid != zoneid &&
18682 			    ipif->ipif_zoneid != ALL_ZONES)
18683 				continue;
18684 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18685 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18686 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18687 
18688 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18689 			    OCTET_LENGTH);
18690 			mae.ipAdEntIfIndex.o_length =
18691 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18692 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18693 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18694 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18695 			mae.ipAdEntInfo.ae_subnet_len =
18696 			    ip_mask_to_plen(ipif->ipif_net_mask);
18697 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18698 			for (bitval = 1;
18699 			    bitval &&
18700 			    !(bitval & ipif->ipif_brd_addr);
18701 			    bitval <<= 1)
18702 				noop;
18703 			mae.ipAdEntBcastAddr = bitval;
18704 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18705 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18706 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18707 			mae.ipAdEntInfo.ae_broadcast_addr =
18708 			    ipif->ipif_brd_addr;
18709 			mae.ipAdEntInfo.ae_pp_dst_addr =
18710 			    ipif->ipif_pp_dst_addr;
18711 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18712 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18713 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18714 
18715 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18716 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18717 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18718 				    "allocate %u bytes\n",
18719 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18720 			}
18721 		}
18722 	}
18723 	rw_exit(&ipst->ips_ill_g_lock);
18724 
18725 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18726 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18727 	    (int)optp->level, (int)optp->name, (int)optp->len));
18728 	qreply(q, mpctl);
18729 	return (mp2ctl);
18730 }
18731 
18732 /* IPv6 address information */
18733 static mblk_t *
18734 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18735 {
18736 	struct opthdr		*optp;
18737 	mblk_t			*mp2ctl;
18738 	mblk_t			*mp_tail = NULL;
18739 	ill_t			*ill;
18740 	ipif_t			*ipif;
18741 	mib2_ipv6AddrEntry_t	mae6;
18742 	zoneid_t		zoneid;
18743 	ill_walk_context_t	ctx;
18744 
18745 	/*
18746 	 * make a copy of the original message
18747 	 */
18748 	mp2ctl = copymsg(mpctl);
18749 
18750 	/* ipv6AddrEntryTable */
18751 
18752 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18753 	optp->level = MIB2_IP6;
18754 	optp->name = MIB2_IP6_ADDR;
18755 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18756 
18757 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18758 	ill = ILL_START_WALK_V6(&ctx, ipst);
18759 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18760 		for (ipif = ill->ill_ipif; ipif != NULL;
18761 		    ipif = ipif->ipif_next) {
18762 			if (ipif->ipif_zoneid != zoneid &&
18763 			    ipif->ipif_zoneid != ALL_ZONES)
18764 				continue;
18765 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18766 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18767 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18768 
18769 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18770 			    OCTET_LENGTH);
18771 			mae6.ipv6AddrIfIndex.o_length =
18772 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18773 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18774 			mae6.ipv6AddrPfxLength =
18775 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18776 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18777 			mae6.ipv6AddrInfo.ae_subnet_len =
18778 			    mae6.ipv6AddrPfxLength;
18779 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18780 
18781 			/* Type: stateless(1), stateful(2), unknown(3) */
18782 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18783 				mae6.ipv6AddrType = 1;
18784 			else
18785 				mae6.ipv6AddrType = 2;
18786 			/* Anycast: true(1), false(2) */
18787 			if (ipif->ipif_flags & IPIF_ANYCAST)
18788 				mae6.ipv6AddrAnycastFlag = 1;
18789 			else
18790 				mae6.ipv6AddrAnycastFlag = 2;
18791 
18792 			/*
18793 			 * Address status: preferred(1), deprecated(2),
18794 			 * invalid(3), inaccessible(4), unknown(5)
18795 			 */
18796 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18797 				mae6.ipv6AddrStatus = 3;
18798 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18799 				mae6.ipv6AddrStatus = 2;
18800 			else
18801 				mae6.ipv6AddrStatus = 1;
18802 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18803 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18804 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18805 			    ipif->ipif_v6pp_dst_addr;
18806 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18807 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18808 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18809 			mae6.ipv6AddrIdentifier = ill->ill_token;
18810 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18811 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18812 			mae6.ipv6AddrRetransmitTime =
18813 			    ill->ill_reachable_retrans_time;
18814 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18815 			    (char *)&mae6,
18816 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18817 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18818 				    "allocate %u bytes\n",
18819 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18820 			}
18821 		}
18822 	}
18823 	rw_exit(&ipst->ips_ill_g_lock);
18824 
18825 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18826 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18827 	    (int)optp->level, (int)optp->name, (int)optp->len));
18828 	qreply(q, mpctl);
18829 	return (mp2ctl);
18830 }
18831 
18832 /* IPv4 multicast group membership. */
18833 static mblk_t *
18834 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18835 {
18836 	struct opthdr		*optp;
18837 	mblk_t			*mp2ctl;
18838 	ill_t			*ill;
18839 	ipif_t			*ipif;
18840 	ilm_t			*ilm;
18841 	ip_member_t		ipm;
18842 	mblk_t			*mp_tail = NULL;
18843 	ill_walk_context_t	ctx;
18844 	zoneid_t		zoneid;
18845 	ilm_walker_t		ilw;
18846 
18847 	/*
18848 	 * make a copy of the original message
18849 	 */
18850 	mp2ctl = copymsg(mpctl);
18851 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18852 
18853 	/* ipGroupMember table */
18854 	optp = (struct opthdr *)&mpctl->b_rptr[
18855 	    sizeof (struct T_optmgmt_ack)];
18856 	optp->level = MIB2_IP;
18857 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18858 
18859 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18860 	ill = ILL_START_WALK_V4(&ctx, ipst);
18861 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18862 		if (IS_UNDER_IPMP(ill))
18863 			continue;
18864 
18865 		ilm = ilm_walker_start(&ilw, ill);
18866 		for (ipif = ill->ill_ipif; ipif != NULL;
18867 		    ipif = ipif->ipif_next) {
18868 			if (ipif->ipif_zoneid != zoneid &&
18869 			    ipif->ipif_zoneid != ALL_ZONES)
18870 				continue;	/* not this zone */
18871 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18872 			    OCTET_LENGTH);
18873 			ipm.ipGroupMemberIfIndex.o_length =
18874 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18875 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18876 				ASSERT(ilm->ilm_ipif != NULL);
18877 				ASSERT(ilm->ilm_ill == NULL);
18878 				if (ilm->ilm_ipif != ipif)
18879 					continue;
18880 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18881 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18882 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18883 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18884 				    (char *)&ipm, (int)sizeof (ipm))) {
18885 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18886 					    "failed to allocate %u bytes\n",
18887 					    (uint_t)sizeof (ipm)));
18888 				}
18889 			}
18890 		}
18891 		ilm_walker_finish(&ilw);
18892 	}
18893 	rw_exit(&ipst->ips_ill_g_lock);
18894 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18895 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18896 	    (int)optp->level, (int)optp->name, (int)optp->len));
18897 	qreply(q, mpctl);
18898 	return (mp2ctl);
18899 }
18900 
18901 /* IPv6 multicast group membership. */
18902 static mblk_t *
18903 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18904 {
18905 	struct opthdr		*optp;
18906 	mblk_t			*mp2ctl;
18907 	ill_t			*ill;
18908 	ilm_t			*ilm;
18909 	ipv6_member_t		ipm6;
18910 	mblk_t			*mp_tail = NULL;
18911 	ill_walk_context_t	ctx;
18912 	zoneid_t		zoneid;
18913 	ilm_walker_t		ilw;
18914 
18915 	/*
18916 	 * make a copy of the original message
18917 	 */
18918 	mp2ctl = copymsg(mpctl);
18919 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18920 
18921 	/* ip6GroupMember table */
18922 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18923 	optp->level = MIB2_IP6;
18924 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18925 
18926 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18927 	ill = ILL_START_WALK_V6(&ctx, ipst);
18928 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18929 		if (IS_UNDER_IPMP(ill))
18930 			continue;
18931 
18932 		ilm = ilm_walker_start(&ilw, ill);
18933 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18934 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18935 			ASSERT(ilm->ilm_ipif == NULL);
18936 			ASSERT(ilm->ilm_ill != NULL);
18937 			if (ilm->ilm_zoneid != zoneid)
18938 				continue;	/* not this zone */
18939 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18940 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18941 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18942 			if (!snmp_append_data2(mpctl->b_cont,
18943 			    &mp_tail,
18944 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18945 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18946 				    "failed to allocate %u bytes\n",
18947 				    (uint_t)sizeof (ipm6)));
18948 			}
18949 		}
18950 		ilm_walker_finish(&ilw);
18951 	}
18952 	rw_exit(&ipst->ips_ill_g_lock);
18953 
18954 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18955 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18956 	    (int)optp->level, (int)optp->name, (int)optp->len));
18957 	qreply(q, mpctl);
18958 	return (mp2ctl);
18959 }
18960 
18961 /* IP multicast filtered sources */
18962 static mblk_t *
18963 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18964 {
18965 	struct opthdr		*optp;
18966 	mblk_t			*mp2ctl;
18967 	ill_t			*ill;
18968 	ipif_t			*ipif;
18969 	ilm_t			*ilm;
18970 	ip_grpsrc_t		ips;
18971 	mblk_t			*mp_tail = NULL;
18972 	ill_walk_context_t	ctx;
18973 	zoneid_t		zoneid;
18974 	int			i;
18975 	slist_t			*sl;
18976 	ilm_walker_t		ilw;
18977 
18978 	/*
18979 	 * make a copy of the original message
18980 	 */
18981 	mp2ctl = copymsg(mpctl);
18982 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18983 
18984 	/* ipGroupSource table */
18985 	optp = (struct opthdr *)&mpctl->b_rptr[
18986 	    sizeof (struct T_optmgmt_ack)];
18987 	optp->level = MIB2_IP;
18988 	optp->name = EXPER_IP_GROUP_SOURCES;
18989 
18990 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18991 	ill = ILL_START_WALK_V4(&ctx, ipst);
18992 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18993 		if (IS_UNDER_IPMP(ill))
18994 			continue;
18995 
18996 		ilm = ilm_walker_start(&ilw, ill);
18997 		for (ipif = ill->ill_ipif; ipif != NULL;
18998 		    ipif = ipif->ipif_next) {
18999 			if (ipif->ipif_zoneid != zoneid)
19000 				continue;	/* not this zone */
19001 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19002 			    OCTET_LENGTH);
19003 			ips.ipGroupSourceIfIndex.o_length =
19004 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19005 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19006 				ASSERT(ilm->ilm_ipif != NULL);
19007 				ASSERT(ilm->ilm_ill == NULL);
19008 				sl = ilm->ilm_filter;
19009 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19010 					continue;
19011 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19012 				for (i = 0; i < sl->sl_numsrc; i++) {
19013 					if (!IN6_IS_ADDR_V4MAPPED(
19014 					    &sl->sl_addr[i]))
19015 						continue;
19016 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19017 					    ips.ipGroupSourceAddress);
19018 					if (snmp_append_data2(mpctl->b_cont,
19019 					    &mp_tail, (char *)&ips,
19020 					    (int)sizeof (ips)) == 0) {
19021 						ip1dbg(("ip_snmp_get_mib2_"
19022 						    "ip_group_src: failed to "
19023 						    "allocate %u bytes\n",
19024 						    (uint_t)sizeof (ips)));
19025 					}
19026 				}
19027 			}
19028 		}
19029 		ilm_walker_finish(&ilw);
19030 	}
19031 	rw_exit(&ipst->ips_ill_g_lock);
19032 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19033 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19034 	    (int)optp->level, (int)optp->name, (int)optp->len));
19035 	qreply(q, mpctl);
19036 	return (mp2ctl);
19037 }
19038 
19039 /* IPv6 multicast filtered sources. */
19040 static mblk_t *
19041 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19042 {
19043 	struct opthdr		*optp;
19044 	mblk_t			*mp2ctl;
19045 	ill_t			*ill;
19046 	ilm_t			*ilm;
19047 	ipv6_grpsrc_t		ips6;
19048 	mblk_t			*mp_tail = NULL;
19049 	ill_walk_context_t	ctx;
19050 	zoneid_t		zoneid;
19051 	int			i;
19052 	slist_t			*sl;
19053 	ilm_walker_t		ilw;
19054 
19055 	/*
19056 	 * make a copy of the original message
19057 	 */
19058 	mp2ctl = copymsg(mpctl);
19059 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19060 
19061 	/* ip6GroupMember table */
19062 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19063 	optp->level = MIB2_IP6;
19064 	optp->name = EXPER_IP6_GROUP_SOURCES;
19065 
19066 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19067 	ill = ILL_START_WALK_V6(&ctx, ipst);
19068 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19069 		if (IS_UNDER_IPMP(ill))
19070 			continue;
19071 
19072 		ilm = ilm_walker_start(&ilw, ill);
19073 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19074 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19075 			ASSERT(ilm->ilm_ipif == NULL);
19076 			ASSERT(ilm->ilm_ill != NULL);
19077 			sl = ilm->ilm_filter;
19078 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19079 				continue;
19080 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19081 			for (i = 0; i < sl->sl_numsrc; i++) {
19082 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19083 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19084 				    (char *)&ips6, (int)sizeof (ips6))) {
19085 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19086 					    "group_src: failed to allocate "
19087 					    "%u bytes\n",
19088 					    (uint_t)sizeof (ips6)));
19089 				}
19090 			}
19091 		}
19092 		ilm_walker_finish(&ilw);
19093 	}
19094 	rw_exit(&ipst->ips_ill_g_lock);
19095 
19096 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19097 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19098 	    (int)optp->level, (int)optp->name, (int)optp->len));
19099 	qreply(q, mpctl);
19100 	return (mp2ctl);
19101 }
19102 
19103 /* Multicast routing virtual interface table. */
19104 static mblk_t *
19105 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19106 {
19107 	struct opthdr		*optp;
19108 	mblk_t			*mp2ctl;
19109 
19110 	/*
19111 	 * make a copy of the original message
19112 	 */
19113 	mp2ctl = copymsg(mpctl);
19114 
19115 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19116 	optp->level = EXPER_DVMRP;
19117 	optp->name = EXPER_DVMRP_VIF;
19118 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19119 		ip0dbg(("ip_mroute_vif: failed\n"));
19120 	}
19121 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19122 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19123 	    (int)optp->level, (int)optp->name, (int)optp->len));
19124 	qreply(q, mpctl);
19125 	return (mp2ctl);
19126 }
19127 
19128 /* Multicast routing table. */
19129 static mblk_t *
19130 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19131 {
19132 	struct opthdr		*optp;
19133 	mblk_t			*mp2ctl;
19134 
19135 	/*
19136 	 * make a copy of the original message
19137 	 */
19138 	mp2ctl = copymsg(mpctl);
19139 
19140 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19141 	optp->level = EXPER_DVMRP;
19142 	optp->name = EXPER_DVMRP_MRT;
19143 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19144 		ip0dbg(("ip_mroute_mrt: failed\n"));
19145 	}
19146 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19147 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19148 	    (int)optp->level, (int)optp->name, (int)optp->len));
19149 	qreply(q, mpctl);
19150 	return (mp2ctl);
19151 }
19152 
19153 /*
19154  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19155  * in one IRE walk.
19156  */
19157 static mblk_t *
19158 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19159     ip_stack_t *ipst)
19160 {
19161 	struct opthdr	*optp;
19162 	mblk_t		*mp2ctl;	/* Returned */
19163 	mblk_t		*mp3ctl;	/* nettomedia */
19164 	mblk_t		*mp4ctl;	/* routeattrs */
19165 	iproutedata_t	ird;
19166 	zoneid_t	zoneid;
19167 
19168 	/*
19169 	 * make copies of the original message
19170 	 *	- mp2ctl is returned unchanged to the caller for his use
19171 	 *	- mpctl is sent upstream as ipRouteEntryTable
19172 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19173 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19174 	 */
19175 	mp2ctl = copymsg(mpctl);
19176 	mp3ctl = copymsg(mpctl);
19177 	mp4ctl = copymsg(mpctl);
19178 	if (mp3ctl == NULL || mp4ctl == NULL) {
19179 		freemsg(mp4ctl);
19180 		freemsg(mp3ctl);
19181 		freemsg(mp2ctl);
19182 		freemsg(mpctl);
19183 		return (NULL);
19184 	}
19185 
19186 	bzero(&ird, sizeof (ird));
19187 
19188 	ird.ird_route.lp_head = mpctl->b_cont;
19189 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19190 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19191 	/*
19192 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19193 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19194 	 * intended a temporary solution until a proper MIB API is provided
19195 	 * that provides complete filtering/caller-opt-in.
19196 	 */
19197 	if (level == EXPER_IP_AND_TESTHIDDEN)
19198 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19199 
19200 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19201 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19202 
19203 	/* ipRouteEntryTable in mpctl */
19204 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19205 	optp->level = MIB2_IP;
19206 	optp->name = MIB2_IP_ROUTE;
19207 	optp->len = msgdsize(ird.ird_route.lp_head);
19208 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19209 	    (int)optp->level, (int)optp->name, (int)optp->len));
19210 	qreply(q, mpctl);
19211 
19212 	/* ipNetToMediaEntryTable in mp3ctl */
19213 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19214 	optp->level = MIB2_IP;
19215 	optp->name = MIB2_IP_MEDIA;
19216 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19217 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19218 	    (int)optp->level, (int)optp->name, (int)optp->len));
19219 	qreply(q, mp3ctl);
19220 
19221 	/* ipRouteAttributeTable in mp4ctl */
19222 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19223 	optp->level = MIB2_IP;
19224 	optp->name = EXPER_IP_RTATTR;
19225 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19226 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19227 	    (int)optp->level, (int)optp->name, (int)optp->len));
19228 	if (optp->len == 0)
19229 		freemsg(mp4ctl);
19230 	else
19231 		qreply(q, mp4ctl);
19232 
19233 	return (mp2ctl);
19234 }
19235 
19236 /*
19237  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19238  * ipv6NetToMediaEntryTable in an NDP walk.
19239  */
19240 static mblk_t *
19241 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19242     ip_stack_t *ipst)
19243 {
19244 	struct opthdr	*optp;
19245 	mblk_t		*mp2ctl;	/* Returned */
19246 	mblk_t		*mp3ctl;	/* nettomedia */
19247 	mblk_t		*mp4ctl;	/* routeattrs */
19248 	iproutedata_t	ird;
19249 	zoneid_t	zoneid;
19250 
19251 	/*
19252 	 * make copies of the original message
19253 	 *	- mp2ctl is returned unchanged to the caller for his use
19254 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19255 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19256 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19257 	 */
19258 	mp2ctl = copymsg(mpctl);
19259 	mp3ctl = copymsg(mpctl);
19260 	mp4ctl = copymsg(mpctl);
19261 	if (mp3ctl == NULL || mp4ctl == NULL) {
19262 		freemsg(mp4ctl);
19263 		freemsg(mp3ctl);
19264 		freemsg(mp2ctl);
19265 		freemsg(mpctl);
19266 		return (NULL);
19267 	}
19268 
19269 	bzero(&ird, sizeof (ird));
19270 
19271 	ird.ird_route.lp_head = mpctl->b_cont;
19272 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19273 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19274 	/*
19275 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19276 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19277 	 * intended a temporary solution until a proper MIB API is provided
19278 	 * that provides complete filtering/caller-opt-in.
19279 	 */
19280 	if (level == EXPER_IP_AND_TESTHIDDEN)
19281 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19282 
19283 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19284 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19285 
19286 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19287 	optp->level = MIB2_IP6;
19288 	optp->name = MIB2_IP6_ROUTE;
19289 	optp->len = msgdsize(ird.ird_route.lp_head);
19290 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19291 	    (int)optp->level, (int)optp->name, (int)optp->len));
19292 	qreply(q, mpctl);
19293 
19294 	/* ipv6NetToMediaEntryTable in mp3ctl */
19295 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19296 
19297 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19298 	optp->level = MIB2_IP6;
19299 	optp->name = MIB2_IP6_MEDIA;
19300 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19301 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19302 	    (int)optp->level, (int)optp->name, (int)optp->len));
19303 	qreply(q, mp3ctl);
19304 
19305 	/* ipv6RouteAttributeTable in mp4ctl */
19306 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19307 	optp->level = MIB2_IP6;
19308 	optp->name = EXPER_IP_RTATTR;
19309 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19310 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19311 	    (int)optp->level, (int)optp->name, (int)optp->len));
19312 	if (optp->len == 0)
19313 		freemsg(mp4ctl);
19314 	else
19315 		qreply(q, mp4ctl);
19316 
19317 	return (mp2ctl);
19318 }
19319 
19320 /*
19321  * IPv6 mib: One per ill
19322  */
19323 static mblk_t *
19324 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19325 {
19326 	struct opthdr		*optp;
19327 	mblk_t			*mp2ctl;
19328 	ill_t			*ill;
19329 	ill_walk_context_t	ctx;
19330 	mblk_t			*mp_tail = NULL;
19331 
19332 	/*
19333 	 * Make a copy of the original message
19334 	 */
19335 	mp2ctl = copymsg(mpctl);
19336 
19337 	/* fixed length IPv6 structure ... */
19338 
19339 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19340 	optp->level = MIB2_IP6;
19341 	optp->name = 0;
19342 	/* Include "unknown interface" ip6_mib */
19343 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19344 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19345 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19346 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19347 	    ipst->ips_ipv6_forward ? 1 : 2);
19348 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19349 	    ipst->ips_ipv6_def_hops);
19350 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19351 	    sizeof (mib2_ipIfStatsEntry_t));
19352 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19353 	    sizeof (mib2_ipv6AddrEntry_t));
19354 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19355 	    sizeof (mib2_ipv6RouteEntry_t));
19356 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19357 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19358 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19359 	    sizeof (ipv6_member_t));
19360 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19361 	    sizeof (ipv6_grpsrc_t));
19362 
19363 	/*
19364 	 * Synchronize 64- and 32-bit counters
19365 	 */
19366 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19367 	    ipIfStatsHCInReceives);
19368 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19369 	    ipIfStatsHCInDelivers);
19370 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19371 	    ipIfStatsHCOutRequests);
19372 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19373 	    ipIfStatsHCOutForwDatagrams);
19374 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19375 	    ipIfStatsHCOutMcastPkts);
19376 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19377 	    ipIfStatsHCInMcastPkts);
19378 
19379 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19380 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19381 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19382 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19383 	}
19384 
19385 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19386 	ill = ILL_START_WALK_V6(&ctx, ipst);
19387 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19388 		ill->ill_ip_mib->ipIfStatsIfIndex =
19389 		    ill->ill_phyint->phyint_ifindex;
19390 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19391 		    ipst->ips_ipv6_forward ? 1 : 2);
19392 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19393 		    ill->ill_max_hops);
19394 
19395 		/*
19396 		 * Synchronize 64- and 32-bit counters
19397 		 */
19398 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19399 		    ipIfStatsHCInReceives);
19400 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19401 		    ipIfStatsHCInDelivers);
19402 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19403 		    ipIfStatsHCOutRequests);
19404 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19405 		    ipIfStatsHCOutForwDatagrams);
19406 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19407 		    ipIfStatsHCOutMcastPkts);
19408 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19409 		    ipIfStatsHCInMcastPkts);
19410 
19411 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19412 		    (char *)ill->ill_ip_mib,
19413 		    (int)sizeof (*ill->ill_ip_mib))) {
19414 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19415 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19416 		}
19417 	}
19418 	rw_exit(&ipst->ips_ill_g_lock);
19419 
19420 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19421 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19422 	    (int)optp->level, (int)optp->name, (int)optp->len));
19423 	qreply(q, mpctl);
19424 	return (mp2ctl);
19425 }
19426 
19427 /*
19428  * ICMPv6 mib: One per ill
19429  */
19430 static mblk_t *
19431 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19432 {
19433 	struct opthdr		*optp;
19434 	mblk_t			*mp2ctl;
19435 	ill_t			*ill;
19436 	ill_walk_context_t	ctx;
19437 	mblk_t			*mp_tail = NULL;
19438 	/*
19439 	 * Make a copy of the original message
19440 	 */
19441 	mp2ctl = copymsg(mpctl);
19442 
19443 	/* fixed length ICMPv6 structure ... */
19444 
19445 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19446 	optp->level = MIB2_ICMP6;
19447 	optp->name = 0;
19448 	/* Include "unknown interface" icmp6_mib */
19449 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19450 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19451 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19452 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19453 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19454 	    (char *)&ipst->ips_icmp6_mib,
19455 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19456 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19457 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19458 	}
19459 
19460 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19461 	ill = ILL_START_WALK_V6(&ctx, ipst);
19462 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19463 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19464 		    ill->ill_phyint->phyint_ifindex;
19465 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19466 		    (char *)ill->ill_icmp6_mib,
19467 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19468 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19469 			    "%u bytes\n",
19470 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19471 		}
19472 	}
19473 	rw_exit(&ipst->ips_ill_g_lock);
19474 
19475 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19476 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19477 	    (int)optp->level, (int)optp->name, (int)optp->len));
19478 	qreply(q, mpctl);
19479 	return (mp2ctl);
19480 }
19481 
19482 /*
19483  * ire_walk routine to create both ipRouteEntryTable and
19484  * ipRouteAttributeTable in one IRE walk
19485  */
19486 static void
19487 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19488 {
19489 	ill_t				*ill;
19490 	ipif_t				*ipif;
19491 	mib2_ipRouteEntry_t		*re;
19492 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19493 	ipaddr_t			gw_addr;
19494 	tsol_ire_gw_secattr_t		*attrp;
19495 	tsol_gc_t			*gc = NULL;
19496 	tsol_gcgrp_t			*gcgrp = NULL;
19497 	uint_t				sacnt = 0;
19498 	int				i;
19499 
19500 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19501 
19502 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19503 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19504 		return;
19505 	}
19506 
19507 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19508 		return;
19509 
19510 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19511 		mutex_enter(&attrp->igsa_lock);
19512 		if ((gc = attrp->igsa_gc) != NULL) {
19513 			gcgrp = gc->gc_grp;
19514 			ASSERT(gcgrp != NULL);
19515 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19516 			sacnt = 1;
19517 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19518 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19519 			gc = gcgrp->gcgrp_head;
19520 			sacnt = gcgrp->gcgrp_count;
19521 		}
19522 		mutex_exit(&attrp->igsa_lock);
19523 
19524 		/* do nothing if there's no gc to report */
19525 		if (gc == NULL) {
19526 			ASSERT(sacnt == 0);
19527 			if (gcgrp != NULL) {
19528 				/* we might as well drop the lock now */
19529 				rw_exit(&gcgrp->gcgrp_rwlock);
19530 				gcgrp = NULL;
19531 			}
19532 			attrp = NULL;
19533 		}
19534 
19535 		ASSERT(gc == NULL || (gcgrp != NULL &&
19536 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19537 	}
19538 	ASSERT(sacnt == 0 || gc != NULL);
19539 
19540 	if (sacnt != 0 &&
19541 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19542 		kmem_free(re, sizeof (*re));
19543 		rw_exit(&gcgrp->gcgrp_rwlock);
19544 		return;
19545 	}
19546 
19547 	/*
19548 	 * Return all IRE types for route table... let caller pick and choose
19549 	 */
19550 	re->ipRouteDest = ire->ire_addr;
19551 	ipif = ire->ire_ipif;
19552 	re->ipRouteIfIndex.o_length = 0;
19553 	if (ire->ire_type == IRE_CACHE) {
19554 		ill = (ill_t *)ire->ire_stq->q_ptr;
19555 		re->ipRouteIfIndex.o_length =
19556 		    ill->ill_name_length == 0 ? 0 :
19557 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19558 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19559 		    re->ipRouteIfIndex.o_length);
19560 	} else if (ipif != NULL) {
19561 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19562 		re->ipRouteIfIndex.o_length =
19563 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19564 	}
19565 	re->ipRouteMetric1 = -1;
19566 	re->ipRouteMetric2 = -1;
19567 	re->ipRouteMetric3 = -1;
19568 	re->ipRouteMetric4 = -1;
19569 
19570 	gw_addr = ire->ire_gateway_addr;
19571 
19572 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19573 		re->ipRouteNextHop = ire->ire_src_addr;
19574 	else
19575 		re->ipRouteNextHop = gw_addr;
19576 	/* indirect(4), direct(3), or invalid(2) */
19577 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19578 		re->ipRouteType = 2;
19579 	else
19580 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19581 	re->ipRouteProto = -1;
19582 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19583 	re->ipRouteMask = ire->ire_mask;
19584 	re->ipRouteMetric5 = -1;
19585 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19586 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19587 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19588 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19589 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19590 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19591 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19592 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19593 
19594 	if (ire->ire_flags & RTF_DYNAMIC) {
19595 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19596 	} else {
19597 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19598 	}
19599 
19600 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19601 	    (char *)re, (int)sizeof (*re))) {
19602 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19603 		    (uint_t)sizeof (*re)));
19604 	}
19605 
19606 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19607 		iaeptr->iae_routeidx = ird->ird_idx;
19608 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19609 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19610 	}
19611 
19612 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19613 	    (char *)iae, sacnt * sizeof (*iae))) {
19614 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19615 		    (unsigned)(sacnt * sizeof (*iae))));
19616 	}
19617 
19618 	/* bump route index for next pass */
19619 	ird->ird_idx++;
19620 
19621 	kmem_free(re, sizeof (*re));
19622 	if (sacnt != 0)
19623 		kmem_free(iae, sacnt * sizeof (*iae));
19624 
19625 	if (gcgrp != NULL)
19626 		rw_exit(&gcgrp->gcgrp_rwlock);
19627 }
19628 
19629 /*
19630  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19631  */
19632 static void
19633 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19634 {
19635 	ill_t				*ill;
19636 	ipif_t				*ipif;
19637 	mib2_ipv6RouteEntry_t		*re;
19638 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19639 	in6_addr_t			gw_addr_v6;
19640 	tsol_ire_gw_secattr_t		*attrp;
19641 	tsol_gc_t			*gc = NULL;
19642 	tsol_gcgrp_t			*gcgrp = NULL;
19643 	uint_t				sacnt = 0;
19644 	int				i;
19645 
19646 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19647 
19648 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19649 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19650 		return;
19651 	}
19652 
19653 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19654 		return;
19655 
19656 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19657 		mutex_enter(&attrp->igsa_lock);
19658 		if ((gc = attrp->igsa_gc) != NULL) {
19659 			gcgrp = gc->gc_grp;
19660 			ASSERT(gcgrp != NULL);
19661 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19662 			sacnt = 1;
19663 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19664 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19665 			gc = gcgrp->gcgrp_head;
19666 			sacnt = gcgrp->gcgrp_count;
19667 		}
19668 		mutex_exit(&attrp->igsa_lock);
19669 
19670 		/* do nothing if there's no gc to report */
19671 		if (gc == NULL) {
19672 			ASSERT(sacnt == 0);
19673 			if (gcgrp != NULL) {
19674 				/* we might as well drop the lock now */
19675 				rw_exit(&gcgrp->gcgrp_rwlock);
19676 				gcgrp = NULL;
19677 			}
19678 			attrp = NULL;
19679 		}
19680 
19681 		ASSERT(gc == NULL || (gcgrp != NULL &&
19682 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19683 	}
19684 	ASSERT(sacnt == 0 || gc != NULL);
19685 
19686 	if (sacnt != 0 &&
19687 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19688 		kmem_free(re, sizeof (*re));
19689 		rw_exit(&gcgrp->gcgrp_rwlock);
19690 		return;
19691 	}
19692 
19693 	/*
19694 	 * Return all IRE types for route table... let caller pick and choose
19695 	 */
19696 	re->ipv6RouteDest = ire->ire_addr_v6;
19697 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19698 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19699 	re->ipv6RouteIfIndex.o_length = 0;
19700 	ipif = ire->ire_ipif;
19701 	if (ire->ire_type == IRE_CACHE) {
19702 		ill = (ill_t *)ire->ire_stq->q_ptr;
19703 		re->ipv6RouteIfIndex.o_length =
19704 		    ill->ill_name_length == 0 ? 0 :
19705 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19706 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19707 		    re->ipv6RouteIfIndex.o_length);
19708 	} else if (ipif != NULL) {
19709 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19710 		re->ipv6RouteIfIndex.o_length =
19711 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19712 	}
19713 
19714 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19715 
19716 	mutex_enter(&ire->ire_lock);
19717 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19718 	mutex_exit(&ire->ire_lock);
19719 
19720 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19721 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19722 	else
19723 		re->ipv6RouteNextHop = gw_addr_v6;
19724 
19725 	/* remote(4), local(3), or discard(2) */
19726 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19727 		re->ipv6RouteType = 2;
19728 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19729 		re->ipv6RouteType = 3;
19730 	else
19731 		re->ipv6RouteType = 4;
19732 
19733 	re->ipv6RouteProtocol	= -1;
19734 	re->ipv6RoutePolicy	= 0;
19735 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19736 	re->ipv6RouteNextHopRDI	= 0;
19737 	re->ipv6RouteWeight	= 0;
19738 	re->ipv6RouteMetric	= 0;
19739 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19740 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19741 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19742 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19743 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19744 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19745 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19746 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19747 
19748 	if (ire->ire_flags & RTF_DYNAMIC) {
19749 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19750 	} else {
19751 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19752 	}
19753 
19754 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19755 	    (char *)re, (int)sizeof (*re))) {
19756 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19757 		    (uint_t)sizeof (*re)));
19758 	}
19759 
19760 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19761 		iaeptr->iae_routeidx = ird->ird_idx;
19762 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19763 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19764 	}
19765 
19766 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19767 	    (char *)iae, sacnt * sizeof (*iae))) {
19768 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19769 		    (unsigned)(sacnt * sizeof (*iae))));
19770 	}
19771 
19772 	/* bump route index for next pass */
19773 	ird->ird_idx++;
19774 
19775 	kmem_free(re, sizeof (*re));
19776 	if (sacnt != 0)
19777 		kmem_free(iae, sacnt * sizeof (*iae));
19778 
19779 	if (gcgrp != NULL)
19780 		rw_exit(&gcgrp->gcgrp_rwlock);
19781 }
19782 
19783 /*
19784  * ndp_walk routine to create ipv6NetToMediaEntryTable
19785  */
19786 static int
19787 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19788 {
19789 	ill_t				*ill;
19790 	mib2_ipv6NetToMediaEntry_t	ntme;
19791 	dl_unitdata_req_t		*dl;
19792 
19793 	ill = nce->nce_ill;
19794 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19795 		return (0);
19796 
19797 	/*
19798 	 * Neighbor cache entry attached to IRE with on-link
19799 	 * destination.
19800 	 */
19801 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19802 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19803 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19804 	    (nce->nce_res_mp != NULL)) {
19805 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19806 		ntme.ipv6NetToMediaPhysAddress.o_length =
19807 		    dl->dl_dest_addr_length;
19808 	} else {
19809 		ntme.ipv6NetToMediaPhysAddress.o_length =
19810 		    ill->ill_phys_addr_length;
19811 	}
19812 	if (nce->nce_res_mp != NULL) {
19813 		bcopy((char *)nce->nce_res_mp->b_rptr +
19814 		    NCE_LL_ADDR_OFFSET(ill),
19815 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19816 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19817 	} else {
19818 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19819 		    ill->ill_phys_addr_length);
19820 	}
19821 	/*
19822 	 * Note: Returns ND_* states. Should be:
19823 	 * reachable(1), stale(2), delay(3), probe(4),
19824 	 * invalid(5), unknown(6)
19825 	 */
19826 	ntme.ipv6NetToMediaState = nce->nce_state;
19827 	ntme.ipv6NetToMediaLastUpdated = 0;
19828 
19829 	/* other(1), dynamic(2), static(3), local(4) */
19830 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19831 		ntme.ipv6NetToMediaType = 4;
19832 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19833 		ntme.ipv6NetToMediaType = 1;
19834 	} else {
19835 		ntme.ipv6NetToMediaType = 2;
19836 	}
19837 
19838 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19839 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19840 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19841 		    (uint_t)sizeof (ntme)));
19842 	}
19843 	return (0);
19844 }
19845 
19846 /*
19847  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19848  */
19849 /* ARGSUSED */
19850 int
19851 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19852 {
19853 	switch (level) {
19854 	case MIB2_IP:
19855 	case MIB2_ICMP:
19856 		switch (name) {
19857 		default:
19858 			break;
19859 		}
19860 		return (1);
19861 	default:
19862 		return (1);
19863 	}
19864 }
19865 
19866 /*
19867  * When there exists both a 64- and 32-bit counter of a particular type
19868  * (i.e., InReceives), only the 64-bit counters are added.
19869  */
19870 void
19871 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19872 {
19873 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19874 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19875 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19876 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19877 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19878 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19879 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19880 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19881 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19882 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19883 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19884 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19885 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19886 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19887 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19888 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19889 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19890 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19891 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19892 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19893 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19894 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19895 	    o2->ipIfStatsInWrongIPVersion);
19896 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19897 	    o2->ipIfStatsInWrongIPVersion);
19898 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19899 	    o2->ipIfStatsOutSwitchIPVersion);
19900 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19901 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19902 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19903 	    o2->ipIfStatsHCInForwDatagrams);
19904 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19905 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19906 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19907 	    o2->ipIfStatsHCOutForwDatagrams);
19908 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19909 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19910 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19911 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19912 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19913 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19914 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19915 	    o2->ipIfStatsHCOutMcastOctets);
19916 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19917 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19918 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19919 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19920 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19921 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19922 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19923 }
19924 
19925 void
19926 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19927 {
19928 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19929 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19930 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19931 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19932 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19933 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19934 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19935 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19936 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19937 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19938 	    o2->ipv6IfIcmpInRouterSolicits);
19939 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19940 	    o2->ipv6IfIcmpInRouterAdvertisements);
19941 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19942 	    o2->ipv6IfIcmpInNeighborSolicits);
19943 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19944 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19945 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19946 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19947 	    o2->ipv6IfIcmpInGroupMembQueries);
19948 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19949 	    o2->ipv6IfIcmpInGroupMembResponses);
19950 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19951 	    o2->ipv6IfIcmpInGroupMembReductions);
19952 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19953 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19954 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19955 	    o2->ipv6IfIcmpOutDestUnreachs);
19956 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19957 	    o2->ipv6IfIcmpOutAdminProhibs);
19958 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19959 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19960 	    o2->ipv6IfIcmpOutParmProblems);
19961 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19962 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19963 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19964 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19965 	    o2->ipv6IfIcmpOutRouterSolicits);
19966 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19967 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19968 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19969 	    o2->ipv6IfIcmpOutNeighborSolicits);
19970 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19971 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19972 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19973 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19974 	    o2->ipv6IfIcmpOutGroupMembQueries);
19975 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19976 	    o2->ipv6IfIcmpOutGroupMembResponses);
19977 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19978 	    o2->ipv6IfIcmpOutGroupMembReductions);
19979 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19980 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19981 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19982 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19983 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19984 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19985 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19986 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19987 	    o2->ipv6IfIcmpInGroupMembTotal);
19988 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19989 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19990 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19991 	    o2->ipv6IfIcmpInGroupMembBadReports);
19992 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19993 	    o2->ipv6IfIcmpInGroupMembOurReports);
19994 }
19995 
19996 /*
19997  * Called before the options are updated to check if this packet will
19998  * be source routed from here.
19999  * This routine assumes that the options are well formed i.e. that they
20000  * have already been checked.
20001  */
20002 static boolean_t
20003 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20004 {
20005 	ipoptp_t	opts;
20006 	uchar_t		*opt;
20007 	uint8_t		optval;
20008 	uint8_t		optlen;
20009 	ipaddr_t	dst;
20010 	ire_t		*ire;
20011 
20012 	if (IS_SIMPLE_IPH(ipha)) {
20013 		ip2dbg(("not source routed\n"));
20014 		return (B_FALSE);
20015 	}
20016 	dst = ipha->ipha_dst;
20017 	for (optval = ipoptp_first(&opts, ipha);
20018 	    optval != IPOPT_EOL;
20019 	    optval = ipoptp_next(&opts)) {
20020 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20021 		opt = opts.ipoptp_cur;
20022 		optlen = opts.ipoptp_len;
20023 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20024 		    optval, optlen));
20025 		switch (optval) {
20026 			uint32_t off;
20027 		case IPOPT_SSRR:
20028 		case IPOPT_LSRR:
20029 			/*
20030 			 * If dst is one of our addresses and there are some
20031 			 * entries left in the source route return (true).
20032 			 */
20033 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20034 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20035 			if (ire == NULL) {
20036 				ip2dbg(("ip_source_routed: not next"
20037 				    " source route 0x%x\n",
20038 				    ntohl(dst)));
20039 				return (B_FALSE);
20040 			}
20041 			ire_refrele(ire);
20042 			off = opt[IPOPT_OFFSET];
20043 			off--;
20044 			if (optlen < IP_ADDR_LEN ||
20045 			    off > optlen - IP_ADDR_LEN) {
20046 				/* End of source route */
20047 				ip1dbg(("ip_source_routed: end of SR\n"));
20048 				return (B_FALSE);
20049 			}
20050 			return (B_TRUE);
20051 		}
20052 	}
20053 	ip2dbg(("not source routed\n"));
20054 	return (B_FALSE);
20055 }
20056 
20057 /*
20058  * Check if the packet contains any source route.
20059  */
20060 static boolean_t
20061 ip_source_route_included(ipha_t *ipha)
20062 {
20063 	ipoptp_t	opts;
20064 	uint8_t		optval;
20065 
20066 	if (IS_SIMPLE_IPH(ipha))
20067 		return (B_FALSE);
20068 	for (optval = ipoptp_first(&opts, ipha);
20069 	    optval != IPOPT_EOL;
20070 	    optval = ipoptp_next(&opts)) {
20071 		switch (optval) {
20072 		case IPOPT_SSRR:
20073 		case IPOPT_LSRR:
20074 			return (B_TRUE);
20075 		}
20076 	}
20077 	return (B_FALSE);
20078 }
20079 
20080 /*
20081  * Called when the IRE expiration timer fires.
20082  */
20083 void
20084 ip_trash_timer_expire(void *args)
20085 {
20086 	int			flush_flag = 0;
20087 	ire_expire_arg_t	iea;
20088 	ip_stack_t		*ipst = (ip_stack_t *)args;
20089 
20090 	iea.iea_ipst = ipst;	/* No netstack_hold */
20091 
20092 	/*
20093 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20094 	 * This lock makes sure that a new invocation of this function
20095 	 * that occurs due to an almost immediate timer firing will not
20096 	 * progress beyond this point until the current invocation is done
20097 	 */
20098 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20099 	ipst->ips_ip_ire_expire_id = 0;
20100 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20101 
20102 	/* Periodic timer */
20103 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20104 	    ipst->ips_ip_ire_arp_interval) {
20105 		/*
20106 		 * Remove all IRE_CACHE entries since they might
20107 		 * contain arp information.
20108 		 */
20109 		flush_flag |= FLUSH_ARP_TIME;
20110 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20111 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20112 	}
20113 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20114 	    ipst->ips_ip_ire_redir_interval) {
20115 		/* Remove all redirects */
20116 		flush_flag |= FLUSH_REDIRECT_TIME;
20117 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20118 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20119 	}
20120 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20121 	    ipst->ips_ip_ire_pathmtu_interval) {
20122 		/* Increase path mtu */
20123 		flush_flag |= FLUSH_MTU_TIME;
20124 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20125 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20126 	}
20127 
20128 	/*
20129 	 * Optimize for the case when there are no redirects in the
20130 	 * ftable, that is, no need to walk the ftable in that case.
20131 	 */
20132 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20133 		iea.iea_flush_flag = flush_flag;
20134 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20135 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20136 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20137 		    NULL, ALL_ZONES, ipst);
20138 	}
20139 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20140 	    ipst->ips_ip_redirect_cnt > 0) {
20141 		iea.iea_flush_flag = flush_flag;
20142 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20143 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20144 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20145 	}
20146 	if (flush_flag & FLUSH_MTU_TIME) {
20147 		/*
20148 		 * Walk all IPv6 IRE's and update them
20149 		 * Note that ARP and redirect timers are not
20150 		 * needed since NUD handles stale entries.
20151 		 */
20152 		flush_flag = FLUSH_MTU_TIME;
20153 		iea.iea_flush_flag = flush_flag;
20154 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20155 		    ALL_ZONES, ipst);
20156 	}
20157 
20158 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20159 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20160 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20161 
20162 	/*
20163 	 * Hold the lock to serialize timeout calls and prevent
20164 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20165 	 * for the timer to fire and a new invocation of this function
20166 	 * to start before the return value of timeout has been stored
20167 	 * in ip_ire_expire_id by the current invocation.
20168 	 */
20169 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20170 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20171 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20172 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20173 }
20174 
20175 /*
20176  * Called by the memory allocator subsystem directly, when the system
20177  * is running low on memory.
20178  */
20179 /* ARGSUSED */
20180 void
20181 ip_trash_ire_reclaim(void *args)
20182 {
20183 	netstack_handle_t nh;
20184 	netstack_t *ns;
20185 
20186 	netstack_next_init(&nh);
20187 	while ((ns = netstack_next(&nh)) != NULL) {
20188 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20189 		netstack_rele(ns);
20190 	}
20191 	netstack_next_fini(&nh);
20192 }
20193 
20194 static void
20195 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20196 {
20197 	ire_cache_count_t icc;
20198 	ire_cache_reclaim_t icr;
20199 	ncc_cache_count_t ncc;
20200 	nce_cache_reclaim_t ncr;
20201 	uint_t delete_cnt;
20202 	/*
20203 	 * Memory reclaim call back.
20204 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20205 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20206 	 * entries, determine what fraction to free for
20207 	 * each category of IRE_CACHE entries giving absolute priority
20208 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20209 	 * entry will be freed unless all offlink entries are freed).
20210 	 */
20211 	icc.icc_total = 0;
20212 	icc.icc_unused = 0;
20213 	icc.icc_offlink = 0;
20214 	icc.icc_pmtu = 0;
20215 	icc.icc_onlink = 0;
20216 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20217 
20218 	/*
20219 	 * Free NCEs for IPv6 like the onlink ires.
20220 	 */
20221 	ncc.ncc_total = 0;
20222 	ncc.ncc_host = 0;
20223 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20224 
20225 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20226 	    icc.icc_pmtu + icc.icc_onlink);
20227 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20228 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20229 	if (delete_cnt == 0)
20230 		return;
20231 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20232 	/* Always delete all unused offlink entries */
20233 	icr.icr_ipst = ipst;
20234 	icr.icr_unused = 1;
20235 	if (delete_cnt <= icc.icc_unused) {
20236 		/*
20237 		 * Only need to free unused entries.  In other words,
20238 		 * there are enough unused entries to free to meet our
20239 		 * target number of freed ire cache entries.
20240 		 */
20241 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20242 		ncr.ncr_host = 0;
20243 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20244 		/*
20245 		 * Only need to free unused entries, plus a fraction of offlink
20246 		 * entries.  It follows from the first if statement that
20247 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20248 		 */
20249 		delete_cnt -= icc.icc_unused;
20250 		/* Round up # deleted by truncating fraction */
20251 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20252 		icr.icr_pmtu = icr.icr_onlink = 0;
20253 		ncr.ncr_host = 0;
20254 	} else if (delete_cnt <=
20255 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20256 		/*
20257 		 * Free all unused and offlink entries, plus a fraction of
20258 		 * pmtu entries.  It follows from the previous if statement
20259 		 * that icc_pmtu is non-zero, and that
20260 		 * delete_cnt != icc_unused + icc_offlink.
20261 		 */
20262 		icr.icr_offlink = 1;
20263 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20264 		/* Round up # deleted by truncating fraction */
20265 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20266 		icr.icr_onlink = 0;
20267 		ncr.ncr_host = 0;
20268 	} else {
20269 		/*
20270 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20271 		 * of onlink entries.  If we're here, then we know that
20272 		 * icc_onlink is non-zero, and that
20273 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20274 		 */
20275 		icr.icr_offlink = icr.icr_pmtu = 1;
20276 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20277 		    icc.icc_pmtu;
20278 		/* Round up # deleted by truncating fraction */
20279 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20280 		/* Using the same delete fraction as for onlink IREs */
20281 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20282 	}
20283 #ifdef DEBUG
20284 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20285 	    "fractions %d/%d/%d/%d\n",
20286 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20287 	    icc.icc_unused, icc.icc_offlink,
20288 	    icc.icc_pmtu, icc.icc_onlink,
20289 	    icr.icr_unused, icr.icr_offlink,
20290 	    icr.icr_pmtu, icr.icr_onlink));
20291 #endif
20292 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20293 	if (ncr.ncr_host != 0)
20294 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20295 		    (uchar_t *)&ncr, ipst);
20296 #ifdef DEBUG
20297 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20298 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20299 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20300 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20301 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20302 	    icc.icc_pmtu, icc.icc_onlink));
20303 #endif
20304 }
20305 
20306 /*
20307  * ip_unbind is called when a copy of an unbind request is received from the
20308  * upper level protocol.  We remove this conn from any fanout hash list it is
20309  * on, and zero out the bind information.  No reply is expected up above.
20310  */
20311 void
20312 ip_unbind(conn_t *connp)
20313 {
20314 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20315 
20316 	if (is_system_labeled() && connp->conn_anon_port) {
20317 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20318 		    connp->conn_mlp_type, connp->conn_ulp,
20319 		    ntohs(connp->conn_lport), B_FALSE);
20320 		connp->conn_anon_port = 0;
20321 	}
20322 	connp->conn_mlp_type = mlptSingle;
20323 
20324 	ipcl_hash_remove(connp);
20325 }
20326 
20327 /*
20328  * Write side put procedure.  Outbound data, IOCTLs, responses from
20329  * resolvers, etc, come down through here.
20330  *
20331  * arg2 is always a queue_t *.
20332  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20333  * the zoneid.
20334  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20335  */
20336 void
20337 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20338 {
20339 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20340 }
20341 
20342 void
20343 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20344     ip_opt_info_t *infop)
20345 {
20346 	conn_t		*connp = NULL;
20347 	queue_t		*q = (queue_t *)arg2;
20348 	ipha_t		*ipha;
20349 #define	rptr	((uchar_t *)ipha)
20350 	ire_t		*ire = NULL;
20351 	ire_t		*sctp_ire = NULL;
20352 	uint32_t	v_hlen_tos_len;
20353 	ipaddr_t	dst;
20354 	mblk_t		*first_mp = NULL;
20355 	boolean_t	mctl_present;
20356 	ipsec_out_t	*io;
20357 	int		match_flags;
20358 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20359 	ipif_t		*dst_ipif;
20360 	boolean_t	multirt_need_resolve = B_FALSE;
20361 	mblk_t		*copy_mp = NULL;
20362 	int		err = 0;
20363 	zoneid_t	zoneid;
20364 	boolean_t	need_decref = B_FALSE;
20365 	boolean_t	ignore_dontroute = B_FALSE;
20366 	boolean_t	ignore_nexthop = B_FALSE;
20367 	boolean_t	ip_nexthop = B_FALSE;
20368 	ipaddr_t	nexthop_addr;
20369 	ip_stack_t	*ipst;
20370 
20371 #ifdef	_BIG_ENDIAN
20372 #define	V_HLEN	(v_hlen_tos_len >> 24)
20373 #else
20374 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20375 #endif
20376 
20377 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20378 	    "ip_wput_start: q %p", q);
20379 
20380 	/*
20381 	 * ip_wput fast path
20382 	 */
20383 
20384 	/* is packet from ARP ? */
20385 	if (q->q_next != NULL) {
20386 		zoneid = (zoneid_t)(uintptr_t)arg;
20387 		goto qnext;
20388 	}
20389 
20390 	connp = (conn_t *)arg;
20391 	ASSERT(connp != NULL);
20392 	zoneid = connp->conn_zoneid;
20393 	ipst = connp->conn_netstack->netstack_ip;
20394 	ASSERT(ipst != NULL);
20395 
20396 	/* is queue flow controlled? */
20397 	if ((q->q_first != NULL || connp->conn_draining) &&
20398 	    (caller == IP_WPUT)) {
20399 		ASSERT(!need_decref);
20400 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20401 		(void) putq(q, mp);
20402 		return;
20403 	}
20404 
20405 	/* Multidata transmit? */
20406 	if (DB_TYPE(mp) == M_MULTIDATA) {
20407 		/*
20408 		 * We should never get here, since all Multidata messages
20409 		 * originating from tcp should have been directed over to
20410 		 * tcp_multisend() in the first place.
20411 		 */
20412 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20413 		freemsg(mp);
20414 		return;
20415 	} else if (DB_TYPE(mp) != M_DATA)
20416 		goto notdata;
20417 
20418 	if (mp->b_flag & MSGHASREF) {
20419 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20420 		mp->b_flag &= ~MSGHASREF;
20421 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20422 		need_decref = B_TRUE;
20423 	}
20424 	ipha = (ipha_t *)mp->b_rptr;
20425 
20426 	/* is IP header non-aligned or mblk smaller than basic IP header */
20427 #ifndef SAFETY_BEFORE_SPEED
20428 	if (!OK_32PTR(rptr) ||
20429 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20430 		goto hdrtoosmall;
20431 #endif
20432 
20433 	ASSERT(OK_32PTR(ipha));
20434 
20435 	/*
20436 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20437 	 * wrong version, we'll catch it again in ip_output_v6.
20438 	 *
20439 	 * Note that this is *only* locally-generated output here, and never
20440 	 * forwarded data, and that we need to deal only with transports that
20441 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20442 	 * label.)
20443 	 */
20444 	if (is_system_labeled() &&
20445 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20446 	    !connp->conn_ulp_labeled) {
20447 		cred_t	*credp;
20448 		pid_t	pid;
20449 
20450 		credp = BEST_CRED(mp, connp, &pid);
20451 		err = tsol_check_label(credp, &mp,
20452 		    connp->conn_mac_mode, ipst, pid);
20453 		ipha = (ipha_t *)mp->b_rptr;
20454 		if (err != 0) {
20455 			first_mp = mp;
20456 			if (err == EINVAL)
20457 				goto icmp_parameter_problem;
20458 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20459 			goto discard_pkt;
20460 		}
20461 	}
20462 
20463 	ASSERT(infop != NULL);
20464 
20465 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20466 		/*
20467 		 * IP_PKTINFO ancillary option is present.
20468 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20469 		 * allows using address of any zone as the source address.
20470 		 */
20471 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20472 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20473 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20474 		if (ire == NULL)
20475 			goto drop_pkt;
20476 		ire_refrele(ire);
20477 		ire = NULL;
20478 	}
20479 
20480 	/*
20481 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20482 	 */
20483 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20484 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20485 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20486 
20487 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20488 			goto drop_pkt;
20489 		/*
20490 		 * check that there is an ipif belonging
20491 		 * to our zone. IPCL_ZONEID is not used because
20492 		 * IP_ALLZONES option is valid only when the ill is
20493 		 * accessible from all zones i.e has a valid ipif in
20494 		 * all zones.
20495 		 */
20496 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20497 			goto drop_pkt;
20498 		}
20499 	}
20500 
20501 	/*
20502 	 * If there is a policy, try to attach an ipsec_out in
20503 	 * the front. At the end, first_mp either points to a
20504 	 * M_DATA message or IPSEC_OUT message linked to a
20505 	 * M_DATA message. We have to do it now as we might
20506 	 * lose the "conn" if we go through ip_newroute.
20507 	 */
20508 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20509 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20510 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20511 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20512 			if (need_decref)
20513 				CONN_DEC_REF(connp);
20514 			return;
20515 		}
20516 		ASSERT(mp->b_datap->db_type == M_CTL);
20517 		first_mp = mp;
20518 		mp = mp->b_cont;
20519 		mctl_present = B_TRUE;
20520 	} else {
20521 		first_mp = mp;
20522 		mctl_present = B_FALSE;
20523 	}
20524 
20525 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20526 
20527 	/* is wrong version or IP options present */
20528 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20529 		goto version_hdrlen_check;
20530 	dst = ipha->ipha_dst;
20531 
20532 	/* If IP_BOUND_IF has been set, use that ill. */
20533 	if (connp->conn_outgoing_ill != NULL) {
20534 		xmit_ill = conn_get_held_ill(connp,
20535 		    &connp->conn_outgoing_ill, &err);
20536 		if (err == ILL_LOOKUP_FAILED)
20537 			goto drop_pkt;
20538 
20539 		goto send_from_ill;
20540 	}
20541 
20542 	/* is packet multicast? */
20543 	if (CLASSD(dst))
20544 		goto multicast;
20545 
20546 	/*
20547 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20548 	 * takes precedence over conn_dontroute and conn_nexthop_set
20549 	 */
20550 	if (xmit_ill != NULL)
20551 		goto send_from_ill;
20552 
20553 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20554 		/*
20555 		 * If the destination is a broadcast, local, or loopback
20556 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20557 		 * standard path.
20558 		 */
20559 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20560 		if ((ire == NULL) || (ire->ire_type &
20561 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20562 			if (ire != NULL) {
20563 				ire_refrele(ire);
20564 				/* No more access to ire */
20565 				ire = NULL;
20566 			}
20567 			/*
20568 			 * bypass routing checks and go directly to interface.
20569 			 */
20570 			if (connp->conn_dontroute)
20571 				goto dontroute;
20572 
20573 			ASSERT(connp->conn_nexthop_set);
20574 			ip_nexthop = B_TRUE;
20575 			nexthop_addr = connp->conn_nexthop_v4;
20576 			goto send_from_ill;
20577 		}
20578 
20579 		/* Must be a broadcast, a loopback or a local ire */
20580 		ire_refrele(ire);
20581 		/* No more access to ire */
20582 		ire = NULL;
20583 	}
20584 
20585 	/*
20586 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20587 	 * this for the tcp global queue and listen end point
20588 	 * as it does not really have a real destination to
20589 	 * talk to.  This is also true for SCTP.
20590 	 */
20591 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20592 	    !connp->conn_fully_bound) {
20593 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20594 		if (ire == NULL)
20595 			goto noirefound;
20596 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20597 		    "ip_wput_end: q %p (%S)", q, "end");
20598 
20599 		/*
20600 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20601 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20602 		 */
20603 		if (ire->ire_flags & RTF_MULTIRT) {
20604 
20605 			/*
20606 			 * Force the TTL of multirouted packets if required.
20607 			 * The TTL of such packets is bounded by the
20608 			 * ip_multirt_ttl ndd variable.
20609 			 */
20610 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20611 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20612 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20613 				    "(was %d), dst 0x%08x\n",
20614 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20615 				    ntohl(ire->ire_addr)));
20616 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20617 			}
20618 			/*
20619 			 * We look at this point if there are pending
20620 			 * unresolved routes. ire_multirt_resolvable()
20621 			 * checks in O(n) that all IRE_OFFSUBNET ire
20622 			 * entries for the packet's destination and
20623 			 * flagged RTF_MULTIRT are currently resolved.
20624 			 * If some remain unresolved, we make a copy
20625 			 * of the current message. It will be used
20626 			 * to initiate additional route resolutions.
20627 			 */
20628 			multirt_need_resolve =
20629 			    ire_multirt_need_resolve(ire->ire_addr,
20630 			    msg_getlabel(first_mp), ipst);
20631 			ip2dbg(("ip_wput[TCP]: ire %p, "
20632 			    "multirt_need_resolve %d, first_mp %p\n",
20633 			    (void *)ire, multirt_need_resolve,
20634 			    (void *)first_mp));
20635 			if (multirt_need_resolve) {
20636 				copy_mp = copymsg(first_mp);
20637 				if (copy_mp != NULL) {
20638 					MULTIRT_DEBUG_TAG(copy_mp);
20639 				}
20640 			}
20641 		}
20642 
20643 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20644 
20645 		/*
20646 		 * Try to resolve another multiroute if
20647 		 * ire_multirt_need_resolve() deemed it necessary.
20648 		 */
20649 		if (copy_mp != NULL)
20650 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20651 		if (need_decref)
20652 			CONN_DEC_REF(connp);
20653 		return;
20654 	}
20655 
20656 	/*
20657 	 * Access to conn_ire_cache. (protected by conn_lock)
20658 	 *
20659 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20660 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20661 	 * send a packet or two with the IRE_CACHE that is going away.
20662 	 * Access to the ire requires an ire refhold on the ire prior to
20663 	 * its use since an interface unplumb thread may delete the cached
20664 	 * ire and release the refhold at any time.
20665 	 *
20666 	 * Caching an ire in the conn_ire_cache
20667 	 *
20668 	 * o Caching an ire pointer in the conn requires a strict check for
20669 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20670 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20671 	 * in the conn is done after making sure under the bucket lock that the
20672 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20673 	 * caching an ire after the unplumb thread has cleaned up the conn.
20674 	 * If the conn does not send a packet subsequently the unplumb thread
20675 	 * will be hanging waiting for the ire count to drop to zero.
20676 	 *
20677 	 * o We also need to atomically test for a null conn_ire_cache and
20678 	 * set the conn_ire_cache under the the protection of the conn_lock
20679 	 * to avoid races among concurrent threads trying to simultaneously
20680 	 * cache an ire in the conn_ire_cache.
20681 	 */
20682 	mutex_enter(&connp->conn_lock);
20683 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20684 
20685 	if (ire != NULL && ire->ire_addr == dst &&
20686 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20687 
20688 		IRE_REFHOLD(ire);
20689 		mutex_exit(&connp->conn_lock);
20690 
20691 	} else {
20692 		boolean_t cached = B_FALSE;
20693 		connp->conn_ire_cache = NULL;
20694 		mutex_exit(&connp->conn_lock);
20695 		/* Release the old ire */
20696 		if (ire != NULL && sctp_ire == NULL)
20697 			IRE_REFRELE_NOTR(ire);
20698 
20699 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20700 		if (ire == NULL)
20701 			goto noirefound;
20702 		IRE_REFHOLD_NOTR(ire);
20703 
20704 		mutex_enter(&connp->conn_lock);
20705 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20706 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20707 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20708 				if (connp->conn_ulp == IPPROTO_TCP)
20709 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20710 				connp->conn_ire_cache = ire;
20711 				cached = B_TRUE;
20712 			}
20713 			rw_exit(&ire->ire_bucket->irb_lock);
20714 		}
20715 		mutex_exit(&connp->conn_lock);
20716 
20717 		/*
20718 		 * We can continue to use the ire but since it was
20719 		 * not cached, we should drop the extra reference.
20720 		 */
20721 		if (!cached)
20722 			IRE_REFRELE_NOTR(ire);
20723 	}
20724 
20725 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20726 	    "ip_wput_end: q %p (%S)", q, "end");
20727 
20728 	/*
20729 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20730 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20731 	 */
20732 	if (ire->ire_flags & RTF_MULTIRT) {
20733 		/*
20734 		 * Force the TTL of multirouted packets if required.
20735 		 * The TTL of such packets is bounded by the
20736 		 * ip_multirt_ttl ndd variable.
20737 		 */
20738 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20739 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20740 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20741 			    "(was %d), dst 0x%08x\n",
20742 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20743 			    ntohl(ire->ire_addr)));
20744 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20745 		}
20746 
20747 		/*
20748 		 * At this point, we check to see if there are any pending
20749 		 * unresolved routes. ire_multirt_resolvable()
20750 		 * checks in O(n) that all IRE_OFFSUBNET ire
20751 		 * entries for the packet's destination and
20752 		 * flagged RTF_MULTIRT are currently resolved.
20753 		 * If some remain unresolved, we make a copy
20754 		 * of the current message. It will be used
20755 		 * to initiate additional route resolutions.
20756 		 */
20757 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20758 		    msg_getlabel(first_mp), ipst);
20759 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20760 		    "multirt_need_resolve %d, first_mp %p\n",
20761 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20762 		if (multirt_need_resolve) {
20763 			copy_mp = copymsg(first_mp);
20764 			if (copy_mp != NULL) {
20765 				MULTIRT_DEBUG_TAG(copy_mp);
20766 			}
20767 		}
20768 	}
20769 
20770 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20771 
20772 	/*
20773 	 * Try to resolve another multiroute if
20774 	 * ire_multirt_resolvable() deemed it necessary
20775 	 */
20776 	if (copy_mp != NULL)
20777 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20778 	if (need_decref)
20779 		CONN_DEC_REF(connp);
20780 	return;
20781 
20782 qnext:
20783 	/*
20784 	 * Upper Level Protocols pass down complete IP datagrams
20785 	 * as M_DATA messages.	Everything else is a sideshow.
20786 	 *
20787 	 * 1) We could be re-entering ip_wput because of ip_neworute
20788 	 *    in which case we could have a IPSEC_OUT message. We
20789 	 *    need to pass through ip_wput like other datagrams and
20790 	 *    hence cannot branch to ip_wput_nondata.
20791 	 *
20792 	 * 2) ARP, AH, ESP, and other clients who are on the module
20793 	 *    instance of IP stream, give us something to deal with.
20794 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20795 	 *
20796 	 * 3) ICMP replies also could come here.
20797 	 */
20798 	ipst = ILLQ_TO_IPST(q);
20799 
20800 	if (DB_TYPE(mp) != M_DATA) {
20801 notdata:
20802 		if (DB_TYPE(mp) == M_CTL) {
20803 			/*
20804 			 * M_CTL messages are used by ARP, AH and ESP to
20805 			 * communicate with IP. We deal with IPSEC_IN and
20806 			 * IPSEC_OUT here. ip_wput_nondata handles other
20807 			 * cases.
20808 			 */
20809 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20810 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20811 				first_mp = mp->b_cont;
20812 				first_mp->b_flag &= ~MSGHASREF;
20813 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20814 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20815 				CONN_DEC_REF(connp);
20816 				connp = NULL;
20817 			}
20818 			if (ii->ipsec_info_type == IPSEC_IN) {
20819 				/*
20820 				 * Either this message goes back to
20821 				 * IPsec for further processing or to
20822 				 * ULP after policy checks.
20823 				 */
20824 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20825 				return;
20826 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20827 				io = (ipsec_out_t *)ii;
20828 				if (io->ipsec_out_proc_begin) {
20829 					/*
20830 					 * IPsec processing has already started.
20831 					 * Complete it.
20832 					 * IPQoS notes: We don't care what is
20833 					 * in ipsec_out_ill_index since this
20834 					 * won't be processed for IPQoS policies
20835 					 * in ipsec_out_process.
20836 					 */
20837 					ipsec_out_process(q, mp, NULL,
20838 					    io->ipsec_out_ill_index);
20839 					return;
20840 				} else {
20841 					connp = (q->q_next != NULL) ?
20842 					    NULL : Q_TO_CONN(q);
20843 					first_mp = mp;
20844 					mp = mp->b_cont;
20845 					mctl_present = B_TRUE;
20846 				}
20847 				zoneid = io->ipsec_out_zoneid;
20848 				ASSERT(zoneid != ALL_ZONES);
20849 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20850 				/*
20851 				 * It's an IPsec control message requesting
20852 				 * an SADB update to be sent to the IPsec
20853 				 * hardware acceleration capable ills.
20854 				 */
20855 				ipsec_ctl_t *ipsec_ctl =
20856 				    (ipsec_ctl_t *)mp->b_rptr;
20857 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20858 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20859 				mblk_t *cmp = mp->b_cont;
20860 
20861 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20862 				ASSERT(cmp != NULL);
20863 
20864 				freeb(mp);
20865 				ill_ipsec_capab_send_all(satype, cmp, sa,
20866 				    ipst->ips_netstack);
20867 				return;
20868 			} else {
20869 				/*
20870 				 * This must be ARP or special TSOL signaling.
20871 				 */
20872 				ip_wput_nondata(NULL, q, mp, NULL);
20873 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20874 				    "ip_wput_end: q %p (%S)", q, "nondata");
20875 				return;
20876 			}
20877 		} else {
20878 			/*
20879 			 * This must be non-(ARP/AH/ESP) messages.
20880 			 */
20881 			ASSERT(!need_decref);
20882 			ip_wput_nondata(NULL, q, mp, NULL);
20883 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20884 			    "ip_wput_end: q %p (%S)", q, "nondata");
20885 			return;
20886 		}
20887 	} else {
20888 		first_mp = mp;
20889 		mctl_present = B_FALSE;
20890 	}
20891 
20892 	ASSERT(first_mp != NULL);
20893 
20894 	if (mctl_present) {
20895 		io = (ipsec_out_t *)first_mp->b_rptr;
20896 		if (io->ipsec_out_ip_nexthop) {
20897 			/*
20898 			 * We may have lost the conn context if we are
20899 			 * coming here from ip_newroute(). Copy the
20900 			 * nexthop information.
20901 			 */
20902 			ip_nexthop = B_TRUE;
20903 			nexthop_addr = io->ipsec_out_nexthop_addr;
20904 
20905 			ipha = (ipha_t *)mp->b_rptr;
20906 			dst = ipha->ipha_dst;
20907 			goto send_from_ill;
20908 		}
20909 	}
20910 
20911 	ASSERT(xmit_ill == NULL);
20912 
20913 	/* We have a complete IP datagram heading outbound. */
20914 	ipha = (ipha_t *)mp->b_rptr;
20915 
20916 #ifndef SPEED_BEFORE_SAFETY
20917 	/*
20918 	 * Make sure we have a full-word aligned message and that at least
20919 	 * a simple IP header is accessible in the first message.  If not,
20920 	 * try a pullup.  For labeled systems we need to always take this
20921 	 * path as M_CTLs are "notdata" but have trailing data to process.
20922 	 */
20923 	if (!OK_32PTR(rptr) ||
20924 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20925 hdrtoosmall:
20926 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20927 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20928 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20929 			if (first_mp == NULL)
20930 				first_mp = mp;
20931 			goto discard_pkt;
20932 		}
20933 
20934 		/* This function assumes that mp points to an IPv4 packet. */
20935 		if (is_system_labeled() &&
20936 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20937 		    (connp == NULL || !connp->conn_ulp_labeled)) {
20938 			cred_t	*credp;
20939 			pid_t	pid;
20940 
20941 			if (connp != NULL) {
20942 				credp = BEST_CRED(mp, connp, &pid);
20943 				err = tsol_check_label(credp, &mp,
20944 				    connp->conn_mac_mode, ipst, pid);
20945 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
20946 				err = tsol_check_label(credp, &mp,
20947 				    CONN_MAC_DEFAULT, ipst, pid);
20948 			}
20949 			ipha = (ipha_t *)mp->b_rptr;
20950 			if (mctl_present)
20951 				first_mp->b_cont = mp;
20952 			else
20953 				first_mp = mp;
20954 			if (err != 0) {
20955 				if (err == EINVAL)
20956 					goto icmp_parameter_problem;
20957 				ip2dbg(("ip_wput: label check failed (%d)\n",
20958 				    err));
20959 				goto discard_pkt;
20960 			}
20961 		}
20962 
20963 		ipha = (ipha_t *)mp->b_rptr;
20964 		if (first_mp == NULL) {
20965 			ASSERT(xmit_ill == NULL);
20966 			/*
20967 			 * If we got here because of "goto hdrtoosmall"
20968 			 * We need to attach a IPSEC_OUT.
20969 			 */
20970 			if (connp->conn_out_enforce_policy) {
20971 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20972 				    NULL, ipha->ipha_protocol,
20973 				    ipst->ips_netstack)) == NULL)) {
20974 					BUMP_MIB(&ipst->ips_ip_mib,
20975 					    ipIfStatsOutDiscards);
20976 					if (need_decref)
20977 						CONN_DEC_REF(connp);
20978 					return;
20979 				} else {
20980 					ASSERT(mp->b_datap->db_type == M_CTL);
20981 					first_mp = mp;
20982 					mp = mp->b_cont;
20983 					mctl_present = B_TRUE;
20984 				}
20985 			} else {
20986 				first_mp = mp;
20987 				mctl_present = B_FALSE;
20988 			}
20989 		}
20990 	}
20991 #endif
20992 
20993 	/* Most of the code below is written for speed, not readability */
20994 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20995 
20996 	/*
20997 	 * If ip_newroute() fails, we're going to need a full
20998 	 * header for the icmp wraparound.
20999 	 */
21000 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21001 		uint_t	v_hlen;
21002 version_hdrlen_check:
21003 		ASSERT(first_mp != NULL);
21004 		v_hlen = V_HLEN;
21005 		/*
21006 		 * siphon off IPv6 packets coming down from transport
21007 		 * layer modules here.
21008 		 * Note: high-order bit carries NUD reachability confirmation
21009 		 */
21010 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21011 			/*
21012 			 * FIXME: assume that callers of ip_output* call
21013 			 * the right version?
21014 			 */
21015 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21016 			ASSERT(xmit_ill == NULL);
21017 			if (need_decref)
21018 				mp->b_flag |= MSGHASREF;
21019 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21020 			return;
21021 		}
21022 
21023 		if ((v_hlen >> 4) != IP_VERSION) {
21024 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21025 			    "ip_wput_end: q %p (%S)", q, "badvers");
21026 			goto discard_pkt;
21027 		}
21028 		/*
21029 		 * Is the header length at least 20 bytes?
21030 		 *
21031 		 * Are there enough bytes accessible in the header?  If
21032 		 * not, try a pullup.
21033 		 */
21034 		v_hlen &= 0xF;
21035 		v_hlen <<= 2;
21036 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21037 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21038 			    "ip_wput_end: q %p (%S)", q, "badlen");
21039 			goto discard_pkt;
21040 		}
21041 		if (v_hlen > (mp->b_wptr - rptr)) {
21042 			if (!pullupmsg(mp, v_hlen)) {
21043 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21044 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21045 				goto discard_pkt;
21046 			}
21047 			ipha = (ipha_t *)mp->b_rptr;
21048 		}
21049 		/*
21050 		 * Move first entry from any source route into ipha_dst and
21051 		 * verify the options
21052 		 */
21053 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21054 		    zoneid, ipst)) {
21055 			ASSERT(xmit_ill == NULL);
21056 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21057 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21058 			    "ip_wput_end: q %p (%S)", q, "badopts");
21059 			if (need_decref)
21060 				CONN_DEC_REF(connp);
21061 			return;
21062 		}
21063 	}
21064 	dst = ipha->ipha_dst;
21065 
21066 	/*
21067 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21068 	 * we have to run the packet through ip_newroute which will take
21069 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21070 	 * a resolver, or assigning a default gateway, etc.
21071 	 */
21072 	if (CLASSD(dst)) {
21073 		ipif_t	*ipif;
21074 		uint32_t setsrc = 0;
21075 
21076 multicast:
21077 		ASSERT(first_mp != NULL);
21078 		ip2dbg(("ip_wput: CLASSD\n"));
21079 		if (connp == NULL) {
21080 			/*
21081 			 * Use the first good ipif on the ill.
21082 			 * XXX Should this ever happen? (Appears
21083 			 * to show up with just ppp and no ethernet due
21084 			 * to in.rdisc.)
21085 			 * However, ire_send should be able to
21086 			 * call ip_wput_ire directly.
21087 			 *
21088 			 * XXX Also, this can happen for ICMP and other packets
21089 			 * with multicast source addresses.  Perhaps we should
21090 			 * fix things so that we drop the packet in question,
21091 			 * but for now, just run with it.
21092 			 */
21093 			ill_t *ill = (ill_t *)q->q_ptr;
21094 
21095 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21096 			if (ipif == NULL) {
21097 				if (need_decref)
21098 					CONN_DEC_REF(connp);
21099 				freemsg(first_mp);
21100 				return;
21101 			}
21102 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21103 			    ntohl(dst), ill->ill_name));
21104 		} else {
21105 			/*
21106 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21107 			 * and IP_MULTICAST_IF.  The block comment above this
21108 			 * function explains the locking mechanism used here.
21109 			 */
21110 			if (xmit_ill == NULL) {
21111 				xmit_ill = conn_get_held_ill(connp,
21112 				    &connp->conn_outgoing_ill, &err);
21113 				if (err == ILL_LOOKUP_FAILED) {
21114 					ip1dbg(("ip_wput: No ill for "
21115 					    "IP_BOUND_IF\n"));
21116 					BUMP_MIB(&ipst->ips_ip_mib,
21117 					    ipIfStatsOutNoRoutes);
21118 					goto drop_pkt;
21119 				}
21120 			}
21121 
21122 			if (xmit_ill == NULL) {
21123 				ipif = conn_get_held_ipif(connp,
21124 				    &connp->conn_multicast_ipif, &err);
21125 				if (err == IPIF_LOOKUP_FAILED) {
21126 					ip1dbg(("ip_wput: No ipif for "
21127 					    "multicast\n"));
21128 					BUMP_MIB(&ipst->ips_ip_mib,
21129 					    ipIfStatsOutNoRoutes);
21130 					goto drop_pkt;
21131 				}
21132 			}
21133 			if (xmit_ill != NULL) {
21134 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21135 				if (ipif == NULL) {
21136 					ip1dbg(("ip_wput: No ipif for "
21137 					    "xmit_ill\n"));
21138 					BUMP_MIB(&ipst->ips_ip_mib,
21139 					    ipIfStatsOutNoRoutes);
21140 					goto drop_pkt;
21141 				}
21142 			} else if (ipif == NULL || ipif->ipif_isv6) {
21143 				/*
21144 				 * We must do this ipif determination here
21145 				 * else we could pass through ip_newroute
21146 				 * and come back here without the conn context.
21147 				 *
21148 				 * Note: we do late binding i.e. we bind to
21149 				 * the interface when the first packet is sent.
21150 				 * For performance reasons we do not rebind on
21151 				 * each packet but keep the binding until the
21152 				 * next IP_MULTICAST_IF option.
21153 				 *
21154 				 * conn_multicast_{ipif,ill} are shared between
21155 				 * IPv4 and IPv6 and AF_INET6 sockets can
21156 				 * send both IPv4 and IPv6 packets. Hence
21157 				 * we have to check that "isv6" matches above.
21158 				 */
21159 				if (ipif != NULL)
21160 					ipif_refrele(ipif);
21161 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21162 				if (ipif == NULL) {
21163 					ip1dbg(("ip_wput: No ipif for "
21164 					    "multicast\n"));
21165 					BUMP_MIB(&ipst->ips_ip_mib,
21166 					    ipIfStatsOutNoRoutes);
21167 					goto drop_pkt;
21168 				}
21169 				err = conn_set_held_ipif(connp,
21170 				    &connp->conn_multicast_ipif, ipif);
21171 				if (err == IPIF_LOOKUP_FAILED) {
21172 					ipif_refrele(ipif);
21173 					ip1dbg(("ip_wput: No ipif for "
21174 					    "multicast\n"));
21175 					BUMP_MIB(&ipst->ips_ip_mib,
21176 					    ipIfStatsOutNoRoutes);
21177 					goto drop_pkt;
21178 				}
21179 			}
21180 		}
21181 		ASSERT(!ipif->ipif_isv6);
21182 		/*
21183 		 * As we may lose the conn by the time we reach ip_wput_ire,
21184 		 * we copy conn_multicast_loop and conn_dontroute on to an
21185 		 * ipsec_out. In case if this datagram goes out secure,
21186 		 * we need the ill_index also. Copy that also into the
21187 		 * ipsec_out.
21188 		 */
21189 		if (mctl_present) {
21190 			io = (ipsec_out_t *)first_mp->b_rptr;
21191 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21192 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21193 		} else {
21194 			ASSERT(mp == first_mp);
21195 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21196 			    BPRI_HI)) == NULL) {
21197 				ipif_refrele(ipif);
21198 				first_mp = mp;
21199 				goto discard_pkt;
21200 			}
21201 			first_mp->b_datap->db_type = M_CTL;
21202 			first_mp->b_wptr += sizeof (ipsec_info_t);
21203 			/* ipsec_out_secure is B_FALSE now */
21204 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21205 			io = (ipsec_out_t *)first_mp->b_rptr;
21206 			io->ipsec_out_type = IPSEC_OUT;
21207 			io->ipsec_out_len = sizeof (ipsec_out_t);
21208 			io->ipsec_out_use_global_policy = B_TRUE;
21209 			io->ipsec_out_ns = ipst->ips_netstack;
21210 			first_mp->b_cont = mp;
21211 			mctl_present = B_TRUE;
21212 		}
21213 
21214 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21215 		io->ipsec_out_ill_index =
21216 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21217 
21218 		if (connp != NULL) {
21219 			io->ipsec_out_multicast_loop =
21220 			    connp->conn_multicast_loop;
21221 			io->ipsec_out_dontroute = connp->conn_dontroute;
21222 			io->ipsec_out_zoneid = connp->conn_zoneid;
21223 		}
21224 		/*
21225 		 * If the application uses IP_MULTICAST_IF with
21226 		 * different logical addresses of the same ILL, we
21227 		 * need to make sure that the soruce address of
21228 		 * the packet matches the logical IP address used
21229 		 * in the option. We do it by initializing ipha_src
21230 		 * here. This should keep IPsec also happy as
21231 		 * when we return from IPsec processing, we don't
21232 		 * have to worry about getting the right address on
21233 		 * the packet. Thus it is sufficient to look for
21234 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21235 		 * MATCH_IRE_IPIF.
21236 		 *
21237 		 * NOTE : We need to do it for non-secure case also as
21238 		 * this might go out secure if there is a global policy
21239 		 * match in ip_wput_ire.
21240 		 *
21241 		 * As we do not have the ire yet, it is possible that
21242 		 * we set the source address here and then later discover
21243 		 * that the ire implies the source address to be assigned
21244 		 * through the RTF_SETSRC flag.
21245 		 * In that case, the setsrc variable will remind us
21246 		 * that overwritting the source address by the one
21247 		 * of the RTF_SETSRC-flagged ire is allowed.
21248 		 */
21249 		if (ipha->ipha_src == INADDR_ANY &&
21250 		    (connp == NULL || !connp->conn_unspec_src)) {
21251 			ipha->ipha_src = ipif->ipif_src_addr;
21252 			setsrc = RTF_SETSRC;
21253 		}
21254 		/*
21255 		 * Find an IRE which matches the destination and the outgoing
21256 		 * queue (i.e. the outgoing interface.)
21257 		 * For loopback use a unicast IP address for
21258 		 * the ire lookup.
21259 		 */
21260 		if (IS_LOOPBACK(ipif->ipif_ill))
21261 			dst = ipif->ipif_lcl_addr;
21262 
21263 		/*
21264 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21265 		 * We don't need to lookup ire in ctable as the packet
21266 		 * needs to be sent to the destination through the specified
21267 		 * ill irrespective of ires in the cache table.
21268 		 */
21269 		ire = NULL;
21270 		if (xmit_ill == NULL) {
21271 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21272 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21273 		}
21274 
21275 		if (ire == NULL) {
21276 			/*
21277 			 * Multicast loopback and multicast forwarding is
21278 			 * done in ip_wput_ire.
21279 			 *
21280 			 * Mark this packet to make it be delivered to
21281 			 * ip_wput_ire after the new ire has been
21282 			 * created.
21283 			 *
21284 			 * The call to ip_newroute_ipif takes into account
21285 			 * the setsrc reminder. In any case, we take care
21286 			 * of the RTF_MULTIRT flag.
21287 			 */
21288 			mp->b_prev = mp->b_next = NULL;
21289 			if (xmit_ill == NULL ||
21290 			    xmit_ill->ill_ipif_up_count > 0) {
21291 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21292 				    setsrc | RTF_MULTIRT, zoneid, infop);
21293 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21294 				    "ip_wput_end: q %p (%S)", q, "noire");
21295 			} else {
21296 				freemsg(first_mp);
21297 			}
21298 			ipif_refrele(ipif);
21299 			if (xmit_ill != NULL)
21300 				ill_refrele(xmit_ill);
21301 			if (need_decref)
21302 				CONN_DEC_REF(connp);
21303 			return;
21304 		}
21305 
21306 		ipif_refrele(ipif);
21307 		ipif = NULL;
21308 		ASSERT(xmit_ill == NULL);
21309 
21310 		/*
21311 		 * Honor the RTF_SETSRC flag for multicast packets,
21312 		 * if allowed by the setsrc reminder.
21313 		 */
21314 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21315 			ipha->ipha_src = ire->ire_src_addr;
21316 		}
21317 
21318 		/*
21319 		 * Unconditionally force the TTL to 1 for
21320 		 * multirouted multicast packets:
21321 		 * multirouted multicast should not cross
21322 		 * multicast routers.
21323 		 */
21324 		if (ire->ire_flags & RTF_MULTIRT) {
21325 			if (ipha->ipha_ttl > 1) {
21326 				ip2dbg(("ip_wput: forcing multicast "
21327 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21328 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21329 				ipha->ipha_ttl = 1;
21330 			}
21331 		}
21332 	} else {
21333 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21334 		if ((ire != NULL) && (ire->ire_type &
21335 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21336 			ignore_dontroute = B_TRUE;
21337 			ignore_nexthop = B_TRUE;
21338 		}
21339 		if (ire != NULL) {
21340 			ire_refrele(ire);
21341 			ire = NULL;
21342 		}
21343 		/*
21344 		 * Guard against coming in from arp in which case conn is NULL.
21345 		 * Also guard against non M_DATA with dontroute set but
21346 		 * destined to local, loopback or broadcast addresses.
21347 		 */
21348 		if (connp != NULL && connp->conn_dontroute &&
21349 		    !ignore_dontroute) {
21350 dontroute:
21351 			/*
21352 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21353 			 * routing protocols from seeing false direct
21354 			 * connectivity.
21355 			 */
21356 			ipha->ipha_ttl = 1;
21357 			/* If suitable ipif not found, drop packet */
21358 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21359 			if (dst_ipif == NULL) {
21360 noroute:
21361 				ip1dbg(("ip_wput: no route for dst using"
21362 				    " SO_DONTROUTE\n"));
21363 				BUMP_MIB(&ipst->ips_ip_mib,
21364 				    ipIfStatsOutNoRoutes);
21365 				mp->b_prev = mp->b_next = NULL;
21366 				if (first_mp == NULL)
21367 					first_mp = mp;
21368 				goto drop_pkt;
21369 			} else {
21370 				/*
21371 				 * If suitable ipif has been found, set
21372 				 * xmit_ill to the corresponding
21373 				 * ipif_ill because we'll be using the
21374 				 * send_from_ill logic below.
21375 				 */
21376 				ASSERT(xmit_ill == NULL);
21377 				xmit_ill = dst_ipif->ipif_ill;
21378 				mutex_enter(&xmit_ill->ill_lock);
21379 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21380 					mutex_exit(&xmit_ill->ill_lock);
21381 					xmit_ill = NULL;
21382 					ipif_refrele(dst_ipif);
21383 					goto noroute;
21384 				}
21385 				ill_refhold_locked(xmit_ill);
21386 				mutex_exit(&xmit_ill->ill_lock);
21387 				ipif_refrele(dst_ipif);
21388 			}
21389 		}
21390 
21391 send_from_ill:
21392 		if (xmit_ill != NULL) {
21393 			ipif_t *ipif;
21394 
21395 			/*
21396 			 * Mark this packet as originated locally
21397 			 */
21398 			mp->b_prev = mp->b_next = NULL;
21399 
21400 			/*
21401 			 * Could be SO_DONTROUTE case also.
21402 			 * Verify that at least one ipif is up on the ill.
21403 			 */
21404 			if (xmit_ill->ill_ipif_up_count == 0) {
21405 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21406 				    xmit_ill->ill_name));
21407 				goto drop_pkt;
21408 			}
21409 
21410 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21411 			if (ipif == NULL) {
21412 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21413 				    xmit_ill->ill_name));
21414 				goto drop_pkt;
21415 			}
21416 
21417 			match_flags = 0;
21418 			if (IS_UNDER_IPMP(xmit_ill))
21419 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21420 
21421 			/*
21422 			 * Look for a ire that is part of the group,
21423 			 * if found use it else call ip_newroute_ipif.
21424 			 * IPCL_ZONEID is not used for matching because
21425 			 * IP_ALLZONES option is valid only when the
21426 			 * ill is accessible from all zones i.e has a
21427 			 * valid ipif in all zones.
21428 			 */
21429 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21430 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21431 			    msg_getlabel(mp), match_flags, ipst);
21432 			/*
21433 			 * If an ire exists use it or else create
21434 			 * an ire but don't add it to the cache.
21435 			 * Adding an ire may cause issues with
21436 			 * asymmetric routing.
21437 			 * In case of multiroute always act as if
21438 			 * ire does not exist.
21439 			 */
21440 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21441 				if (ire != NULL)
21442 					ire_refrele(ire);
21443 				ip_newroute_ipif(q, first_mp, ipif,
21444 				    dst, connp, 0, zoneid, infop);
21445 				ipif_refrele(ipif);
21446 				ip1dbg(("ip_output: xmit_ill via %s\n",
21447 				    xmit_ill->ill_name));
21448 				ill_refrele(xmit_ill);
21449 				if (need_decref)
21450 					CONN_DEC_REF(connp);
21451 				return;
21452 			}
21453 			ipif_refrele(ipif);
21454 		} else if (ip_nexthop || (connp != NULL &&
21455 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21456 			if (!ip_nexthop) {
21457 				ip_nexthop = B_TRUE;
21458 				nexthop_addr = connp->conn_nexthop_v4;
21459 			}
21460 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21461 			    MATCH_IRE_GW;
21462 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21463 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21464 		} else {
21465 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21466 			    ipst);
21467 		}
21468 		if (!ire) {
21469 			if (ip_nexthop && !ignore_nexthop) {
21470 				if (mctl_present) {
21471 					io = (ipsec_out_t *)first_mp->b_rptr;
21472 					ASSERT(first_mp->b_datap->db_type ==
21473 					    M_CTL);
21474 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21475 				} else {
21476 					ASSERT(mp == first_mp);
21477 					first_mp = allocb(
21478 					    sizeof (ipsec_info_t), BPRI_HI);
21479 					if (first_mp == NULL) {
21480 						first_mp = mp;
21481 						goto discard_pkt;
21482 					}
21483 					first_mp->b_datap->db_type = M_CTL;
21484 					first_mp->b_wptr +=
21485 					    sizeof (ipsec_info_t);
21486 					/* ipsec_out_secure is B_FALSE now */
21487 					bzero(first_mp->b_rptr,
21488 					    sizeof (ipsec_info_t));
21489 					io = (ipsec_out_t *)first_mp->b_rptr;
21490 					io->ipsec_out_type = IPSEC_OUT;
21491 					io->ipsec_out_len =
21492 					    sizeof (ipsec_out_t);
21493 					io->ipsec_out_use_global_policy =
21494 					    B_TRUE;
21495 					io->ipsec_out_ns = ipst->ips_netstack;
21496 					first_mp->b_cont = mp;
21497 					mctl_present = B_TRUE;
21498 				}
21499 				io->ipsec_out_ip_nexthop = ip_nexthop;
21500 				io->ipsec_out_nexthop_addr = nexthop_addr;
21501 			}
21502 noirefound:
21503 			/*
21504 			 * Mark this packet as having originated on
21505 			 * this machine.  This will be noted in
21506 			 * ire_add_then_send, which needs to know
21507 			 * whether to run it back through ip_wput or
21508 			 * ip_rput following successful resolution.
21509 			 */
21510 			mp->b_prev = NULL;
21511 			mp->b_next = NULL;
21512 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21513 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21514 			    "ip_wput_end: q %p (%S)", q, "newroute");
21515 			if (xmit_ill != NULL)
21516 				ill_refrele(xmit_ill);
21517 			if (need_decref)
21518 				CONN_DEC_REF(connp);
21519 			return;
21520 		}
21521 	}
21522 
21523 	/* We now know where we are going with it. */
21524 
21525 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21526 	    "ip_wput_end: q %p (%S)", q, "end");
21527 
21528 	/*
21529 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21530 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21531 	 */
21532 	if (ire->ire_flags & RTF_MULTIRT) {
21533 		/*
21534 		 * Force the TTL of multirouted packets if required.
21535 		 * The TTL of such packets is bounded by the
21536 		 * ip_multirt_ttl ndd variable.
21537 		 */
21538 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21539 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21540 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21541 			    "(was %d), dst 0x%08x\n",
21542 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21543 			    ntohl(ire->ire_addr)));
21544 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21545 		}
21546 		/*
21547 		 * At this point, we check to see if there are any pending
21548 		 * unresolved routes. ire_multirt_resolvable()
21549 		 * checks in O(n) that all IRE_OFFSUBNET ire
21550 		 * entries for the packet's destination and
21551 		 * flagged RTF_MULTIRT are currently resolved.
21552 		 * If some remain unresolved, we make a copy
21553 		 * of the current message. It will be used
21554 		 * to initiate additional route resolutions.
21555 		 */
21556 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21557 		    msg_getlabel(first_mp), ipst);
21558 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21559 		    "multirt_need_resolve %d, first_mp %p\n",
21560 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21561 		if (multirt_need_resolve) {
21562 			copy_mp = copymsg(first_mp);
21563 			if (copy_mp != NULL) {
21564 				MULTIRT_DEBUG_TAG(copy_mp);
21565 			}
21566 		}
21567 	}
21568 
21569 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21570 	/*
21571 	 * Try to resolve another multiroute if
21572 	 * ire_multirt_resolvable() deemed it necessary.
21573 	 * At this point, we need to distinguish
21574 	 * multicasts from other packets. For multicasts,
21575 	 * we call ip_newroute_ipif() and request that both
21576 	 * multirouting and setsrc flags are checked.
21577 	 */
21578 	if (copy_mp != NULL) {
21579 		if (CLASSD(dst)) {
21580 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21581 			if (ipif) {
21582 				ASSERT(infop->ip_opt_ill_index == 0);
21583 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21584 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21585 				ipif_refrele(ipif);
21586 			} else {
21587 				MULTIRT_DEBUG_UNTAG(copy_mp);
21588 				freemsg(copy_mp);
21589 				copy_mp = NULL;
21590 			}
21591 		} else {
21592 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21593 		}
21594 	}
21595 	if (xmit_ill != NULL)
21596 		ill_refrele(xmit_ill);
21597 	if (need_decref)
21598 		CONN_DEC_REF(connp);
21599 	return;
21600 
21601 icmp_parameter_problem:
21602 	/* could not have originated externally */
21603 	ASSERT(mp->b_prev == NULL);
21604 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21605 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21606 		/* it's the IP header length that's in trouble */
21607 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21608 		first_mp = NULL;
21609 	}
21610 
21611 discard_pkt:
21612 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21613 drop_pkt:
21614 	ip1dbg(("ip_wput: dropped packet\n"));
21615 	if (ire != NULL)
21616 		ire_refrele(ire);
21617 	if (need_decref)
21618 		CONN_DEC_REF(connp);
21619 	freemsg(first_mp);
21620 	if (xmit_ill != NULL)
21621 		ill_refrele(xmit_ill);
21622 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21623 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21624 }
21625 
21626 /*
21627  * If this is a conn_t queue, then we pass in the conn. This includes the
21628  * zoneid.
21629  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21630  * in which case we use the global zoneid since those are all part of
21631  * the global zone.
21632  */
21633 void
21634 ip_wput(queue_t *q, mblk_t *mp)
21635 {
21636 	if (CONN_Q(q))
21637 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21638 	else
21639 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21640 }
21641 
21642 /*
21643  *
21644  * The following rules must be observed when accessing any ipif or ill
21645  * that has been cached in the conn. Typically conn_outgoing_ill,
21646  * conn_multicast_ipif and conn_multicast_ill.
21647  *
21648  * Access: The ipif or ill pointed to from the conn can be accessed under
21649  * the protection of the conn_lock or after it has been refheld under the
21650  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21651  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21652  * The reason for this is that a concurrent unplumb could actually be
21653  * cleaning up these cached pointers by walking the conns and might have
21654  * finished cleaning up the conn in question. The macros check that an
21655  * unplumb has not yet started on the ipif or ill.
21656  *
21657  * Caching: An ipif or ill pointer may be cached in the conn only after
21658  * making sure that an unplumb has not started. So the caching is done
21659  * while holding both the conn_lock and the ill_lock and after using the
21660  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21661  * flag before starting the cleanup of conns.
21662  *
21663  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21664  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21665  * or a reference to the ipif or a reference to an ire that references the
21666  * ipif. An ipif only changes its ill when migrating from an underlying ill
21667  * to an IPMP ill in ipif_up().
21668  */
21669 ipif_t *
21670 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21671 {
21672 	ipif_t	*ipif;
21673 	ill_t	*ill;
21674 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21675 
21676 	*err = 0;
21677 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21678 	mutex_enter(&connp->conn_lock);
21679 	ipif = *ipifp;
21680 	if (ipif != NULL) {
21681 		ill = ipif->ipif_ill;
21682 		mutex_enter(&ill->ill_lock);
21683 		if (IPIF_CAN_LOOKUP(ipif)) {
21684 			ipif_refhold_locked(ipif);
21685 			mutex_exit(&ill->ill_lock);
21686 			mutex_exit(&connp->conn_lock);
21687 			rw_exit(&ipst->ips_ill_g_lock);
21688 			return (ipif);
21689 		} else {
21690 			*err = IPIF_LOOKUP_FAILED;
21691 		}
21692 		mutex_exit(&ill->ill_lock);
21693 	}
21694 	mutex_exit(&connp->conn_lock);
21695 	rw_exit(&ipst->ips_ill_g_lock);
21696 	return (NULL);
21697 }
21698 
21699 ill_t *
21700 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21701 {
21702 	ill_t	*ill;
21703 
21704 	*err = 0;
21705 	mutex_enter(&connp->conn_lock);
21706 	ill = *illp;
21707 	if (ill != NULL) {
21708 		mutex_enter(&ill->ill_lock);
21709 		if (ILL_CAN_LOOKUP(ill)) {
21710 			ill_refhold_locked(ill);
21711 			mutex_exit(&ill->ill_lock);
21712 			mutex_exit(&connp->conn_lock);
21713 			return (ill);
21714 		} else {
21715 			*err = ILL_LOOKUP_FAILED;
21716 		}
21717 		mutex_exit(&ill->ill_lock);
21718 	}
21719 	mutex_exit(&connp->conn_lock);
21720 	return (NULL);
21721 }
21722 
21723 static int
21724 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21725 {
21726 	ill_t	*ill;
21727 
21728 	ill = ipif->ipif_ill;
21729 	mutex_enter(&connp->conn_lock);
21730 	mutex_enter(&ill->ill_lock);
21731 	if (IPIF_CAN_LOOKUP(ipif)) {
21732 		*ipifp = ipif;
21733 		mutex_exit(&ill->ill_lock);
21734 		mutex_exit(&connp->conn_lock);
21735 		return (0);
21736 	}
21737 	mutex_exit(&ill->ill_lock);
21738 	mutex_exit(&connp->conn_lock);
21739 	return (IPIF_LOOKUP_FAILED);
21740 }
21741 
21742 /*
21743  * This is called if the outbound datagram needs fragmentation.
21744  *
21745  * NOTE : This function does not ire_refrele the ire argument passed in.
21746  */
21747 static void
21748 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21749     ip_stack_t *ipst, conn_t *connp)
21750 {
21751 	ipha_t		*ipha;
21752 	mblk_t		*mp;
21753 	uint32_t	v_hlen_tos_len;
21754 	uint32_t	max_frag;
21755 	uint32_t	frag_flag;
21756 	boolean_t	dont_use;
21757 
21758 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21759 		mp = ipsec_mp->b_cont;
21760 	} else {
21761 		mp = ipsec_mp;
21762 	}
21763 
21764 	ipha = (ipha_t *)mp->b_rptr;
21765 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21766 
21767 #ifdef	_BIG_ENDIAN
21768 #define	V_HLEN	(v_hlen_tos_len >> 24)
21769 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21770 #else
21771 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21772 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21773 #endif
21774 
21775 #ifndef SPEED_BEFORE_SAFETY
21776 	/*
21777 	 * Check that ipha_length is consistent with
21778 	 * the mblk length
21779 	 */
21780 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21781 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21782 		    LENGTH, msgdsize(mp)));
21783 		freemsg(ipsec_mp);
21784 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21785 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21786 		    "packet length mismatch");
21787 		return;
21788 	}
21789 #endif
21790 	/*
21791 	 * Don't use frag_flag if pre-built packet or source
21792 	 * routed or if multicast (since multicast packets do not solicit
21793 	 * ICMP "packet too big" messages). Get the values of
21794 	 * max_frag and frag_flag atomically by acquiring the
21795 	 * ire_lock.
21796 	 */
21797 	mutex_enter(&ire->ire_lock);
21798 	max_frag = ire->ire_max_frag;
21799 	frag_flag = ire->ire_frag_flag;
21800 	mutex_exit(&ire->ire_lock);
21801 
21802 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21803 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21804 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21805 
21806 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21807 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21808 }
21809 
21810 /*
21811  * Used for deciding the MSS size for the upper layer. Thus
21812  * we need to check the outbound policy values in the conn.
21813  */
21814 int
21815 conn_ipsec_length(conn_t *connp)
21816 {
21817 	ipsec_latch_t *ipl;
21818 
21819 	ipl = connp->conn_latch;
21820 	if (ipl == NULL)
21821 		return (0);
21822 
21823 	if (ipl->ipl_out_policy == NULL)
21824 		return (0);
21825 
21826 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21827 }
21828 
21829 /*
21830  * Returns an estimate of the IPsec headers size. This is used if
21831  * we don't want to call into IPsec to get the exact size.
21832  */
21833 int
21834 ipsec_out_extra_length(mblk_t *ipsec_mp)
21835 {
21836 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21837 	ipsec_action_t *a;
21838 
21839 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21840 	if (!io->ipsec_out_secure)
21841 		return (0);
21842 
21843 	a = io->ipsec_out_act;
21844 
21845 	if (a == NULL) {
21846 		ASSERT(io->ipsec_out_policy != NULL);
21847 		a = io->ipsec_out_policy->ipsp_act;
21848 	}
21849 	ASSERT(a != NULL);
21850 
21851 	return (a->ipa_ovhd);
21852 }
21853 
21854 /*
21855  * Returns an estimate of the IPsec headers size. This is used if
21856  * we don't want to call into IPsec to get the exact size.
21857  */
21858 int
21859 ipsec_in_extra_length(mblk_t *ipsec_mp)
21860 {
21861 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21862 	ipsec_action_t *a;
21863 
21864 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21865 
21866 	a = ii->ipsec_in_action;
21867 	return (a == NULL ? 0 : a->ipa_ovhd);
21868 }
21869 
21870 /*
21871  * If there are any source route options, return the true final
21872  * destination. Otherwise, return the destination.
21873  */
21874 ipaddr_t
21875 ip_get_dst(ipha_t *ipha)
21876 {
21877 	ipoptp_t	opts;
21878 	uchar_t		*opt;
21879 	uint8_t		optval;
21880 	uint8_t		optlen;
21881 	ipaddr_t	dst;
21882 	uint32_t off;
21883 
21884 	dst = ipha->ipha_dst;
21885 
21886 	if (IS_SIMPLE_IPH(ipha))
21887 		return (dst);
21888 
21889 	for (optval = ipoptp_first(&opts, ipha);
21890 	    optval != IPOPT_EOL;
21891 	    optval = ipoptp_next(&opts)) {
21892 		opt = opts.ipoptp_cur;
21893 		optlen = opts.ipoptp_len;
21894 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21895 		switch (optval) {
21896 		case IPOPT_SSRR:
21897 		case IPOPT_LSRR:
21898 			off = opt[IPOPT_OFFSET];
21899 			/*
21900 			 * If one of the conditions is true, it means
21901 			 * end of options and dst already has the right
21902 			 * value.
21903 			 */
21904 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21905 				off = optlen - IP_ADDR_LEN;
21906 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21907 			}
21908 			return (dst);
21909 		default:
21910 			break;
21911 		}
21912 	}
21913 
21914 	return (dst);
21915 }
21916 
21917 mblk_t *
21918 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21919     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21920 {
21921 	ipsec_out_t	*io;
21922 	mblk_t		*first_mp;
21923 	boolean_t policy_present;
21924 	ip_stack_t	*ipst;
21925 	ipsec_stack_t	*ipss;
21926 
21927 	ASSERT(ire != NULL);
21928 	ipst = ire->ire_ipst;
21929 	ipss = ipst->ips_netstack->netstack_ipsec;
21930 
21931 	first_mp = mp;
21932 	if (mp->b_datap->db_type == M_CTL) {
21933 		io = (ipsec_out_t *)first_mp->b_rptr;
21934 		/*
21935 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21936 		 *
21937 		 * 1) There is per-socket policy (including cached global
21938 		 *    policy) or a policy on the IP-in-IP tunnel.
21939 		 * 2) There is no per-socket policy, but it is
21940 		 *    a multicast packet that needs to go out
21941 		 *    on a specific interface. This is the case
21942 		 *    where (ip_wput and ip_wput_multicast) attaches
21943 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21944 		 *
21945 		 * In case (2) we check with global policy to
21946 		 * see if there is a match and set the ill_index
21947 		 * appropriately so that we can lookup the ire
21948 		 * properly in ip_wput_ipsec_out.
21949 		 */
21950 
21951 		/*
21952 		 * ipsec_out_use_global_policy is set to B_FALSE
21953 		 * in ipsec_in_to_out(). Refer to that function for
21954 		 * details.
21955 		 */
21956 		if ((io->ipsec_out_latch == NULL) &&
21957 		    (io->ipsec_out_use_global_policy)) {
21958 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21959 			    ire, connp, unspec_src, zoneid));
21960 		}
21961 		if (!io->ipsec_out_secure) {
21962 			/*
21963 			 * If this is not a secure packet, drop
21964 			 * the IPSEC_OUT mp and treat it as a clear
21965 			 * packet. This happens when we are sending
21966 			 * a ICMP reply back to a clear packet. See
21967 			 * ipsec_in_to_out() for details.
21968 			 */
21969 			mp = first_mp->b_cont;
21970 			freeb(first_mp);
21971 		}
21972 		return (mp);
21973 	}
21974 	/*
21975 	 * See whether we need to attach a global policy here. We
21976 	 * don't depend on the conn (as it could be null) for deciding
21977 	 * what policy this datagram should go through because it
21978 	 * should have happened in ip_wput if there was some
21979 	 * policy. This normally happens for connections which are not
21980 	 * fully bound preventing us from caching policies in
21981 	 * ip_bind. Packets coming from the TCP listener/global queue
21982 	 * - which are non-hard_bound - could also be affected by
21983 	 * applying policy here.
21984 	 *
21985 	 * If this packet is coming from tcp global queue or listener,
21986 	 * we will be applying policy here.  This may not be *right*
21987 	 * if these packets are coming from the detached connection as
21988 	 * it could have gone in clear before. This happens only if a
21989 	 * TCP connection started when there is no policy and somebody
21990 	 * added policy before it became detached. Thus packets of the
21991 	 * detached connection could go out secure and the other end
21992 	 * would drop it because it will be expecting in clear. The
21993 	 * converse is not true i.e if somebody starts a TCP
21994 	 * connection and deletes the policy, all the packets will
21995 	 * still go out with the policy that existed before deleting
21996 	 * because ip_unbind sends up policy information which is used
21997 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21998 	 * TCP to attach a dummy IPSEC_OUT and set
21999 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22000 	 * affect performance for normal cases, we are not doing it.
22001 	 * Thus, set policy before starting any TCP connections.
22002 	 *
22003 	 * NOTE - We might apply policy even for a hard bound connection
22004 	 * - for which we cached policy in ip_bind - if somebody added
22005 	 * global policy after we inherited the policy in ip_bind.
22006 	 * This means that the packets that were going out in clear
22007 	 * previously would start going secure and hence get dropped
22008 	 * on the other side. To fix this, TCP attaches a dummy
22009 	 * ipsec_out and make sure that we don't apply global policy.
22010 	 */
22011 	if (ipha != NULL)
22012 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22013 	else
22014 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22015 	if (!policy_present)
22016 		return (mp);
22017 
22018 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22019 	    zoneid));
22020 }
22021 
22022 /*
22023  * This function does the ire_refrele of the ire passed in as the
22024  * argument. As this function looks up more ires i.e broadcast ires,
22025  * it needs to REFRELE them. Currently, for simplicity we don't
22026  * differentiate the one passed in and looked up here. We always
22027  * REFRELE.
22028  * IPQoS Notes:
22029  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22030  * IPsec packets are done in ipsec_out_process.
22031  */
22032 void
22033 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22034     zoneid_t zoneid)
22035 {
22036 	ipha_t		*ipha;
22037 #define	rptr	((uchar_t *)ipha)
22038 	queue_t		*stq;
22039 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22040 	uint32_t	v_hlen_tos_len;
22041 	uint32_t	ttl_protocol;
22042 	ipaddr_t	src;
22043 	ipaddr_t	dst;
22044 	uint32_t	cksum;
22045 	ipaddr_t	orig_src;
22046 	ire_t		*ire1;
22047 	mblk_t		*next_mp;
22048 	uint_t		hlen;
22049 	uint16_t	*up;
22050 	uint32_t	max_frag = ire->ire_max_frag;
22051 	ill_t		*ill = ire_to_ill(ire);
22052 	int		clusterwide;
22053 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22054 	int		ipsec_len;
22055 	mblk_t		*first_mp;
22056 	ipsec_out_t	*io;
22057 	boolean_t	conn_dontroute;		/* conn value for multicast */
22058 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22059 	boolean_t	multicast_forward;	/* Should we forward ? */
22060 	boolean_t	unspec_src;
22061 	ill_t		*conn_outgoing_ill = NULL;
22062 	ill_t		*ire_ill;
22063 	ill_t		*ire1_ill;
22064 	ill_t		*out_ill;
22065 	uint32_t 	ill_index = 0;
22066 	boolean_t	multirt_send = B_FALSE;
22067 	int		err;
22068 	ipxmit_state_t	pktxmit_state;
22069 	ip_stack_t	*ipst = ire->ire_ipst;
22070 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22071 
22072 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22073 	    "ip_wput_ire_start: q %p", q);
22074 
22075 	multicast_forward = B_FALSE;
22076 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22077 
22078 	if (ire->ire_flags & RTF_MULTIRT) {
22079 		/*
22080 		 * Multirouting case. The bucket where ire is stored
22081 		 * probably holds other RTF_MULTIRT flagged ire
22082 		 * to the destination. In this call to ip_wput_ire,
22083 		 * we attempt to send the packet through all
22084 		 * those ires. Thus, we first ensure that ire is the
22085 		 * first RTF_MULTIRT ire in the bucket,
22086 		 * before walking the ire list.
22087 		 */
22088 		ire_t *first_ire;
22089 		irb_t *irb = ire->ire_bucket;
22090 		ASSERT(irb != NULL);
22091 
22092 		/* Make sure we do not omit any multiroute ire. */
22093 		IRB_REFHOLD(irb);
22094 		for (first_ire = irb->irb_ire;
22095 		    first_ire != NULL;
22096 		    first_ire = first_ire->ire_next) {
22097 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22098 			    (first_ire->ire_addr == ire->ire_addr) &&
22099 			    !(first_ire->ire_marks &
22100 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22101 				break;
22102 		}
22103 
22104 		if ((first_ire != NULL) && (first_ire != ire)) {
22105 			IRE_REFHOLD(first_ire);
22106 			ire_refrele(ire);
22107 			ire = first_ire;
22108 			ill = ire_to_ill(ire);
22109 		}
22110 		IRB_REFRELE(irb);
22111 	}
22112 
22113 	/*
22114 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22115 	 * for performance we don't grab the mutexs in the fastpath
22116 	 */
22117 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22118 	    connp->conn_outgoing_ill != NULL) {
22119 		conn_outgoing_ill = conn_get_held_ill(connp,
22120 		    &connp->conn_outgoing_ill, &err);
22121 		if (err == ILL_LOOKUP_FAILED) {
22122 			ire_refrele(ire);
22123 			freemsg(mp);
22124 			return;
22125 		}
22126 	}
22127 
22128 	if (mp->b_datap->db_type != M_CTL) {
22129 		ipha = (ipha_t *)mp->b_rptr;
22130 	} else {
22131 		io = (ipsec_out_t *)mp->b_rptr;
22132 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22133 		ASSERT(zoneid == io->ipsec_out_zoneid);
22134 		ASSERT(zoneid != ALL_ZONES);
22135 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22136 		dst = ipha->ipha_dst;
22137 		/*
22138 		 * For the multicast case, ipsec_out carries conn_dontroute and
22139 		 * conn_multicast_loop as conn may not be available here. We
22140 		 * need this for multicast loopback and forwarding which is done
22141 		 * later in the code.
22142 		 */
22143 		if (CLASSD(dst)) {
22144 			conn_dontroute = io->ipsec_out_dontroute;
22145 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22146 			/*
22147 			 * If conn_dontroute is not set or conn_multicast_loop
22148 			 * is set, we need to do forwarding/loopback. For
22149 			 * datagrams from ip_wput_multicast, conn_dontroute is
22150 			 * set to B_TRUE and conn_multicast_loop is set to
22151 			 * B_FALSE so that we neither do forwarding nor
22152 			 * loopback.
22153 			 */
22154 			if (!conn_dontroute || conn_multicast_loop)
22155 				multicast_forward = B_TRUE;
22156 		}
22157 	}
22158 
22159 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22160 	    ire->ire_zoneid != ALL_ZONES) {
22161 		/*
22162 		 * When a zone sends a packet to another zone, we try to deliver
22163 		 * the packet under the same conditions as if the destination
22164 		 * was a real node on the network. To do so, we look for a
22165 		 * matching route in the forwarding table.
22166 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22167 		 * ip_newroute() does.
22168 		 * Note that IRE_LOCAL are special, since they are used
22169 		 * when the zoneid doesn't match in some cases. This means that
22170 		 * we need to handle ipha_src differently since ire_src_addr
22171 		 * belongs to the receiving zone instead of the sending zone.
22172 		 * When ip_restrict_interzone_loopback is set, then
22173 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22174 		 * for loopback between zones when the logical "Ethernet" would
22175 		 * have looped them back.
22176 		 */
22177 		ire_t *src_ire;
22178 
22179 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22180 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22181 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22182 		if (src_ire != NULL &&
22183 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22184 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22185 		    ire_local_same_lan(ire, src_ire))) {
22186 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22187 				ipha->ipha_src = src_ire->ire_src_addr;
22188 			ire_refrele(src_ire);
22189 		} else {
22190 			ire_refrele(ire);
22191 			if (conn_outgoing_ill != NULL)
22192 				ill_refrele(conn_outgoing_ill);
22193 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22194 			if (src_ire != NULL) {
22195 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22196 					ire_refrele(src_ire);
22197 					freemsg(mp);
22198 					return;
22199 				}
22200 				ire_refrele(src_ire);
22201 			}
22202 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22203 				/* Failed */
22204 				freemsg(mp);
22205 				return;
22206 			}
22207 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22208 			    ipst);
22209 			return;
22210 		}
22211 	}
22212 
22213 	if (mp->b_datap->db_type == M_CTL ||
22214 	    ipss->ipsec_outbound_v4_policy_present) {
22215 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22216 		    unspec_src, zoneid);
22217 		if (mp == NULL) {
22218 			ire_refrele(ire);
22219 			if (conn_outgoing_ill != NULL)
22220 				ill_refrele(conn_outgoing_ill);
22221 			return;
22222 		}
22223 		/*
22224 		 * Trusted Extensions supports all-zones interfaces, so
22225 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22226 		 * the global zone.
22227 		 */
22228 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22229 			io = (ipsec_out_t *)mp->b_rptr;
22230 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22231 			zoneid = io->ipsec_out_zoneid;
22232 		}
22233 	}
22234 
22235 	first_mp = mp;
22236 	ipsec_len = 0;
22237 
22238 	if (first_mp->b_datap->db_type == M_CTL) {
22239 		io = (ipsec_out_t *)first_mp->b_rptr;
22240 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22241 		mp = first_mp->b_cont;
22242 		ipsec_len = ipsec_out_extra_length(first_mp);
22243 		ASSERT(ipsec_len >= 0);
22244 		if (zoneid == ALL_ZONES)
22245 			zoneid = GLOBAL_ZONEID;
22246 		/* We already picked up the zoneid from the M_CTL above */
22247 		ASSERT(zoneid == io->ipsec_out_zoneid);
22248 
22249 		/*
22250 		 * Drop M_CTL here if IPsec processing is not needed.
22251 		 * (Non-IPsec use of M_CTL extracted any information it
22252 		 * needed above).
22253 		 */
22254 		if (ipsec_len == 0) {
22255 			freeb(first_mp);
22256 			first_mp = mp;
22257 		}
22258 	}
22259 
22260 	/*
22261 	 * Fast path for ip_wput_ire
22262 	 */
22263 
22264 	ipha = (ipha_t *)mp->b_rptr;
22265 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22266 	dst = ipha->ipha_dst;
22267 
22268 	/*
22269 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22270 	 * if the socket is a SOCK_RAW type. The transport checksum should
22271 	 * be provided in the pre-built packet, so we don't need to compute it.
22272 	 * Also, other application set flags, like DF, should not be altered.
22273 	 * Other transport MUST pass down zero.
22274 	 */
22275 	ip_hdr_included = ipha->ipha_ident;
22276 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22277 
22278 	if (CLASSD(dst)) {
22279 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22280 		    ntohl(dst),
22281 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22282 		    ntohl(ire->ire_addr)));
22283 	}
22284 
22285 /* Macros to extract header fields from data already in registers */
22286 #ifdef	_BIG_ENDIAN
22287 #define	V_HLEN	(v_hlen_tos_len >> 24)
22288 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22289 #define	PROTO	(ttl_protocol & 0xFF)
22290 #else
22291 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22292 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22293 #define	PROTO	(ttl_protocol >> 8)
22294 #endif
22295 
22296 	orig_src = src = ipha->ipha_src;
22297 	/* (The loop back to "another" is explained down below.) */
22298 another:;
22299 	/*
22300 	 * Assign an ident value for this packet.  We assign idents on
22301 	 * a per destination basis out of the IRE.  There could be
22302 	 * other threads targeting the same destination, so we have to
22303 	 * arrange for a atomic increment.  Note that we use a 32-bit
22304 	 * atomic add because it has better performance than its
22305 	 * 16-bit sibling.
22306 	 *
22307 	 * If running in cluster mode and if the source address
22308 	 * belongs to a replicated service then vector through
22309 	 * cl_inet_ipident vector to allocate ip identifier
22310 	 * NOTE: This is a contract private interface with the
22311 	 * clustering group.
22312 	 */
22313 	clusterwide = 0;
22314 	if (cl_inet_ipident) {
22315 		ASSERT(cl_inet_isclusterwide);
22316 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22317 
22318 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22319 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22320 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22321 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22322 			    (uint8_t *)(uintptr_t)dst, NULL);
22323 			clusterwide = 1;
22324 		}
22325 	}
22326 	if (!clusterwide) {
22327 		ipha->ipha_ident =
22328 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22329 	}
22330 
22331 #ifndef _BIG_ENDIAN
22332 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22333 #endif
22334 
22335 	/*
22336 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22337 	 * This is needed to obey conn_unspec_src when packets go through
22338 	 * ip_newroute + arp.
22339 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22340 	 */
22341 	if (src == INADDR_ANY && !unspec_src) {
22342 		/*
22343 		 * Assign the appropriate source address from the IRE if none
22344 		 * was specified.
22345 		 */
22346 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22347 
22348 		src = ire->ire_src_addr;
22349 		if (connp == NULL) {
22350 			ip1dbg(("ip_wput_ire: no connp and no src "
22351 			    "address for dst 0x%x, using src 0x%x\n",
22352 			    ntohl(dst),
22353 			    ntohl(src)));
22354 		}
22355 		ipha->ipha_src = src;
22356 	}
22357 	stq = ire->ire_stq;
22358 
22359 	/*
22360 	 * We only allow ire chains for broadcasts since there will
22361 	 * be multiple IRE_CACHE entries for the same multicast
22362 	 * address (one per ipif).
22363 	 */
22364 	next_mp = NULL;
22365 
22366 	/* broadcast packet */
22367 	if (ire->ire_type == IRE_BROADCAST)
22368 		goto broadcast;
22369 
22370 	/* loopback ? */
22371 	if (stq == NULL)
22372 		goto nullstq;
22373 
22374 	/* The ill_index for outbound ILL */
22375 	ill_index = Q_TO_INDEX(stq);
22376 
22377 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22378 	ttl_protocol = ((uint16_t *)ipha)[4];
22379 
22380 	/* pseudo checksum (do it in parts for IP header checksum) */
22381 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22382 
22383 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22384 		queue_t *dev_q = stq->q_next;
22385 
22386 		/*
22387 		 * For DIRECT_CAPABLE, we do flow control at
22388 		 * the time of sending the packet. See
22389 		 * ILL_SEND_TX().
22390 		 */
22391 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22392 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22393 			goto blocked;
22394 
22395 		if ((PROTO == IPPROTO_UDP) &&
22396 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22397 			hlen = (V_HLEN & 0xF) << 2;
22398 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22399 			if (*up != 0) {
22400 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22401 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22402 				/* Software checksum? */
22403 				if (DB_CKSUMFLAGS(mp) == 0) {
22404 					IP_STAT(ipst, ip_out_sw_cksum);
22405 					IP_STAT_UPDATE(ipst,
22406 					    ip_udp_out_sw_cksum_bytes,
22407 					    LENGTH - hlen);
22408 				}
22409 			}
22410 		}
22411 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22412 		hlen = (V_HLEN & 0xF) << 2;
22413 		if (PROTO == IPPROTO_TCP) {
22414 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22415 			/*
22416 			 * The packet header is processed once and for all, even
22417 			 * in the multirouting case. We disable hardware
22418 			 * checksum if the packet is multirouted, as it will be
22419 			 * replicated via several interfaces, and not all of
22420 			 * them may have this capability.
22421 			 */
22422 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22423 			    LENGTH, max_frag, ipsec_len, cksum);
22424 			/* Software checksum? */
22425 			if (DB_CKSUMFLAGS(mp) == 0) {
22426 				IP_STAT(ipst, ip_out_sw_cksum);
22427 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22428 				    LENGTH - hlen);
22429 			}
22430 		} else {
22431 			sctp_hdr_t	*sctph;
22432 
22433 			ASSERT(PROTO == IPPROTO_SCTP);
22434 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22435 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22436 			/*
22437 			 * Zero out the checksum field to ensure proper
22438 			 * checksum calculation.
22439 			 */
22440 			sctph->sh_chksum = 0;
22441 #ifdef	DEBUG
22442 			if (!skip_sctp_cksum)
22443 #endif
22444 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22445 		}
22446 	}
22447 
22448 	/*
22449 	 * If this is a multicast packet and originated from ip_wput
22450 	 * we need to do loopback and forwarding checks. If it comes
22451 	 * from ip_wput_multicast, we SHOULD not do this.
22452 	 */
22453 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22454 
22455 	/* checksum */
22456 	cksum += ttl_protocol;
22457 
22458 	/* fragment the packet */
22459 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22460 		goto fragmentit;
22461 	/*
22462 	 * Don't use frag_flag if packet is pre-built or source
22463 	 * routed or if multicast (since multicast packets do
22464 	 * not solicit ICMP "packet too big" messages).
22465 	 */
22466 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22467 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22468 	    !ip_source_route_included(ipha)) &&
22469 	    !CLASSD(ipha->ipha_dst))
22470 		ipha->ipha_fragment_offset_and_flags |=
22471 		    htons(ire->ire_frag_flag);
22472 
22473 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22474 		/* calculate IP header checksum */
22475 		cksum += ipha->ipha_ident;
22476 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22477 		cksum += ipha->ipha_fragment_offset_and_flags;
22478 
22479 		/* IP options present */
22480 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22481 		if (hlen)
22482 			goto checksumoptions;
22483 
22484 		/* calculate hdr checksum */
22485 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22486 		cksum = ~(cksum + (cksum >> 16));
22487 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22488 	}
22489 	if (ipsec_len != 0) {
22490 		/*
22491 		 * We will do the rest of the processing after
22492 		 * we come back from IPsec in ip_wput_ipsec_out().
22493 		 */
22494 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22495 
22496 		io = (ipsec_out_t *)first_mp->b_rptr;
22497 		io->ipsec_out_ill_index =
22498 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22499 		ipsec_out_process(q, first_mp, ire, 0);
22500 		ire_refrele(ire);
22501 		if (conn_outgoing_ill != NULL)
22502 			ill_refrele(conn_outgoing_ill);
22503 		return;
22504 	}
22505 
22506 	/*
22507 	 * In most cases, the emission loop below is entered only
22508 	 * once. Only in the case where the ire holds the
22509 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22510 	 * flagged ires in the bucket, and send the packet
22511 	 * through all crossed RTF_MULTIRT routes.
22512 	 */
22513 	if (ire->ire_flags & RTF_MULTIRT) {
22514 		multirt_send = B_TRUE;
22515 	}
22516 	do {
22517 		if (multirt_send) {
22518 			irb_t *irb;
22519 			/*
22520 			 * We are in a multiple send case, need to get
22521 			 * the next ire and make a duplicate of the packet.
22522 			 * ire1 holds here the next ire to process in the
22523 			 * bucket. If multirouting is expected,
22524 			 * any non-RTF_MULTIRT ire that has the
22525 			 * right destination address is ignored.
22526 			 */
22527 			irb = ire->ire_bucket;
22528 			ASSERT(irb != NULL);
22529 
22530 			IRB_REFHOLD(irb);
22531 			for (ire1 = ire->ire_next;
22532 			    ire1 != NULL;
22533 			    ire1 = ire1->ire_next) {
22534 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22535 					continue;
22536 				if (ire1->ire_addr != ire->ire_addr)
22537 					continue;
22538 				if (ire1->ire_marks &
22539 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22540 					continue;
22541 
22542 				/* Got one */
22543 				IRE_REFHOLD(ire1);
22544 				break;
22545 			}
22546 			IRB_REFRELE(irb);
22547 
22548 			if (ire1 != NULL) {
22549 				next_mp = copyb(mp);
22550 				if ((next_mp == NULL) ||
22551 				    ((mp->b_cont != NULL) &&
22552 				    ((next_mp->b_cont =
22553 				    dupmsg(mp->b_cont)) == NULL))) {
22554 					freemsg(next_mp);
22555 					next_mp = NULL;
22556 					ire_refrele(ire1);
22557 					ire1 = NULL;
22558 				}
22559 			}
22560 
22561 			/* Last multiroute ire; don't loop anymore. */
22562 			if (ire1 == NULL) {
22563 				multirt_send = B_FALSE;
22564 			}
22565 		}
22566 
22567 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22568 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22569 		    mblk_t *, mp);
22570 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22571 		    ipst->ips_ipv4firewall_physical_out,
22572 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22573 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22574 
22575 		if (mp == NULL)
22576 			goto release_ire_and_ill;
22577 
22578 		if (ipst->ips_ip4_observe.he_interested) {
22579 			zoneid_t szone;
22580 
22581 			/*
22582 			 * On the outbound path the destination zone will be
22583 			 * unknown as we're sending this packet out on the
22584 			 * wire.
22585 			 */
22586 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22587 			    ALL_ZONES);
22588 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22589 			    ire->ire_ipif->ipif_ill, ipst);
22590 		}
22591 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22592 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22593 
22594 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22595 
22596 		if ((pktxmit_state == SEND_FAILED) ||
22597 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22598 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22599 			    "- packet dropped\n"));
22600 release_ire_and_ill:
22601 			ire_refrele(ire);
22602 			if (next_mp != NULL) {
22603 				freemsg(next_mp);
22604 				ire_refrele(ire1);
22605 			}
22606 			if (conn_outgoing_ill != NULL)
22607 				ill_refrele(conn_outgoing_ill);
22608 			return;
22609 		}
22610 
22611 		if (CLASSD(dst)) {
22612 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22613 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22614 			    LENGTH);
22615 		}
22616 
22617 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22618 		    "ip_wput_ire_end: q %p (%S)",
22619 		    q, "last copy out");
22620 		IRE_REFRELE(ire);
22621 
22622 		if (multirt_send) {
22623 			ASSERT(ire1);
22624 			/*
22625 			 * Proceed with the next RTF_MULTIRT ire,
22626 			 * Also set up the send-to queue accordingly.
22627 			 */
22628 			ire = ire1;
22629 			ire1 = NULL;
22630 			stq = ire->ire_stq;
22631 			mp = next_mp;
22632 			next_mp = NULL;
22633 			ipha = (ipha_t *)mp->b_rptr;
22634 			ill_index = Q_TO_INDEX(stq);
22635 			ill = (ill_t *)stq->q_ptr;
22636 		}
22637 	} while (multirt_send);
22638 	if (conn_outgoing_ill != NULL)
22639 		ill_refrele(conn_outgoing_ill);
22640 	return;
22641 
22642 	/*
22643 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22644 	 */
22645 broadcast:
22646 	{
22647 		/*
22648 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22649 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22650 		 * can be overridden stack-wide through the ip_broadcast_ttl
22651 		 * ndd tunable, or on a per-connection basis through the
22652 		 * IP_BROADCAST_TTL socket option.
22653 		 *
22654 		 * In the event that we are replying to incoming ICMP packets,
22655 		 * connp could be NULL.
22656 		 */
22657 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22658 		if (connp != NULL) {
22659 			if (connp->conn_dontroute)
22660 				ipha->ipha_ttl = 1;
22661 			else if (connp->conn_broadcast_ttl != 0)
22662 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22663 		}
22664 
22665 		/*
22666 		 * Note that we are not doing a IRB_REFHOLD here.
22667 		 * Actually we don't care if the list changes i.e
22668 		 * if somebody deletes an IRE from the list while
22669 		 * we drop the lock, the next time we come around
22670 		 * ire_next will be NULL and hence we won't send
22671 		 * out multiple copies which is fine.
22672 		 */
22673 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22674 		ire1 = ire->ire_next;
22675 		if (conn_outgoing_ill != NULL) {
22676 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22677 				ASSERT(ire1 == ire->ire_next);
22678 				if (ire1 != NULL && ire1->ire_addr == dst) {
22679 					ire_refrele(ire);
22680 					ire = ire1;
22681 					IRE_REFHOLD(ire);
22682 					ire1 = ire->ire_next;
22683 					continue;
22684 				}
22685 				rw_exit(&ire->ire_bucket->irb_lock);
22686 				/* Did not find a matching ill */
22687 				ip1dbg(("ip_wput_ire: broadcast with no "
22688 				    "matching IP_BOUND_IF ill %s dst %x\n",
22689 				    conn_outgoing_ill->ill_name, dst));
22690 				freemsg(first_mp);
22691 				if (ire != NULL)
22692 					ire_refrele(ire);
22693 				ill_refrele(conn_outgoing_ill);
22694 				return;
22695 			}
22696 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22697 			/*
22698 			 * If the next IRE has the same address and is not one
22699 			 * of the two copies that we need to send, try to see
22700 			 * whether this copy should be sent at all. This
22701 			 * assumes that we insert loopbacks first and then
22702 			 * non-loopbacks. This is acheived by inserting the
22703 			 * loopback always before non-loopback.
22704 			 * This is used to send a single copy of a broadcast
22705 			 * packet out all physical interfaces that have an
22706 			 * matching IRE_BROADCAST while also looping
22707 			 * back one copy (to ip_wput_local) for each
22708 			 * matching physical interface. However, we avoid
22709 			 * sending packets out different logical that match by
22710 			 * having ipif_up/ipif_down supress duplicate
22711 			 * IRE_BROADCASTS.
22712 			 *
22713 			 * This feature is currently used to get broadcasts
22714 			 * sent to multiple interfaces, when the broadcast
22715 			 * address being used applies to multiple interfaces.
22716 			 * For example, a whole net broadcast will be
22717 			 * replicated on every connected subnet of
22718 			 * the target net.
22719 			 *
22720 			 * Each zone has its own set of IRE_BROADCASTs, so that
22721 			 * we're able to distribute inbound packets to multiple
22722 			 * zones who share a broadcast address. We avoid looping
22723 			 * back outbound packets in different zones but on the
22724 			 * same ill, as the application would see duplicates.
22725 			 *
22726 			 * This logic assumes that ire_add_v4() groups the
22727 			 * IRE_BROADCAST entries so that those with the same
22728 			 * ire_addr are kept together.
22729 			 */
22730 			ire_ill = ire->ire_ipif->ipif_ill;
22731 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22732 				while (ire1 != NULL && ire1->ire_addr == dst) {
22733 					ire1_ill = ire1->ire_ipif->ipif_ill;
22734 					if (ire1_ill != ire_ill)
22735 						break;
22736 					ire1 = ire1->ire_next;
22737 				}
22738 			}
22739 		}
22740 		ASSERT(multirt_send == B_FALSE);
22741 		if (ire1 != NULL && ire1->ire_addr == dst) {
22742 			if ((ire->ire_flags & RTF_MULTIRT) &&
22743 			    (ire1->ire_flags & RTF_MULTIRT)) {
22744 				/*
22745 				 * We are in the multirouting case.
22746 				 * The message must be sent at least
22747 				 * on both ires. These ires have been
22748 				 * inserted AFTER the standard ones
22749 				 * in ip_rt_add(). There are thus no
22750 				 * other ire entries for the destination
22751 				 * address in the rest of the bucket
22752 				 * that do not have the RTF_MULTIRT
22753 				 * flag. We don't process a copy
22754 				 * of the message here. This will be
22755 				 * done in the final sending loop.
22756 				 */
22757 				multirt_send = B_TRUE;
22758 			} else {
22759 				next_mp = ip_copymsg(first_mp);
22760 				if (next_mp != NULL)
22761 					IRE_REFHOLD(ire1);
22762 			}
22763 		}
22764 		rw_exit(&ire->ire_bucket->irb_lock);
22765 	}
22766 
22767 	if (stq) {
22768 		/*
22769 		 * A non-NULL send-to queue means this packet is going
22770 		 * out of this machine.
22771 		 */
22772 		out_ill = (ill_t *)stq->q_ptr;
22773 
22774 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22775 		ttl_protocol = ((uint16_t *)ipha)[4];
22776 		/*
22777 		 * We accumulate the pseudo header checksum in cksum.
22778 		 * This is pretty hairy code, so watch close.  One
22779 		 * thing to keep in mind is that UDP and TCP have
22780 		 * stored their respective datagram lengths in their
22781 		 * checksum fields.  This lines things up real nice.
22782 		 */
22783 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22784 		    (src >> 16) + (src & 0xFFFF);
22785 		/*
22786 		 * We assume the udp checksum field contains the
22787 		 * length, so to compute the pseudo header checksum,
22788 		 * all we need is the protocol number and src/dst.
22789 		 */
22790 		/* Provide the checksums for UDP and TCP. */
22791 		if ((PROTO == IPPROTO_TCP) &&
22792 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22793 			/* hlen gets the number of uchar_ts in the IP header */
22794 			hlen = (V_HLEN & 0xF) << 2;
22795 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22796 			IP_STAT(ipst, ip_out_sw_cksum);
22797 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22798 			    LENGTH - hlen);
22799 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22800 		} else if (PROTO == IPPROTO_SCTP &&
22801 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22802 			sctp_hdr_t	*sctph;
22803 
22804 			hlen = (V_HLEN & 0xF) << 2;
22805 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22806 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22807 			sctph->sh_chksum = 0;
22808 #ifdef	DEBUG
22809 			if (!skip_sctp_cksum)
22810 #endif
22811 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22812 		} else {
22813 			queue_t	*dev_q = stq->q_next;
22814 
22815 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22816 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22817 blocked:
22818 				ipha->ipha_ident = ip_hdr_included;
22819 				/*
22820 				 * If we don't have a conn to apply
22821 				 * backpressure, free the message.
22822 				 * In the ire_send path, we don't know
22823 				 * the position to requeue the packet. Rather
22824 				 * than reorder packets, we just drop this
22825 				 * packet.
22826 				 */
22827 				if (ipst->ips_ip_output_queue &&
22828 				    connp != NULL &&
22829 				    caller != IRE_SEND) {
22830 					if (caller == IP_WSRV) {
22831 						idl_tx_list_t *idl_txl;
22832 
22833 						idl_txl =
22834 						    &ipst->ips_idl_tx_list[0];
22835 						connp->conn_did_putbq = 1;
22836 						(void) putbq(connp->conn_wq,
22837 						    first_mp);
22838 						conn_drain_insert(connp,
22839 						    idl_txl);
22840 						/*
22841 						 * This is the service thread,
22842 						 * and the queue is already
22843 						 * noenabled. The check for
22844 						 * canput and the putbq is not
22845 						 * atomic. So we need to check
22846 						 * again.
22847 						 */
22848 						if (canput(stq->q_next))
22849 							connp->conn_did_putbq
22850 							    = 0;
22851 						IP_STAT(ipst, ip_conn_flputbq);
22852 					} else {
22853 						/*
22854 						 * We are not the service proc.
22855 						 * ip_wsrv will be scheduled or
22856 						 * is already running.
22857 						 */
22858 
22859 						(void) putq(connp->conn_wq,
22860 						    first_mp);
22861 					}
22862 				} else {
22863 					out_ill = (ill_t *)stq->q_ptr;
22864 					BUMP_MIB(out_ill->ill_ip_mib,
22865 					    ipIfStatsOutDiscards);
22866 					freemsg(first_mp);
22867 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22868 					    "ip_wput_ire_end: q %p (%S)",
22869 					    q, "discard");
22870 				}
22871 				ire_refrele(ire);
22872 				if (next_mp) {
22873 					ire_refrele(ire1);
22874 					freemsg(next_mp);
22875 				}
22876 				if (conn_outgoing_ill != NULL)
22877 					ill_refrele(conn_outgoing_ill);
22878 				return;
22879 			}
22880 			if ((PROTO == IPPROTO_UDP) &&
22881 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22882 				/*
22883 				 * hlen gets the number of uchar_ts in the
22884 				 * IP header
22885 				 */
22886 				hlen = (V_HLEN & 0xF) << 2;
22887 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22888 				max_frag = ire->ire_max_frag;
22889 				if (*up != 0) {
22890 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22891 					    up, PROTO, hlen, LENGTH, max_frag,
22892 					    ipsec_len, cksum);
22893 					/* Software checksum? */
22894 					if (DB_CKSUMFLAGS(mp) == 0) {
22895 						IP_STAT(ipst, ip_out_sw_cksum);
22896 						IP_STAT_UPDATE(ipst,
22897 						    ip_udp_out_sw_cksum_bytes,
22898 						    LENGTH - hlen);
22899 					}
22900 				}
22901 			}
22902 		}
22903 		/*
22904 		 * Need to do this even when fragmenting. The local
22905 		 * loopback can be done without computing checksums
22906 		 * but forwarding out other interface must be done
22907 		 * after the IP checksum (and ULP checksums) have been
22908 		 * computed.
22909 		 *
22910 		 * NOTE : multicast_forward is set only if this packet
22911 		 * originated from ip_wput. For packets originating from
22912 		 * ip_wput_multicast, it is not set.
22913 		 */
22914 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22915 multi_loopback:
22916 			ip2dbg(("ip_wput: multicast, loop %d\n",
22917 			    conn_multicast_loop));
22918 
22919 			/*  Forget header checksum offload */
22920 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22921 
22922 			/*
22923 			 * Local loopback of multicasts?  Check the
22924 			 * ill.
22925 			 *
22926 			 * Note that the loopback function will not come
22927 			 * in through ip_rput - it will only do the
22928 			 * client fanout thus we need to do an mforward
22929 			 * as well.  The is different from the BSD
22930 			 * logic.
22931 			 */
22932 			if (ill != NULL) {
22933 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22934 				    ALL_ZONES) != NULL) {
22935 					/*
22936 					 * Pass along the virtual output q.
22937 					 * ip_wput_local() will distribute the
22938 					 * packet to all the matching zones,
22939 					 * except the sending zone when
22940 					 * IP_MULTICAST_LOOP is false.
22941 					 */
22942 					ip_multicast_loopback(q, ill, first_mp,
22943 					    conn_multicast_loop ? 0 :
22944 					    IP_FF_NO_MCAST_LOOP, zoneid);
22945 				}
22946 			}
22947 			if (ipha->ipha_ttl == 0) {
22948 				/*
22949 				 * 0 => only to this host i.e. we are
22950 				 * done. We are also done if this was the
22951 				 * loopback interface since it is sufficient
22952 				 * to loopback one copy of a multicast packet.
22953 				 */
22954 				freemsg(first_mp);
22955 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22956 				    "ip_wput_ire_end: q %p (%S)",
22957 				    q, "loopback");
22958 				ire_refrele(ire);
22959 				if (conn_outgoing_ill != NULL)
22960 					ill_refrele(conn_outgoing_ill);
22961 				return;
22962 			}
22963 			/*
22964 			 * ILLF_MULTICAST is checked in ip_newroute
22965 			 * i.e. we don't need to check it here since
22966 			 * all IRE_CACHEs come from ip_newroute.
22967 			 * For multicast traffic, SO_DONTROUTE is interpreted
22968 			 * to mean only send the packet out the interface
22969 			 * (optionally specified with IP_MULTICAST_IF)
22970 			 * and do not forward it out additional interfaces.
22971 			 * RSVP and the rsvp daemon is an example of a
22972 			 * protocol and user level process that
22973 			 * handles it's own routing. Hence, it uses the
22974 			 * SO_DONTROUTE option to accomplish this.
22975 			 */
22976 
22977 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22978 			    ill != NULL) {
22979 				/* Unconditionally redo the checksum */
22980 				ipha->ipha_hdr_checksum = 0;
22981 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22982 
22983 				/*
22984 				 * If this needs to go out secure, we need
22985 				 * to wait till we finish the IPsec
22986 				 * processing.
22987 				 */
22988 				if (ipsec_len == 0 &&
22989 				    ip_mforward(ill, ipha, mp)) {
22990 					freemsg(first_mp);
22991 					ip1dbg(("ip_wput: mforward failed\n"));
22992 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22993 					    "ip_wput_ire_end: q %p (%S)",
22994 					    q, "mforward failed");
22995 					ire_refrele(ire);
22996 					if (conn_outgoing_ill != NULL)
22997 						ill_refrele(conn_outgoing_ill);
22998 					return;
22999 				}
23000 			}
23001 		}
23002 		max_frag = ire->ire_max_frag;
23003 		cksum += ttl_protocol;
23004 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23005 			/* No fragmentation required for this one. */
23006 			/*
23007 			 * Don't use frag_flag if packet is pre-built or source
23008 			 * routed or if multicast (since multicast packets do
23009 			 * not solicit ICMP "packet too big" messages).
23010 			 */
23011 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23012 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23013 			    !ip_source_route_included(ipha)) &&
23014 			    !CLASSD(ipha->ipha_dst))
23015 				ipha->ipha_fragment_offset_and_flags |=
23016 				    htons(ire->ire_frag_flag);
23017 
23018 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23019 				/* Complete the IP header checksum. */
23020 				cksum += ipha->ipha_ident;
23021 				cksum += (v_hlen_tos_len >> 16)+
23022 				    (v_hlen_tos_len & 0xFFFF);
23023 				cksum += ipha->ipha_fragment_offset_and_flags;
23024 				hlen = (V_HLEN & 0xF) -
23025 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23026 				if (hlen) {
23027 checksumoptions:
23028 					/*
23029 					 * Account for the IP Options in the IP
23030 					 * header checksum.
23031 					 */
23032 					up = (uint16_t *)(rptr+
23033 					    IP_SIMPLE_HDR_LENGTH);
23034 					do {
23035 						cksum += up[0];
23036 						cksum += up[1];
23037 						up += 2;
23038 					} while (--hlen);
23039 				}
23040 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23041 				cksum = ~(cksum + (cksum >> 16));
23042 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23043 			}
23044 			if (ipsec_len != 0) {
23045 				ipsec_out_process(q, first_mp, ire, ill_index);
23046 				if (!next_mp) {
23047 					ire_refrele(ire);
23048 					if (conn_outgoing_ill != NULL)
23049 						ill_refrele(conn_outgoing_ill);
23050 					return;
23051 				}
23052 				goto next;
23053 			}
23054 
23055 			/*
23056 			 * multirt_send has already been handled
23057 			 * for broadcast, but not yet for multicast
23058 			 * or IP options.
23059 			 */
23060 			if (next_mp == NULL) {
23061 				if (ire->ire_flags & RTF_MULTIRT) {
23062 					multirt_send = B_TRUE;
23063 				}
23064 			}
23065 
23066 			/*
23067 			 * In most cases, the emission loop below is
23068 			 * entered only once. Only in the case where
23069 			 * the ire holds the RTF_MULTIRT flag, do we loop
23070 			 * to process all RTF_MULTIRT ires in the bucket,
23071 			 * and send the packet through all crossed
23072 			 * RTF_MULTIRT routes.
23073 			 */
23074 			do {
23075 				if (multirt_send) {
23076 					irb_t *irb;
23077 
23078 					irb = ire->ire_bucket;
23079 					ASSERT(irb != NULL);
23080 					/*
23081 					 * We are in a multiple send case,
23082 					 * need to get the next IRE and make
23083 					 * a duplicate of the packet.
23084 					 */
23085 					IRB_REFHOLD(irb);
23086 					for (ire1 = ire->ire_next;
23087 					    ire1 != NULL;
23088 					    ire1 = ire1->ire_next) {
23089 						if (!(ire1->ire_flags &
23090 						    RTF_MULTIRT))
23091 							continue;
23092 
23093 						if (ire1->ire_addr !=
23094 						    ire->ire_addr)
23095 							continue;
23096 
23097 						if (ire1->ire_marks &
23098 						    (IRE_MARK_CONDEMNED |
23099 						    IRE_MARK_TESTHIDDEN))
23100 							continue;
23101 
23102 						/* Got one */
23103 						IRE_REFHOLD(ire1);
23104 						break;
23105 					}
23106 					IRB_REFRELE(irb);
23107 
23108 					if (ire1 != NULL) {
23109 						next_mp = copyb(mp);
23110 						if ((next_mp == NULL) ||
23111 						    ((mp->b_cont != NULL) &&
23112 						    ((next_mp->b_cont =
23113 						    dupmsg(mp->b_cont))
23114 						    == NULL))) {
23115 							freemsg(next_mp);
23116 							next_mp = NULL;
23117 							ire_refrele(ire1);
23118 							ire1 = NULL;
23119 						}
23120 					}
23121 
23122 					/*
23123 					 * Last multiroute ire; don't loop
23124 					 * anymore. The emission is over
23125 					 * and next_mp is NULL.
23126 					 */
23127 					if (ire1 == NULL) {
23128 						multirt_send = B_FALSE;
23129 					}
23130 				}
23131 
23132 				out_ill = ire_to_ill(ire);
23133 				DTRACE_PROBE4(ip4__physical__out__start,
23134 				    ill_t *, NULL,
23135 				    ill_t *, out_ill,
23136 				    ipha_t *, ipha, mblk_t *, mp);
23137 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23138 				    ipst->ips_ipv4firewall_physical_out,
23139 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23140 				DTRACE_PROBE1(ip4__physical__out__end,
23141 				    mblk_t *, mp);
23142 				if (mp == NULL)
23143 					goto release_ire_and_ill_2;
23144 
23145 				ASSERT(ipsec_len == 0);
23146 				mp->b_prev =
23147 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23148 				DTRACE_PROBE2(ip__xmit__2,
23149 				    mblk_t *, mp, ire_t *, ire);
23150 				pktxmit_state = ip_xmit_v4(mp, ire,
23151 				    NULL, B_TRUE, connp);
23152 				if ((pktxmit_state == SEND_FAILED) ||
23153 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23154 release_ire_and_ill_2:
23155 					if (next_mp) {
23156 						freemsg(next_mp);
23157 						ire_refrele(ire1);
23158 					}
23159 					ire_refrele(ire);
23160 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23161 					    "ip_wput_ire_end: q %p (%S)",
23162 					    q, "discard MDATA");
23163 					if (conn_outgoing_ill != NULL)
23164 						ill_refrele(conn_outgoing_ill);
23165 					return;
23166 				}
23167 
23168 				if (CLASSD(dst)) {
23169 					BUMP_MIB(out_ill->ill_ip_mib,
23170 					    ipIfStatsHCOutMcastPkts);
23171 					UPDATE_MIB(out_ill->ill_ip_mib,
23172 					    ipIfStatsHCOutMcastOctets,
23173 					    LENGTH);
23174 				} else if (ire->ire_type == IRE_BROADCAST) {
23175 					BUMP_MIB(out_ill->ill_ip_mib,
23176 					    ipIfStatsHCOutBcastPkts);
23177 				}
23178 
23179 				if (multirt_send) {
23180 					/*
23181 					 * We are in a multiple send case,
23182 					 * need to re-enter the sending loop
23183 					 * using the next ire.
23184 					 */
23185 					ire_refrele(ire);
23186 					ire = ire1;
23187 					stq = ire->ire_stq;
23188 					mp = next_mp;
23189 					next_mp = NULL;
23190 					ipha = (ipha_t *)mp->b_rptr;
23191 					ill_index = Q_TO_INDEX(stq);
23192 				}
23193 			} while (multirt_send);
23194 
23195 			if (!next_mp) {
23196 				/*
23197 				 * Last copy going out (the ultra-common
23198 				 * case).  Note that we intentionally replicate
23199 				 * the putnext rather than calling it before
23200 				 * the next_mp check in hopes of a little
23201 				 * tail-call action out of the compiler.
23202 				 */
23203 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23204 				    "ip_wput_ire_end: q %p (%S)",
23205 				    q, "last copy out(1)");
23206 				ire_refrele(ire);
23207 				if (conn_outgoing_ill != NULL)
23208 					ill_refrele(conn_outgoing_ill);
23209 				return;
23210 			}
23211 			/* More copies going out below. */
23212 		} else {
23213 			int offset;
23214 fragmentit:
23215 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23216 			/*
23217 			 * If this would generate a icmp_frag_needed message,
23218 			 * we need to handle it before we do the IPsec
23219 			 * processing. Otherwise, we need to strip the IPsec
23220 			 * headers before we send up the message to the ULPs
23221 			 * which becomes messy and difficult.
23222 			 */
23223 			if (ipsec_len != 0) {
23224 				if ((max_frag < (unsigned int)(LENGTH +
23225 				    ipsec_len)) && (offset & IPH_DF)) {
23226 					out_ill = (ill_t *)stq->q_ptr;
23227 					BUMP_MIB(out_ill->ill_ip_mib,
23228 					    ipIfStatsOutFragFails);
23229 					BUMP_MIB(out_ill->ill_ip_mib,
23230 					    ipIfStatsOutFragReqds);
23231 					ipha->ipha_hdr_checksum = 0;
23232 					ipha->ipha_hdr_checksum =
23233 					    (uint16_t)ip_csum_hdr(ipha);
23234 					icmp_frag_needed(ire->ire_stq, first_mp,
23235 					    max_frag, zoneid, ipst);
23236 					if (!next_mp) {
23237 						ire_refrele(ire);
23238 						if (conn_outgoing_ill != NULL) {
23239 							ill_refrele(
23240 							    conn_outgoing_ill);
23241 						}
23242 						return;
23243 					}
23244 				} else {
23245 					/*
23246 					 * This won't cause a icmp_frag_needed
23247 					 * message. to be generated. Send it on
23248 					 * the wire. Note that this could still
23249 					 * cause fragmentation and all we
23250 					 * do is the generation of the message
23251 					 * to the ULP if needed before IPsec.
23252 					 */
23253 					if (!next_mp) {
23254 						ipsec_out_process(q, first_mp,
23255 						    ire, ill_index);
23256 						TRACE_2(TR_FAC_IP,
23257 						    TR_IP_WPUT_IRE_END,
23258 						    "ip_wput_ire_end: q %p "
23259 						    "(%S)", q,
23260 						    "last ipsec_out_process");
23261 						ire_refrele(ire);
23262 						if (conn_outgoing_ill != NULL) {
23263 							ill_refrele(
23264 							    conn_outgoing_ill);
23265 						}
23266 						return;
23267 					}
23268 					ipsec_out_process(q, first_mp,
23269 					    ire, ill_index);
23270 				}
23271 			} else {
23272 				/*
23273 				 * Initiate IPPF processing. For
23274 				 * fragmentable packets we finish
23275 				 * all QOS packet processing before
23276 				 * calling:
23277 				 * ip_wput_ire_fragmentit->ip_wput_frag
23278 				 */
23279 
23280 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23281 					ip_process(IPP_LOCAL_OUT, &mp,
23282 					    ill_index);
23283 					if (mp == NULL) {
23284 						out_ill = (ill_t *)stq->q_ptr;
23285 						BUMP_MIB(out_ill->ill_ip_mib,
23286 						    ipIfStatsOutDiscards);
23287 						if (next_mp != NULL) {
23288 							freemsg(next_mp);
23289 							ire_refrele(ire1);
23290 						}
23291 						ire_refrele(ire);
23292 						TRACE_2(TR_FAC_IP,
23293 						    TR_IP_WPUT_IRE_END,
23294 						    "ip_wput_ire: q %p (%S)",
23295 						    q, "discard MDATA");
23296 						if (conn_outgoing_ill != NULL) {
23297 							ill_refrele(
23298 							    conn_outgoing_ill);
23299 						}
23300 						return;
23301 					}
23302 				}
23303 				if (!next_mp) {
23304 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23305 					    "ip_wput_ire_end: q %p (%S)",
23306 					    q, "last fragmentation");
23307 					ip_wput_ire_fragmentit(mp, ire,
23308 					    zoneid, ipst, connp);
23309 					ire_refrele(ire);
23310 					if (conn_outgoing_ill != NULL)
23311 						ill_refrele(conn_outgoing_ill);
23312 					return;
23313 				}
23314 				ip_wput_ire_fragmentit(mp, ire,
23315 				    zoneid, ipst, connp);
23316 			}
23317 		}
23318 	} else {
23319 nullstq:
23320 		/* A NULL stq means the destination address is local. */
23321 		UPDATE_OB_PKT_COUNT(ire);
23322 		ire->ire_last_used_time = lbolt;
23323 		ASSERT(ire->ire_ipif != NULL);
23324 		if (!next_mp) {
23325 			/*
23326 			 * Is there an "in" and "out" for traffic local
23327 			 * to a host (loopback)?  The code in Solaris doesn't
23328 			 * explicitly draw a line in its code for in vs out,
23329 			 * so we've had to draw a line in the sand: ip_wput_ire
23330 			 * is considered to be the "output" side and
23331 			 * ip_wput_local to be the "input" side.
23332 			 */
23333 			out_ill = ire_to_ill(ire);
23334 
23335 			/*
23336 			 * DTrace this as ip:::send.  A blocked packet will
23337 			 * fire the send probe, but not the receive probe.
23338 			 */
23339 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23340 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23341 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23342 
23343 			DTRACE_PROBE4(ip4__loopback__out__start,
23344 			    ill_t *, NULL, ill_t *, out_ill,
23345 			    ipha_t *, ipha, mblk_t *, first_mp);
23346 
23347 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23348 			    ipst->ips_ipv4firewall_loopback_out,
23349 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23350 
23351 			DTRACE_PROBE1(ip4__loopback__out_end,
23352 			    mblk_t *, first_mp);
23353 
23354 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23355 			    "ip_wput_ire_end: q %p (%S)",
23356 			    q, "local address");
23357 
23358 			if (first_mp != NULL)
23359 				ip_wput_local(q, out_ill, ipha,
23360 				    first_mp, ire, 0, ire->ire_zoneid);
23361 			ire_refrele(ire);
23362 			if (conn_outgoing_ill != NULL)
23363 				ill_refrele(conn_outgoing_ill);
23364 			return;
23365 		}
23366 
23367 		out_ill = ire_to_ill(ire);
23368 
23369 		/*
23370 		 * DTrace this as ip:::send.  A blocked packet will fire the
23371 		 * send probe, but not the receive probe.
23372 		 */
23373 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23374 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23375 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23376 
23377 		DTRACE_PROBE4(ip4__loopback__out__start,
23378 		    ill_t *, NULL, ill_t *, out_ill,
23379 		    ipha_t *, ipha, mblk_t *, first_mp);
23380 
23381 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23382 		    ipst->ips_ipv4firewall_loopback_out,
23383 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23384 
23385 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23386 
23387 		if (first_mp != NULL)
23388 			ip_wput_local(q, out_ill, ipha,
23389 			    first_mp, ire, 0, ire->ire_zoneid);
23390 	}
23391 next:
23392 	/*
23393 	 * More copies going out to additional interfaces.
23394 	 * ire1 has already been held. We don't need the
23395 	 * "ire" anymore.
23396 	 */
23397 	ire_refrele(ire);
23398 	ire = ire1;
23399 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23400 	mp = next_mp;
23401 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23402 	ill = ire_to_ill(ire);
23403 	first_mp = mp;
23404 	if (ipsec_len != 0) {
23405 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23406 		mp = mp->b_cont;
23407 	}
23408 	dst = ire->ire_addr;
23409 	ipha = (ipha_t *)mp->b_rptr;
23410 	/*
23411 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23412 	 * Restore ipha_ident "no checksum" flag.
23413 	 */
23414 	src = orig_src;
23415 	ipha->ipha_ident = ip_hdr_included;
23416 	goto another;
23417 
23418 #undef	rptr
23419 #undef	Q_TO_INDEX
23420 }
23421 
23422 /*
23423  * Routine to allocate a message that is used to notify the ULP about MDT.
23424  * The caller may provide a pointer to the link-layer MDT capabilities,
23425  * or NULL if MDT is to be disabled on the stream.
23426  */
23427 mblk_t *
23428 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23429 {
23430 	mblk_t *mp;
23431 	ip_mdt_info_t *mdti;
23432 	ill_mdt_capab_t *idst;
23433 
23434 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23435 		DB_TYPE(mp) = M_CTL;
23436 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23437 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23438 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23439 		idst = &(mdti->mdt_capab);
23440 
23441 		/*
23442 		 * If the caller provides us with the capability, copy
23443 		 * it over into our notification message; otherwise
23444 		 * we zero out the capability portion.
23445 		 */
23446 		if (isrc != NULL)
23447 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23448 		else
23449 			bzero((caddr_t)idst, sizeof (*idst));
23450 	}
23451 	return (mp);
23452 }
23453 
23454 /*
23455  * Routine which determines whether MDT can be enabled on the destination
23456  * IRE and IPC combination, and if so, allocates and returns the MDT
23457  * notification mblk that may be used by ULP.  We also check if we need to
23458  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23459  * MDT usage in the past have been lifted.  This gets called during IP
23460  * and ULP binding.
23461  */
23462 mblk_t *
23463 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23464     ill_mdt_capab_t *mdt_cap)
23465 {
23466 	mblk_t *mp;
23467 	boolean_t rc = B_FALSE;
23468 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23469 
23470 	ASSERT(dst_ire != NULL);
23471 	ASSERT(connp != NULL);
23472 	ASSERT(mdt_cap != NULL);
23473 
23474 	/*
23475 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23476 	 * Multidata, which is handled in tcp_multisend().  This
23477 	 * is the reason why we do all these checks here, to ensure
23478 	 * that we don't enable Multidata for the cases which we
23479 	 * can't handle at the moment.
23480 	 */
23481 	do {
23482 		/* Only do TCP at the moment */
23483 		if (connp->conn_ulp != IPPROTO_TCP)
23484 			break;
23485 
23486 		/*
23487 		 * IPsec outbound policy present?  Note that we get here
23488 		 * after calling ipsec_conn_cache_policy() where the global
23489 		 * policy checking is performed.  conn_latch will be
23490 		 * non-NULL as long as there's a policy defined,
23491 		 * i.e. conn_out_enforce_policy may be NULL in such case
23492 		 * when the connection is non-secure, and hence we check
23493 		 * further if the latch refers to an outbound policy.
23494 		 */
23495 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23496 			break;
23497 
23498 		/* CGTP (multiroute) is enabled? */
23499 		if (dst_ire->ire_flags & RTF_MULTIRT)
23500 			break;
23501 
23502 		/* Outbound IPQoS enabled? */
23503 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23504 			/*
23505 			 * In this case, we disable MDT for this and all
23506 			 * future connections going over the interface.
23507 			 */
23508 			mdt_cap->ill_mdt_on = 0;
23509 			break;
23510 		}
23511 
23512 		/* socket option(s) present? */
23513 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23514 			break;
23515 
23516 		rc = B_TRUE;
23517 	/* CONSTCOND */
23518 	} while (0);
23519 
23520 	/* Remember the result */
23521 	connp->conn_mdt_ok = rc;
23522 
23523 	if (!rc)
23524 		return (NULL);
23525 	else if (!mdt_cap->ill_mdt_on) {
23526 		/*
23527 		 * If MDT has been previously turned off in the past, and we
23528 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23529 		 * then enable it for this interface.
23530 		 */
23531 		mdt_cap->ill_mdt_on = 1;
23532 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23533 		    "interface %s\n", ill_name));
23534 	}
23535 
23536 	/* Allocate the MDT info mblk */
23537 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23538 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23539 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23540 		return (NULL);
23541 	}
23542 	return (mp);
23543 }
23544 
23545 /*
23546  * Routine to allocate a message that is used to notify the ULP about LSO.
23547  * The caller may provide a pointer to the link-layer LSO capabilities,
23548  * or NULL if LSO is to be disabled on the stream.
23549  */
23550 mblk_t *
23551 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23552 {
23553 	mblk_t *mp;
23554 	ip_lso_info_t *lsoi;
23555 	ill_lso_capab_t *idst;
23556 
23557 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23558 		DB_TYPE(mp) = M_CTL;
23559 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23560 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23561 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23562 		idst = &(lsoi->lso_capab);
23563 
23564 		/*
23565 		 * If the caller provides us with the capability, copy
23566 		 * it over into our notification message; otherwise
23567 		 * we zero out the capability portion.
23568 		 */
23569 		if (isrc != NULL)
23570 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23571 		else
23572 			bzero((caddr_t)idst, sizeof (*idst));
23573 	}
23574 	return (mp);
23575 }
23576 
23577 /*
23578  * Routine which determines whether LSO can be enabled on the destination
23579  * IRE and IPC combination, and if so, allocates and returns the LSO
23580  * notification mblk that may be used by ULP.  We also check if we need to
23581  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23582  * LSO usage in the past have been lifted.  This gets called during IP
23583  * and ULP binding.
23584  */
23585 mblk_t *
23586 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23587     ill_lso_capab_t *lso_cap)
23588 {
23589 	mblk_t *mp;
23590 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23591 
23592 	ASSERT(dst_ire != NULL);
23593 	ASSERT(connp != NULL);
23594 	ASSERT(lso_cap != NULL);
23595 
23596 	connp->conn_lso_ok = B_TRUE;
23597 
23598 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23599 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23600 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23601 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23602 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23603 		connp->conn_lso_ok = B_FALSE;
23604 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23605 			/*
23606 			 * Disable LSO for this and all future connections going
23607 			 * over the interface.
23608 			 */
23609 			lso_cap->ill_lso_on = 0;
23610 		}
23611 	}
23612 
23613 	if (!connp->conn_lso_ok)
23614 		return (NULL);
23615 	else if (!lso_cap->ill_lso_on) {
23616 		/*
23617 		 * If LSO has been previously turned off in the past, and we
23618 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23619 		 * then enable it for this interface.
23620 		 */
23621 		lso_cap->ill_lso_on = 1;
23622 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23623 		    ill_name));
23624 	}
23625 
23626 	/* Allocate the LSO info mblk */
23627 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23628 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23629 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23630 
23631 	return (mp);
23632 }
23633 
23634 /*
23635  * Create destination address attribute, and fill it with the physical
23636  * destination address and SAP taken from the template DL_UNITDATA_REQ
23637  * message block.
23638  */
23639 boolean_t
23640 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23641 {
23642 	dl_unitdata_req_t *dlurp;
23643 	pattr_t *pa;
23644 	pattrinfo_t pa_info;
23645 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23646 	uint_t das_len, das_off;
23647 
23648 	ASSERT(dlmp != NULL);
23649 
23650 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23651 	das_len = dlurp->dl_dest_addr_length;
23652 	das_off = dlurp->dl_dest_addr_offset;
23653 
23654 	pa_info.type = PATTR_DSTADDRSAP;
23655 	pa_info.len = sizeof (**das) + das_len - 1;
23656 
23657 	/* create and associate the attribute */
23658 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23659 	if (pa != NULL) {
23660 		ASSERT(*das != NULL);
23661 		(*das)->addr_is_group = 0;
23662 		(*das)->addr_len = (uint8_t)das_len;
23663 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23664 	}
23665 
23666 	return (pa != NULL);
23667 }
23668 
23669 /*
23670  * Create hardware checksum attribute and fill it with the values passed.
23671  */
23672 boolean_t
23673 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23674     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23675 {
23676 	pattr_t *pa;
23677 	pattrinfo_t pa_info;
23678 
23679 	ASSERT(mmd != NULL);
23680 
23681 	pa_info.type = PATTR_HCKSUM;
23682 	pa_info.len = sizeof (pattr_hcksum_t);
23683 
23684 	/* create and associate the attribute */
23685 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23686 	if (pa != NULL) {
23687 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23688 
23689 		hck->hcksum_start_offset = start_offset;
23690 		hck->hcksum_stuff_offset = stuff_offset;
23691 		hck->hcksum_end_offset = end_offset;
23692 		hck->hcksum_flags = flags;
23693 	}
23694 	return (pa != NULL);
23695 }
23696 
23697 /*
23698  * Create zerocopy attribute and fill it with the specified flags
23699  */
23700 boolean_t
23701 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23702 {
23703 	pattr_t *pa;
23704 	pattrinfo_t pa_info;
23705 
23706 	ASSERT(mmd != NULL);
23707 	pa_info.type = PATTR_ZCOPY;
23708 	pa_info.len = sizeof (pattr_zcopy_t);
23709 
23710 	/* create and associate the attribute */
23711 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23712 	if (pa != NULL) {
23713 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23714 
23715 		zcopy->zcopy_flags = flags;
23716 	}
23717 	return (pa != NULL);
23718 }
23719 
23720 /*
23721  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23722  * block chain. We could rewrite to handle arbitrary message block chains but
23723  * that would make the code complicated and slow. Right now there three
23724  * restrictions:
23725  *
23726  *   1. The first message block must contain the complete IP header and
23727  *	at least 1 byte of payload data.
23728  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23729  *	so that we can use a single Multidata message.
23730  *   3. No frag must be distributed over two or more message blocks so
23731  *	that we don't need more than two packet descriptors per frag.
23732  *
23733  * The above restrictions allow us to support userland applications (which
23734  * will send down a single message block) and NFS over UDP (which will
23735  * send down a chain of at most three message blocks).
23736  *
23737  * We also don't use MDT for payloads with less than or equal to
23738  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23739  */
23740 boolean_t
23741 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23742 {
23743 	int	blocks;
23744 	ssize_t	total, missing, size;
23745 
23746 	ASSERT(mp != NULL);
23747 	ASSERT(hdr_len > 0);
23748 
23749 	size = MBLKL(mp) - hdr_len;
23750 	if (size <= 0)
23751 		return (B_FALSE);
23752 
23753 	/* The first mblk contains the header and some payload. */
23754 	blocks = 1;
23755 	total = size;
23756 	size %= len;
23757 	missing = (size == 0) ? 0 : (len - size);
23758 	mp = mp->b_cont;
23759 
23760 	while (mp != NULL) {
23761 		/*
23762 		 * Give up if we encounter a zero length message block.
23763 		 * In practice, this should rarely happen and therefore
23764 		 * not worth the trouble of freeing and re-linking the
23765 		 * mblk from the chain to handle such case.
23766 		 */
23767 		if ((size = MBLKL(mp)) == 0)
23768 			return (B_FALSE);
23769 
23770 		/* Too many payload buffers for a single Multidata message? */
23771 		if (++blocks > MULTIDATA_MAX_PBUFS)
23772 			return (B_FALSE);
23773 
23774 		total += size;
23775 		/* Is a frag distributed over two or more message blocks? */
23776 		if (missing > size)
23777 			return (B_FALSE);
23778 		size -= missing;
23779 
23780 		size %= len;
23781 		missing = (size == 0) ? 0 : (len - size);
23782 
23783 		mp = mp->b_cont;
23784 	}
23785 
23786 	return (total > ip_wput_frag_mdt_min);
23787 }
23788 
23789 /*
23790  * Outbound IPv4 fragmentation routine using MDT.
23791  */
23792 static void
23793 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23794     uint32_t frag_flag, int offset)
23795 {
23796 	ipha_t		*ipha_orig;
23797 	int		i1, ip_data_end;
23798 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23799 	mblk_t		*hdr_mp, *md_mp = NULL;
23800 	unsigned char	*hdr_ptr, *pld_ptr;
23801 	multidata_t	*mmd;
23802 	ip_pdescinfo_t	pdi;
23803 	ill_t		*ill;
23804 	ip_stack_t	*ipst = ire->ire_ipst;
23805 
23806 	ASSERT(DB_TYPE(mp) == M_DATA);
23807 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23808 
23809 	ill = ire_to_ill(ire);
23810 	ASSERT(ill != NULL);
23811 
23812 	ipha_orig = (ipha_t *)mp->b_rptr;
23813 	mp->b_rptr += sizeof (ipha_t);
23814 
23815 	/* Calculate how many packets we will send out */
23816 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23817 	pkts = (i1 + len - 1) / len;
23818 	ASSERT(pkts > 1);
23819 
23820 	/* Allocate a message block which will hold all the IP Headers. */
23821 	wroff = ipst->ips_ip_wroff_extra;
23822 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23823 
23824 	i1 = pkts * hdr_chunk_len;
23825 	/*
23826 	 * Create the header buffer, Multidata and destination address
23827 	 * and SAP attribute that should be associated with it.
23828 	 */
23829 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23830 	    ((hdr_mp->b_wptr += i1),
23831 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23832 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23833 		freemsg(mp);
23834 		if (md_mp == NULL) {
23835 			freemsg(hdr_mp);
23836 		} else {
23837 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23838 			freemsg(md_mp);
23839 		}
23840 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23841 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23842 		return;
23843 	}
23844 	IP_STAT(ipst, ip_frag_mdt_allocd);
23845 
23846 	/*
23847 	 * Add a payload buffer to the Multidata; this operation must not
23848 	 * fail, or otherwise our logic in this routine is broken.  There
23849 	 * is no memory allocation done by the routine, so any returned
23850 	 * failure simply tells us that we've done something wrong.
23851 	 *
23852 	 * A failure tells us that either we're adding the same payload
23853 	 * buffer more than once, or we're trying to add more buffers than
23854 	 * allowed.  None of the above cases should happen, and we panic
23855 	 * because either there's horrible heap corruption, and/or
23856 	 * programming mistake.
23857 	 */
23858 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23859 		goto pbuf_panic;
23860 
23861 	hdr_ptr = hdr_mp->b_rptr;
23862 	pld_ptr = mp->b_rptr;
23863 
23864 	/* Establish the ending byte offset, based on the starting offset. */
23865 	offset <<= 3;
23866 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23867 	    IP_SIMPLE_HDR_LENGTH;
23868 
23869 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23870 
23871 	while (pld_ptr < mp->b_wptr) {
23872 		ipha_t		*ipha;
23873 		uint16_t	offset_and_flags;
23874 		uint16_t	ip_len;
23875 		int		error;
23876 
23877 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23878 		ipha = (ipha_t *)(hdr_ptr + wroff);
23879 		ASSERT(OK_32PTR(ipha));
23880 		*ipha = *ipha_orig;
23881 
23882 		if (ip_data_end - offset > len) {
23883 			offset_and_flags = IPH_MF;
23884 		} else {
23885 			/*
23886 			 * Last frag. Set len to the length of this last piece.
23887 			 */
23888 			len = ip_data_end - offset;
23889 			/* A frag of a frag might have IPH_MF non-zero */
23890 			offset_and_flags =
23891 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23892 			    IPH_MF;
23893 		}
23894 		offset_and_flags |= (uint16_t)(offset >> 3);
23895 		offset_and_flags |= (uint16_t)frag_flag;
23896 		/* Store the offset and flags in the IP header. */
23897 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23898 
23899 		/* Store the length in the IP header. */
23900 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23901 		ipha->ipha_length = htons(ip_len);
23902 
23903 		/*
23904 		 * Set the IP header checksum.  Note that mp is just
23905 		 * the header, so this is easy to pass to ip_csum.
23906 		 */
23907 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23908 
23909 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23910 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23911 		    NULL, int, 0);
23912 
23913 		/*
23914 		 * Record offset and size of header and data of the next packet
23915 		 * in the multidata message.
23916 		 */
23917 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23918 		PDESC_PLD_INIT(&pdi);
23919 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23920 		ASSERT(i1 > 0);
23921 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23922 		if (i1 == len) {
23923 			pld_ptr += len;
23924 		} else {
23925 			i1 = len - i1;
23926 			mp = mp->b_cont;
23927 			ASSERT(mp != NULL);
23928 			ASSERT(MBLKL(mp) >= i1);
23929 			/*
23930 			 * Attach the next payload message block to the
23931 			 * multidata message.
23932 			 */
23933 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23934 				goto pbuf_panic;
23935 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23936 			pld_ptr = mp->b_rptr + i1;
23937 		}
23938 
23939 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23940 		    KM_NOSLEEP)) == NULL) {
23941 			/*
23942 			 * Any failure other than ENOMEM indicates that we
23943 			 * have passed in invalid pdesc info or parameters
23944 			 * to mmd_addpdesc, which must not happen.
23945 			 *
23946 			 * EINVAL is a result of failure on boundary checks
23947 			 * against the pdesc info contents.  It should not
23948 			 * happen, and we panic because either there's
23949 			 * horrible heap corruption, and/or programming
23950 			 * mistake.
23951 			 */
23952 			if (error != ENOMEM) {
23953 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23954 				    "pdesc logic error detected for "
23955 				    "mmd %p pinfo %p (%d)\n",
23956 				    (void *)mmd, (void *)&pdi, error);
23957 				/* NOTREACHED */
23958 			}
23959 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23960 			/* Free unattached payload message blocks as well */
23961 			md_mp->b_cont = mp->b_cont;
23962 			goto free_mmd;
23963 		}
23964 
23965 		/* Advance fragment offset. */
23966 		offset += len;
23967 
23968 		/* Advance to location for next header in the buffer. */
23969 		hdr_ptr += hdr_chunk_len;
23970 
23971 		/* Did we reach the next payload message block? */
23972 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23973 			mp = mp->b_cont;
23974 			/*
23975 			 * Attach the next message block with payload
23976 			 * data to the multidata message.
23977 			 */
23978 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23979 				goto pbuf_panic;
23980 			pld_ptr = mp->b_rptr;
23981 		}
23982 	}
23983 
23984 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23985 	ASSERT(mp->b_wptr == pld_ptr);
23986 
23987 	/* Update IP statistics */
23988 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23989 
23990 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23991 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23992 
23993 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23994 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23995 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23996 
23997 	if (pkt_type == OB_PKT) {
23998 		ire->ire_ob_pkt_count += pkts;
23999 		if (ire->ire_ipif != NULL)
24000 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24001 	} else {
24002 		/* The type is IB_PKT in the forwarding path. */
24003 		ire->ire_ib_pkt_count += pkts;
24004 		ASSERT(!IRE_IS_LOCAL(ire));
24005 		if (ire->ire_type & IRE_BROADCAST) {
24006 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24007 		} else {
24008 			UPDATE_MIB(ill->ill_ip_mib,
24009 			    ipIfStatsHCOutForwDatagrams, pkts);
24010 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24011 		}
24012 	}
24013 	ire->ire_last_used_time = lbolt;
24014 	/* Send it down */
24015 	putnext(ire->ire_stq, md_mp);
24016 	return;
24017 
24018 pbuf_panic:
24019 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24020 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24021 	    pbuf_idx);
24022 	/* NOTREACHED */
24023 }
24024 
24025 /*
24026  * Outbound IP fragmentation routine.
24027  *
24028  * NOTE : This routine does not ire_refrele the ire that is passed in
24029  * as the argument.
24030  */
24031 static void
24032 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24033     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24034 {
24035 	int		i1;
24036 	mblk_t		*ll_hdr_mp;
24037 	int 		ll_hdr_len;
24038 	int		hdr_len;
24039 	mblk_t		*hdr_mp;
24040 	ipha_t		*ipha;
24041 	int		ip_data_end;
24042 	int		len;
24043 	mblk_t		*mp = mp_orig, *mp1;
24044 	int		offset;
24045 	queue_t		*q;
24046 	uint32_t	v_hlen_tos_len;
24047 	mblk_t		*first_mp;
24048 	boolean_t	mctl_present;
24049 	ill_t		*ill;
24050 	ill_t		*out_ill;
24051 	mblk_t		*xmit_mp;
24052 	mblk_t		*carve_mp;
24053 	ire_t		*ire1 = NULL;
24054 	ire_t		*save_ire = NULL;
24055 	mblk_t  	*next_mp = NULL;
24056 	boolean_t	last_frag = B_FALSE;
24057 	boolean_t	multirt_send = B_FALSE;
24058 	ire_t		*first_ire = NULL;
24059 	irb_t		*irb = NULL;
24060 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24061 
24062 	ill = ire_to_ill(ire);
24063 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24064 
24065 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24066 
24067 	if (max_frag == 0) {
24068 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24069 		    " -  dropping packet\n"));
24070 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24071 		freemsg(mp);
24072 		return;
24073 	}
24074 
24075 	/*
24076 	 * IPsec does not allow hw accelerated packets to be fragmented
24077 	 * This check is made in ip_wput_ipsec_out prior to coming here
24078 	 * via ip_wput_ire_fragmentit.
24079 	 *
24080 	 * If at this point we have an ire whose ARP request has not
24081 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24082 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24083 	 * This packet and all fragmentable packets for this ire will
24084 	 * continue to get dropped while ire_nce->nce_state remains in
24085 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24086 	 * ND_REACHABLE, all subsquent large packets for this ire will
24087 	 * get fragemented and sent out by this function.
24088 	 */
24089 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24090 		/* If nce_state is ND_INITIAL, trigger ARP query */
24091 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24092 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24093 		    " -  dropping packet\n"));
24094 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24095 		freemsg(mp);
24096 		return;
24097 	}
24098 
24099 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24100 	    "ip_wput_frag_start:");
24101 
24102 	if (mp->b_datap->db_type == M_CTL) {
24103 		first_mp = mp;
24104 		mp_orig = mp = mp->b_cont;
24105 		mctl_present = B_TRUE;
24106 	} else {
24107 		first_mp = mp;
24108 		mctl_present = B_FALSE;
24109 	}
24110 
24111 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24112 	ipha = (ipha_t *)mp->b_rptr;
24113 
24114 	/*
24115 	 * If the Don't Fragment flag is on, generate an ICMP destination
24116 	 * unreachable, fragmentation needed.
24117 	 */
24118 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24119 	if (offset & IPH_DF) {
24120 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24121 		if (is_system_labeled()) {
24122 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24123 			    ire->ire_max_frag - max_frag, AF_INET);
24124 		}
24125 		/*
24126 		 * Need to compute hdr checksum if called from ip_wput_ire.
24127 		 * Note that ip_rput_forward verifies the checksum before
24128 		 * calling this routine so in that case this is a noop.
24129 		 */
24130 		ipha->ipha_hdr_checksum = 0;
24131 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24132 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24133 		    ipst);
24134 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24135 		    "ip_wput_frag_end:(%S)",
24136 		    "don't fragment");
24137 		return;
24138 	}
24139 	/*
24140 	 * Labeled systems adjust max_frag if they add a label
24141 	 * to send the correct path mtu.  We need the real mtu since we
24142 	 * are fragmenting the packet after label adjustment.
24143 	 */
24144 	if (is_system_labeled())
24145 		max_frag = ire->ire_max_frag;
24146 	if (mctl_present)
24147 		freeb(first_mp);
24148 	/*
24149 	 * Establish the starting offset.  May not be zero if we are fragging
24150 	 * a fragment that is being forwarded.
24151 	 */
24152 	offset = offset & IPH_OFFSET;
24153 
24154 	/* TODO why is this test needed? */
24155 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24156 	if (((max_frag - LENGTH) & ~7) < 8) {
24157 		/* TODO: notify ulp somehow */
24158 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24159 		freemsg(mp);
24160 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24161 		    "ip_wput_frag_end:(%S)",
24162 		    "len < 8");
24163 		return;
24164 	}
24165 
24166 	hdr_len = (V_HLEN & 0xF) << 2;
24167 
24168 	ipha->ipha_hdr_checksum = 0;
24169 
24170 	/*
24171 	 * Establish the number of bytes maximum per frag, after putting
24172 	 * in the header.
24173 	 */
24174 	len = (max_frag - hdr_len) & ~7;
24175 
24176 	/* Check if we can use MDT to send out the frags. */
24177 	ASSERT(!IRE_IS_LOCAL(ire));
24178 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24179 	    ipst->ips_ip_multidata_outbound &&
24180 	    !(ire->ire_flags & RTF_MULTIRT) &&
24181 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24182 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24183 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24184 		ASSERT(ill->ill_mdt_capab != NULL);
24185 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24186 			/*
24187 			 * If MDT has been previously turned off in the past,
24188 			 * and we currently can do MDT (due to IPQoS policy
24189 			 * removal, etc.) then enable it for this interface.
24190 			 */
24191 			ill->ill_mdt_capab->ill_mdt_on = 1;
24192 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24193 			    ill->ill_name));
24194 		}
24195 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24196 		    offset);
24197 		return;
24198 	}
24199 
24200 	/* Get a copy of the header for the trailing frags */
24201 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24202 	    mp);
24203 	if (!hdr_mp) {
24204 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24205 		freemsg(mp);
24206 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24207 		    "ip_wput_frag_end:(%S)",
24208 		    "couldn't copy hdr");
24209 		return;
24210 	}
24211 
24212 	/* Store the starting offset, with the MoreFrags flag. */
24213 	i1 = offset | IPH_MF | frag_flag;
24214 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24215 
24216 	/* Establish the ending byte offset, based on the starting offset. */
24217 	offset <<= 3;
24218 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24219 
24220 	/* Store the length of the first fragment in the IP header. */
24221 	i1 = len + hdr_len;
24222 	ASSERT(i1 <= IP_MAXPACKET);
24223 	ipha->ipha_length = htons((uint16_t)i1);
24224 
24225 	/*
24226 	 * Compute the IP header checksum for the first frag.  We have to
24227 	 * watch out that we stop at the end of the header.
24228 	 */
24229 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24230 
24231 	/*
24232 	 * Now carve off the first frag.  Note that this will include the
24233 	 * original IP header.
24234 	 */
24235 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24236 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24237 		freeb(hdr_mp);
24238 		freemsg(mp_orig);
24239 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24240 		    "ip_wput_frag_end:(%S)",
24241 		    "couldn't carve first");
24242 		return;
24243 	}
24244 
24245 	/*
24246 	 * Multirouting case. Each fragment is replicated
24247 	 * via all non-condemned RTF_MULTIRT routes
24248 	 * currently resolved.
24249 	 * We ensure that first_ire is the first RTF_MULTIRT
24250 	 * ire in the bucket.
24251 	 */
24252 	if (ire->ire_flags & RTF_MULTIRT) {
24253 		irb = ire->ire_bucket;
24254 		ASSERT(irb != NULL);
24255 
24256 		multirt_send = B_TRUE;
24257 
24258 		/* Make sure we do not omit any multiroute ire. */
24259 		IRB_REFHOLD(irb);
24260 		for (first_ire = irb->irb_ire;
24261 		    first_ire != NULL;
24262 		    first_ire = first_ire->ire_next) {
24263 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24264 			    (first_ire->ire_addr == ire->ire_addr) &&
24265 			    !(first_ire->ire_marks &
24266 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24267 				break;
24268 		}
24269 
24270 		if (first_ire != NULL) {
24271 			if (first_ire != ire) {
24272 				IRE_REFHOLD(first_ire);
24273 				/*
24274 				 * Do not release the ire passed in
24275 				 * as the argument.
24276 				 */
24277 				ire = first_ire;
24278 			} else {
24279 				first_ire = NULL;
24280 			}
24281 		}
24282 		IRB_REFRELE(irb);
24283 
24284 		/*
24285 		 * Save the first ire; we will need to restore it
24286 		 * for the trailing frags.
24287 		 * We REFHOLD save_ire, as each iterated ire will be
24288 		 * REFRELEd.
24289 		 */
24290 		save_ire = ire;
24291 		IRE_REFHOLD(save_ire);
24292 	}
24293 
24294 	/*
24295 	 * First fragment emission loop.
24296 	 * In most cases, the emission loop below is entered only
24297 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24298 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24299 	 * bucket, and send the fragment through all crossed
24300 	 * RTF_MULTIRT routes.
24301 	 */
24302 	do {
24303 		if (ire->ire_flags & RTF_MULTIRT) {
24304 			/*
24305 			 * We are in a multiple send case, need to get
24306 			 * the next ire and make a copy of the packet.
24307 			 * ire1 holds here the next ire to process in the
24308 			 * bucket. If multirouting is expected,
24309 			 * any non-RTF_MULTIRT ire that has the
24310 			 * right destination address is ignored.
24311 			 *
24312 			 * We have to take into account the MTU of
24313 			 * each walked ire. max_frag is set by the
24314 			 * the caller and generally refers to
24315 			 * the primary ire entry. Here we ensure that
24316 			 * no route with a lower MTU will be used, as
24317 			 * fragments are carved once for all ires,
24318 			 * then replicated.
24319 			 */
24320 			ASSERT(irb != NULL);
24321 			IRB_REFHOLD(irb);
24322 			for (ire1 = ire->ire_next;
24323 			    ire1 != NULL;
24324 			    ire1 = ire1->ire_next) {
24325 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24326 					continue;
24327 				if (ire1->ire_addr != ire->ire_addr)
24328 					continue;
24329 				if (ire1->ire_marks &
24330 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24331 					continue;
24332 				/*
24333 				 * Ensure we do not exceed the MTU
24334 				 * of the next route.
24335 				 */
24336 				if (ire1->ire_max_frag < max_frag) {
24337 					ip_multirt_bad_mtu(ire1, max_frag);
24338 					continue;
24339 				}
24340 
24341 				/* Got one. */
24342 				IRE_REFHOLD(ire1);
24343 				break;
24344 			}
24345 			IRB_REFRELE(irb);
24346 
24347 			if (ire1 != NULL) {
24348 				next_mp = copyb(mp);
24349 				if ((next_mp == NULL) ||
24350 				    ((mp->b_cont != NULL) &&
24351 				    ((next_mp->b_cont =
24352 				    dupmsg(mp->b_cont)) == NULL))) {
24353 					freemsg(next_mp);
24354 					next_mp = NULL;
24355 					ire_refrele(ire1);
24356 					ire1 = NULL;
24357 				}
24358 			}
24359 
24360 			/* Last multiroute ire; don't loop anymore. */
24361 			if (ire1 == NULL) {
24362 				multirt_send = B_FALSE;
24363 			}
24364 		}
24365 
24366 		ll_hdr_len = 0;
24367 		LOCK_IRE_FP_MP(ire);
24368 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24369 		if (ll_hdr_mp != NULL) {
24370 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24371 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24372 		} else {
24373 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24374 		}
24375 
24376 		/* If there is a transmit header, get a copy for this frag. */
24377 		/*
24378 		 * TODO: should check db_ref before calling ip_carve_mp since
24379 		 * it might give us a dup.
24380 		 */
24381 		if (!ll_hdr_mp) {
24382 			/* No xmit header. */
24383 			xmit_mp = mp;
24384 
24385 		/* We have a link-layer header that can fit in our mblk. */
24386 		} else if (mp->b_datap->db_ref == 1 &&
24387 		    ll_hdr_len != 0 &&
24388 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24389 			/* M_DATA fastpath */
24390 			mp->b_rptr -= ll_hdr_len;
24391 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24392 			xmit_mp = mp;
24393 
24394 		/* Corner case if copyb has failed */
24395 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24396 			UNLOCK_IRE_FP_MP(ire);
24397 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24398 			freeb(hdr_mp);
24399 			freemsg(mp);
24400 			freemsg(mp_orig);
24401 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24402 			    "ip_wput_frag_end:(%S)",
24403 			    "discard");
24404 
24405 			if (multirt_send) {
24406 				ASSERT(ire1);
24407 				ASSERT(next_mp);
24408 
24409 				freemsg(next_mp);
24410 				ire_refrele(ire1);
24411 			}
24412 			if (save_ire != NULL)
24413 				IRE_REFRELE(save_ire);
24414 
24415 			if (first_ire != NULL)
24416 				ire_refrele(first_ire);
24417 			return;
24418 
24419 		/*
24420 		 * Case of res_mp OR the fastpath mp can't fit
24421 		 * in the mblk
24422 		 */
24423 		} else {
24424 			xmit_mp->b_cont = mp;
24425 
24426 			/*
24427 			 * Get priority marking, if any.
24428 			 * We propagate the CoS marking from the
24429 			 * original packet that went to QoS processing
24430 			 * in ip_wput_ire to the newly carved mp.
24431 			 */
24432 			if (DB_TYPE(xmit_mp) == M_DATA)
24433 				xmit_mp->b_band = mp->b_band;
24434 		}
24435 		UNLOCK_IRE_FP_MP(ire);
24436 
24437 		q = ire->ire_stq;
24438 		out_ill = (ill_t *)q->q_ptr;
24439 
24440 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24441 
24442 		DTRACE_PROBE4(ip4__physical__out__start,
24443 		    ill_t *, NULL, ill_t *, out_ill,
24444 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24445 
24446 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24447 		    ipst->ips_ipv4firewall_physical_out,
24448 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24449 
24450 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24451 
24452 		if (xmit_mp != NULL) {
24453 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24454 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24455 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24456 
24457 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24458 
24459 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24460 			UPDATE_MIB(out_ill->ill_ip_mib,
24461 			    ipIfStatsHCOutOctets, i1);
24462 
24463 			if (pkt_type != OB_PKT) {
24464 				/*
24465 				 * Update the packet count and MIB stats
24466 				 * of trailing RTF_MULTIRT ires.
24467 				 */
24468 				UPDATE_OB_PKT_COUNT(ire);
24469 				BUMP_MIB(out_ill->ill_ip_mib,
24470 				    ipIfStatsOutFragReqds);
24471 			}
24472 		}
24473 
24474 		if (multirt_send) {
24475 			/*
24476 			 * We are in a multiple send case; look for
24477 			 * the next ire and re-enter the loop.
24478 			 */
24479 			ASSERT(ire1);
24480 			ASSERT(next_mp);
24481 			/* REFRELE the current ire before looping */
24482 			ire_refrele(ire);
24483 			ire = ire1;
24484 			ire1 = NULL;
24485 			mp = next_mp;
24486 			next_mp = NULL;
24487 		}
24488 	} while (multirt_send);
24489 
24490 	ASSERT(ire1 == NULL);
24491 
24492 	/* Restore the original ire; we need it for the trailing frags */
24493 	if (save_ire != NULL) {
24494 		/* REFRELE the last iterated ire */
24495 		ire_refrele(ire);
24496 		/* save_ire has been REFHOLDed */
24497 		ire = save_ire;
24498 		save_ire = NULL;
24499 		q = ire->ire_stq;
24500 	}
24501 
24502 	if (pkt_type == OB_PKT) {
24503 		UPDATE_OB_PKT_COUNT(ire);
24504 	} else {
24505 		out_ill = (ill_t *)q->q_ptr;
24506 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24507 		UPDATE_IB_PKT_COUNT(ire);
24508 	}
24509 
24510 	/* Advance the offset to the second frag starting point. */
24511 	offset += len;
24512 	/*
24513 	 * Update hdr_len from the copied header - there might be less options
24514 	 * in the later fragments.
24515 	 */
24516 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24517 	/* Loop until done. */
24518 	for (;;) {
24519 		uint16_t	offset_and_flags;
24520 		uint16_t	ip_len;
24521 
24522 		if (ip_data_end - offset > len) {
24523 			/*
24524 			 * Carve off the appropriate amount from the original
24525 			 * datagram.
24526 			 */
24527 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24528 				mp = NULL;
24529 				break;
24530 			}
24531 			/*
24532 			 * More frags after this one.  Get another copy
24533 			 * of the header.
24534 			 */
24535 			if (carve_mp->b_datap->db_ref == 1 &&
24536 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24537 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24538 				/* Inline IP header */
24539 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24540 				    hdr_mp->b_rptr;
24541 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24542 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24543 				mp = carve_mp;
24544 			} else {
24545 				if (!(mp = copyb(hdr_mp))) {
24546 					freemsg(carve_mp);
24547 					break;
24548 				}
24549 				/* Get priority marking, if any. */
24550 				mp->b_band = carve_mp->b_band;
24551 				mp->b_cont = carve_mp;
24552 			}
24553 			ipha = (ipha_t *)mp->b_rptr;
24554 			offset_and_flags = IPH_MF;
24555 		} else {
24556 			/*
24557 			 * Last frag.  Consume the header. Set len to
24558 			 * the length of this last piece.
24559 			 */
24560 			len = ip_data_end - offset;
24561 
24562 			/*
24563 			 * Carve off the appropriate amount from the original
24564 			 * datagram.
24565 			 */
24566 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24567 				mp = NULL;
24568 				break;
24569 			}
24570 			if (carve_mp->b_datap->db_ref == 1 &&
24571 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24572 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24573 				/* Inline IP header */
24574 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24575 				    hdr_mp->b_rptr;
24576 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24577 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24578 				mp = carve_mp;
24579 				freeb(hdr_mp);
24580 				hdr_mp = mp;
24581 			} else {
24582 				mp = hdr_mp;
24583 				/* Get priority marking, if any. */
24584 				mp->b_band = carve_mp->b_band;
24585 				mp->b_cont = carve_mp;
24586 			}
24587 			ipha = (ipha_t *)mp->b_rptr;
24588 			/* A frag of a frag might have IPH_MF non-zero */
24589 			offset_and_flags =
24590 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24591 			    IPH_MF;
24592 		}
24593 		offset_and_flags |= (uint16_t)(offset >> 3);
24594 		offset_and_flags |= (uint16_t)frag_flag;
24595 		/* Store the offset and flags in the IP header. */
24596 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24597 
24598 		/* Store the length in the IP header. */
24599 		ip_len = (uint16_t)(len + hdr_len);
24600 		ipha->ipha_length = htons(ip_len);
24601 
24602 		/*
24603 		 * Set the IP header checksum.	Note that mp is just
24604 		 * the header, so this is easy to pass to ip_csum.
24605 		 */
24606 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24607 
24608 		/* Attach a transmit header, if any, and ship it. */
24609 		if (pkt_type == OB_PKT) {
24610 			UPDATE_OB_PKT_COUNT(ire);
24611 		} else {
24612 			out_ill = (ill_t *)q->q_ptr;
24613 			BUMP_MIB(out_ill->ill_ip_mib,
24614 			    ipIfStatsHCOutForwDatagrams);
24615 			UPDATE_IB_PKT_COUNT(ire);
24616 		}
24617 
24618 		if (ire->ire_flags & RTF_MULTIRT) {
24619 			irb = ire->ire_bucket;
24620 			ASSERT(irb != NULL);
24621 
24622 			multirt_send = B_TRUE;
24623 
24624 			/*
24625 			 * Save the original ire; we will need to restore it
24626 			 * for the tailing frags.
24627 			 */
24628 			save_ire = ire;
24629 			IRE_REFHOLD(save_ire);
24630 		}
24631 		/*
24632 		 * Emission loop for this fragment, similar
24633 		 * to what is done for the first fragment.
24634 		 */
24635 		do {
24636 			if (multirt_send) {
24637 				/*
24638 				 * We are in a multiple send case, need to get
24639 				 * the next ire and make a copy of the packet.
24640 				 */
24641 				ASSERT(irb != NULL);
24642 				IRB_REFHOLD(irb);
24643 				for (ire1 = ire->ire_next;
24644 				    ire1 != NULL;
24645 				    ire1 = ire1->ire_next) {
24646 					if (!(ire1->ire_flags & RTF_MULTIRT))
24647 						continue;
24648 					if (ire1->ire_addr != ire->ire_addr)
24649 						continue;
24650 					if (ire1->ire_marks &
24651 					    (IRE_MARK_CONDEMNED |
24652 					    IRE_MARK_TESTHIDDEN))
24653 						continue;
24654 					/*
24655 					 * Ensure we do not exceed the MTU
24656 					 * of the next route.
24657 					 */
24658 					if (ire1->ire_max_frag < max_frag) {
24659 						ip_multirt_bad_mtu(ire1,
24660 						    max_frag);
24661 						continue;
24662 					}
24663 
24664 					/* Got one. */
24665 					IRE_REFHOLD(ire1);
24666 					break;
24667 				}
24668 				IRB_REFRELE(irb);
24669 
24670 				if (ire1 != NULL) {
24671 					next_mp = copyb(mp);
24672 					if ((next_mp == NULL) ||
24673 					    ((mp->b_cont != NULL) &&
24674 					    ((next_mp->b_cont =
24675 					    dupmsg(mp->b_cont)) == NULL))) {
24676 						freemsg(next_mp);
24677 						next_mp = NULL;
24678 						ire_refrele(ire1);
24679 						ire1 = NULL;
24680 					}
24681 				}
24682 
24683 				/* Last multiroute ire; don't loop anymore. */
24684 				if (ire1 == NULL) {
24685 					multirt_send = B_FALSE;
24686 				}
24687 			}
24688 
24689 			/* Update transmit header */
24690 			ll_hdr_len = 0;
24691 			LOCK_IRE_FP_MP(ire);
24692 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24693 			if (ll_hdr_mp != NULL) {
24694 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24695 				ll_hdr_len = MBLKL(ll_hdr_mp);
24696 			} else {
24697 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24698 			}
24699 
24700 			if (!ll_hdr_mp) {
24701 				xmit_mp = mp;
24702 
24703 			/*
24704 			 * We have link-layer header that can fit in
24705 			 * our mblk.
24706 			 */
24707 			} else if (mp->b_datap->db_ref == 1 &&
24708 			    ll_hdr_len != 0 &&
24709 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24710 				/* M_DATA fastpath */
24711 				mp->b_rptr -= ll_hdr_len;
24712 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24713 				    ll_hdr_len);
24714 				xmit_mp = mp;
24715 
24716 			/*
24717 			 * Case of res_mp OR the fastpath mp can't fit
24718 			 * in the mblk
24719 			 */
24720 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24721 				xmit_mp->b_cont = mp;
24722 				/* Get priority marking, if any. */
24723 				if (DB_TYPE(xmit_mp) == M_DATA)
24724 					xmit_mp->b_band = mp->b_band;
24725 
24726 			/* Corner case if copyb failed */
24727 			} else {
24728 				/*
24729 				 * Exit both the replication and
24730 				 * fragmentation loops.
24731 				 */
24732 				UNLOCK_IRE_FP_MP(ire);
24733 				goto drop_pkt;
24734 			}
24735 			UNLOCK_IRE_FP_MP(ire);
24736 
24737 			mp1 = mp;
24738 			out_ill = (ill_t *)q->q_ptr;
24739 
24740 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24741 
24742 			DTRACE_PROBE4(ip4__physical__out__start,
24743 			    ill_t *, NULL, ill_t *, out_ill,
24744 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24745 
24746 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24747 			    ipst->ips_ipv4firewall_physical_out,
24748 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24749 
24750 			DTRACE_PROBE1(ip4__physical__out__end,
24751 			    mblk_t *, xmit_mp);
24752 
24753 			if (mp != mp1 && hdr_mp == mp1)
24754 				hdr_mp = mp;
24755 			if (mp != mp1 && mp_orig == mp1)
24756 				mp_orig = mp;
24757 
24758 			if (xmit_mp != NULL) {
24759 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24760 				    NULL, void_ip_t *, ipha,
24761 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24762 				    ipha, ip6_t *, NULL, int, 0);
24763 
24764 				ILL_SEND_TX(out_ill, ire, connp,
24765 				    xmit_mp, 0, connp);
24766 
24767 				BUMP_MIB(out_ill->ill_ip_mib,
24768 				    ipIfStatsHCOutTransmits);
24769 				UPDATE_MIB(out_ill->ill_ip_mib,
24770 				    ipIfStatsHCOutOctets, ip_len);
24771 
24772 				if (pkt_type != OB_PKT) {
24773 					/*
24774 					 * Update the packet count of trailing
24775 					 * RTF_MULTIRT ires.
24776 					 */
24777 					UPDATE_OB_PKT_COUNT(ire);
24778 				}
24779 			}
24780 
24781 			/* All done if we just consumed the hdr_mp. */
24782 			if (mp == hdr_mp) {
24783 				last_frag = B_TRUE;
24784 				BUMP_MIB(out_ill->ill_ip_mib,
24785 				    ipIfStatsOutFragOKs);
24786 			}
24787 
24788 			if (multirt_send) {
24789 				/*
24790 				 * We are in a multiple send case; look for
24791 				 * the next ire and re-enter the loop.
24792 				 */
24793 				ASSERT(ire1);
24794 				ASSERT(next_mp);
24795 				/* REFRELE the current ire before looping */
24796 				ire_refrele(ire);
24797 				ire = ire1;
24798 				ire1 = NULL;
24799 				q = ire->ire_stq;
24800 				mp = next_mp;
24801 				next_mp = NULL;
24802 			}
24803 		} while (multirt_send);
24804 		/*
24805 		 * Restore the original ire; we need it for the
24806 		 * trailing frags
24807 		 */
24808 		if (save_ire != NULL) {
24809 			ASSERT(ire1 == NULL);
24810 			/* REFRELE the last iterated ire */
24811 			ire_refrele(ire);
24812 			/* save_ire has been REFHOLDed */
24813 			ire = save_ire;
24814 			q = ire->ire_stq;
24815 			save_ire = NULL;
24816 		}
24817 
24818 		if (last_frag) {
24819 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24820 			    "ip_wput_frag_end:(%S)",
24821 			    "consumed hdr_mp");
24822 
24823 			if (first_ire != NULL)
24824 				ire_refrele(first_ire);
24825 			return;
24826 		}
24827 		/* Otherwise, advance and loop. */
24828 		offset += len;
24829 	}
24830 
24831 drop_pkt:
24832 	/* Clean up following allocation failure. */
24833 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24834 	freemsg(mp);
24835 	if (mp != hdr_mp)
24836 		freeb(hdr_mp);
24837 	if (mp != mp_orig)
24838 		freemsg(mp_orig);
24839 
24840 	if (save_ire != NULL)
24841 		IRE_REFRELE(save_ire);
24842 	if (first_ire != NULL)
24843 		ire_refrele(first_ire);
24844 
24845 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24846 	    "ip_wput_frag_end:(%S)",
24847 	    "end--alloc failure");
24848 }
24849 
24850 /*
24851  * Copy the header plus those options which have the copy bit set
24852  * src is the template to make sure we preserve the cred for TX purposes.
24853  */
24854 static mblk_t *
24855 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24856     mblk_t *src)
24857 {
24858 	mblk_t	*mp;
24859 	uchar_t	*up;
24860 
24861 	/*
24862 	 * Quick check if we need to look for options without the copy bit
24863 	 * set
24864 	 */
24865 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24866 	if (!mp)
24867 		return (mp);
24868 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24869 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24870 		bcopy(rptr, mp->b_rptr, hdr_len);
24871 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24872 		return (mp);
24873 	}
24874 	up  = mp->b_rptr;
24875 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24876 	up += IP_SIMPLE_HDR_LENGTH;
24877 	rptr += IP_SIMPLE_HDR_LENGTH;
24878 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24879 	while (hdr_len > 0) {
24880 		uint32_t optval;
24881 		uint32_t optlen;
24882 
24883 		optval = *rptr;
24884 		if (optval == IPOPT_EOL)
24885 			break;
24886 		if (optval == IPOPT_NOP)
24887 			optlen = 1;
24888 		else
24889 			optlen = rptr[1];
24890 		if (optval & IPOPT_COPY) {
24891 			bcopy(rptr, up, optlen);
24892 			up += optlen;
24893 		}
24894 		rptr += optlen;
24895 		hdr_len -= optlen;
24896 	}
24897 	/*
24898 	 * Make sure that we drop an even number of words by filling
24899 	 * with EOL to the next word boundary.
24900 	 */
24901 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24902 	    hdr_len & 0x3; hdr_len++)
24903 		*up++ = IPOPT_EOL;
24904 	mp->b_wptr = up;
24905 	/* Update header length */
24906 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24907 	return (mp);
24908 }
24909 
24910 /*
24911  * Delivery to local recipients including fanout to multiple recipients.
24912  * Does not do checksumming of UDP/TCP.
24913  * Note: q should be the read side queue for either the ill or conn.
24914  * Note: rq should be the read side q for the lower (ill) stream.
24915  * We don't send packets to IPPF processing, thus the last argument
24916  * to all the fanout calls are B_FALSE.
24917  */
24918 void
24919 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24920     int fanout_flags, zoneid_t zoneid)
24921 {
24922 	uint32_t	protocol;
24923 	mblk_t		*first_mp;
24924 	boolean_t	mctl_present;
24925 	int		ire_type;
24926 #define	rptr	((uchar_t *)ipha)
24927 	ip_stack_t	*ipst = ill->ill_ipst;
24928 
24929 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24930 	    "ip_wput_local_start: q %p", q);
24931 
24932 	if (ire != NULL) {
24933 		ire_type = ire->ire_type;
24934 	} else {
24935 		/*
24936 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24937 		 * packet is not multicast, we can't tell the ire type.
24938 		 */
24939 		ASSERT(CLASSD(ipha->ipha_dst));
24940 		ire_type = IRE_BROADCAST;
24941 	}
24942 
24943 	first_mp = mp;
24944 	if (first_mp->b_datap->db_type == M_CTL) {
24945 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24946 		if (!io->ipsec_out_secure) {
24947 			/*
24948 			 * This ipsec_out_t was allocated in ip_wput
24949 			 * for multicast packets to store the ill_index.
24950 			 * As this is being delivered locally, we don't
24951 			 * need this anymore.
24952 			 */
24953 			mp = first_mp->b_cont;
24954 			freeb(first_mp);
24955 			first_mp = mp;
24956 			mctl_present = B_FALSE;
24957 		} else {
24958 			/*
24959 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24960 			 * security properties for the looped-back packet.
24961 			 */
24962 			mctl_present = B_TRUE;
24963 			mp = first_mp->b_cont;
24964 			ASSERT(mp != NULL);
24965 			ipsec_out_to_in(first_mp);
24966 		}
24967 	} else {
24968 		mctl_present = B_FALSE;
24969 	}
24970 
24971 	DTRACE_PROBE4(ip4__loopback__in__start,
24972 	    ill_t *, ill, ill_t *, NULL,
24973 	    ipha_t *, ipha, mblk_t *, first_mp);
24974 
24975 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24976 	    ipst->ips_ipv4firewall_loopback_in,
24977 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24978 
24979 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24980 
24981 	if (first_mp == NULL)
24982 		return;
24983 
24984 	if (ipst->ips_ip4_observe.he_interested) {
24985 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
24986 		zoneid_t stackzoneid = netstackid_to_zoneid(
24987 		    ipst->ips_netstack->netstack_stackid);
24988 
24989 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
24990 		/*
24991 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
24992 		 * address.  Restrict the lookup below to the destination zone.
24993 		 */
24994 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
24995 			lookup_zoneid = zoneid;
24996 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
24997 		    lookup_zoneid);
24998 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill, ipst);
24999 	}
25000 
25001 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25002 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25003 	    int, 1);
25004 
25005 	ipst->ips_loopback_packets++;
25006 
25007 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25008 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25009 	if (!IS_SIMPLE_IPH(ipha)) {
25010 		ip_wput_local_options(ipha, ipst);
25011 	}
25012 
25013 	protocol = ipha->ipha_protocol;
25014 	switch (protocol) {
25015 	case IPPROTO_ICMP: {
25016 		ire_t		*ire_zone;
25017 		ilm_t		*ilm;
25018 		mblk_t		*mp1;
25019 		zoneid_t	last_zoneid;
25020 		ilm_walker_t	ilw;
25021 
25022 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25023 			ASSERT(ire_type == IRE_BROADCAST);
25024 			/*
25025 			 * In the multicast case, applications may have joined
25026 			 * the group from different zones, so we need to deliver
25027 			 * the packet to each of them. Loop through the
25028 			 * multicast memberships structures (ilm) on the receive
25029 			 * ill and send a copy of the packet up each matching
25030 			 * one. However, we don't do this for multicasts sent on
25031 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25032 			 * they must stay in the sender's zone.
25033 			 *
25034 			 * ilm_add_v6() ensures that ilms in the same zone are
25035 			 * contiguous in the ill_ilm list. We use this property
25036 			 * to avoid sending duplicates needed when two
25037 			 * applications in the same zone join the same group on
25038 			 * different logical interfaces: we ignore the ilm if
25039 			 * it's zoneid is the same as the last matching one.
25040 			 * In addition, the sending of the packet for
25041 			 * ire_zoneid is delayed until all of the other ilms
25042 			 * have been exhausted.
25043 			 */
25044 			last_zoneid = -1;
25045 			ilm = ilm_walker_start(&ilw, ill);
25046 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25047 				if (ipha->ipha_dst != ilm->ilm_addr ||
25048 				    ilm->ilm_zoneid == last_zoneid ||
25049 				    ilm->ilm_zoneid == zoneid ||
25050 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25051 					continue;
25052 				mp1 = ip_copymsg(first_mp);
25053 				if (mp1 == NULL)
25054 					continue;
25055 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25056 				    0, 0, mctl_present, B_FALSE, ill,
25057 				    ilm->ilm_zoneid);
25058 				last_zoneid = ilm->ilm_zoneid;
25059 			}
25060 			ilm_walker_finish(&ilw);
25061 			/*
25062 			 * Loopback case: the sending endpoint has
25063 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25064 			 * dispatch the multicast packet to the sending zone.
25065 			 */
25066 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25067 				freemsg(first_mp);
25068 				return;
25069 			}
25070 		} else if (ire_type == IRE_BROADCAST) {
25071 			/*
25072 			 * In the broadcast case, there may be many zones
25073 			 * which need a copy of the packet delivered to them.
25074 			 * There is one IRE_BROADCAST per broadcast address
25075 			 * and per zone; we walk those using a helper function.
25076 			 * In addition, the sending of the packet for zoneid is
25077 			 * delayed until all of the other ires have been
25078 			 * processed.
25079 			 */
25080 			IRB_REFHOLD(ire->ire_bucket);
25081 			ire_zone = NULL;
25082 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25083 			    ire)) != NULL) {
25084 				mp1 = ip_copymsg(first_mp);
25085 				if (mp1 == NULL)
25086 					continue;
25087 
25088 				UPDATE_IB_PKT_COUNT(ire_zone);
25089 				ire_zone->ire_last_used_time = lbolt;
25090 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25091 				    mctl_present, B_FALSE, ill,
25092 				    ire_zone->ire_zoneid);
25093 			}
25094 			IRB_REFRELE(ire->ire_bucket);
25095 		}
25096 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25097 		    0, mctl_present, B_FALSE, ill, zoneid);
25098 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25099 		    "ip_wput_local_end: q %p (%S)",
25100 		    q, "icmp");
25101 		return;
25102 	}
25103 	case IPPROTO_IGMP:
25104 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25105 			/* Bad packet - discarded by igmp_input */
25106 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25107 			    "ip_wput_local_end: q %p (%S)",
25108 			    q, "igmp_input--bad packet");
25109 			if (mctl_present)
25110 				freeb(first_mp);
25111 			return;
25112 		}
25113 		/*
25114 		 * igmp_input() may have returned the pulled up message.
25115 		 * So first_mp and ipha need to be reinitialized.
25116 		 */
25117 		ipha = (ipha_t *)mp->b_rptr;
25118 		if (mctl_present)
25119 			first_mp->b_cont = mp;
25120 		else
25121 			first_mp = mp;
25122 		/* deliver to local raw users */
25123 		break;
25124 	case IPPROTO_ENCAP:
25125 		/*
25126 		 * This case is covered by either ip_fanout_proto, or by
25127 		 * the above security processing for self-tunneled packets.
25128 		 */
25129 		break;
25130 	case IPPROTO_UDP: {
25131 		uint16_t	*up;
25132 		uint32_t	ports;
25133 
25134 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25135 		    UDP_PORTS_OFFSET);
25136 		/* Force a 'valid' checksum. */
25137 		up[3] = 0;
25138 
25139 		ports = *(uint32_t *)up;
25140 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25141 		    (ire_type == IRE_BROADCAST),
25142 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25143 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25144 		    ill, zoneid);
25145 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25146 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25147 		return;
25148 	}
25149 	case IPPROTO_TCP: {
25150 
25151 		/*
25152 		 * For TCP, discard broadcast packets.
25153 		 */
25154 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25155 			freemsg(first_mp);
25156 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25157 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25158 			return;
25159 		}
25160 
25161 		if (mp->b_datap->db_type == M_DATA) {
25162 			/*
25163 			 * M_DATA mblk, so init mblk (chain) for no struio().
25164 			 */
25165 			mblk_t	*mp1 = mp;
25166 
25167 			do {
25168 				mp1->b_datap->db_struioflag = 0;
25169 			} while ((mp1 = mp1->b_cont) != NULL);
25170 		}
25171 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25172 		    <= mp->b_wptr);
25173 		ip_fanout_tcp(q, first_mp, ill, ipha,
25174 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25175 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25176 		    mctl_present, B_FALSE, zoneid);
25177 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25178 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25179 		return;
25180 	}
25181 	case IPPROTO_SCTP:
25182 	{
25183 		uint32_t	ports;
25184 
25185 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25186 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25187 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25188 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25189 		return;
25190 	}
25191 
25192 	default:
25193 		break;
25194 	}
25195 	/*
25196 	 * Find a client for some other protocol.  We give
25197 	 * copies to multiple clients, if more than one is
25198 	 * bound.
25199 	 */
25200 	ip_fanout_proto(q, first_mp, ill, ipha,
25201 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25202 	    mctl_present, B_FALSE, ill, zoneid);
25203 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25204 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25205 #undef	rptr
25206 }
25207 
25208 /*
25209  * Update any source route, record route, or timestamp options.
25210  * Check that we are at end of strict source route.
25211  * The options have been sanity checked by ip_wput_options().
25212  */
25213 static void
25214 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25215 {
25216 	ipoptp_t	opts;
25217 	uchar_t		*opt;
25218 	uint8_t		optval;
25219 	uint8_t		optlen;
25220 	ipaddr_t	dst;
25221 	uint32_t	ts;
25222 	ire_t		*ire;
25223 	timestruc_t	now;
25224 
25225 	ip2dbg(("ip_wput_local_options\n"));
25226 	for (optval = ipoptp_first(&opts, ipha);
25227 	    optval != IPOPT_EOL;
25228 	    optval = ipoptp_next(&opts)) {
25229 		opt = opts.ipoptp_cur;
25230 		optlen = opts.ipoptp_len;
25231 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25232 		switch (optval) {
25233 			uint32_t off;
25234 		case IPOPT_SSRR:
25235 		case IPOPT_LSRR:
25236 			off = opt[IPOPT_OFFSET];
25237 			off--;
25238 			if (optlen < IP_ADDR_LEN ||
25239 			    off > optlen - IP_ADDR_LEN) {
25240 				/* End of source route */
25241 				break;
25242 			}
25243 			/*
25244 			 * This will only happen if two consecutive entries
25245 			 * in the source route contains our address or if
25246 			 * it is a packet with a loose source route which
25247 			 * reaches us before consuming the whole source route
25248 			 */
25249 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25250 			if (optval == IPOPT_SSRR) {
25251 				return;
25252 			}
25253 			/*
25254 			 * Hack: instead of dropping the packet truncate the
25255 			 * source route to what has been used by filling the
25256 			 * rest with IPOPT_NOP.
25257 			 */
25258 			opt[IPOPT_OLEN] = (uint8_t)off;
25259 			while (off < optlen) {
25260 				opt[off++] = IPOPT_NOP;
25261 			}
25262 			break;
25263 		case IPOPT_RR:
25264 			off = opt[IPOPT_OFFSET];
25265 			off--;
25266 			if (optlen < IP_ADDR_LEN ||
25267 			    off > optlen - IP_ADDR_LEN) {
25268 				/* No more room - ignore */
25269 				ip1dbg((
25270 				    "ip_wput_forward_options: end of RR\n"));
25271 				break;
25272 			}
25273 			dst = htonl(INADDR_LOOPBACK);
25274 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25275 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25276 			break;
25277 		case IPOPT_TS:
25278 			/* Insert timestamp if there is romm */
25279 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25280 			case IPOPT_TS_TSONLY:
25281 				off = IPOPT_TS_TIMELEN;
25282 				break;
25283 			case IPOPT_TS_PRESPEC:
25284 			case IPOPT_TS_PRESPEC_RFC791:
25285 				/* Verify that the address matched */
25286 				off = opt[IPOPT_OFFSET] - 1;
25287 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25288 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25289 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25290 				    ipst);
25291 				if (ire == NULL) {
25292 					/* Not for us */
25293 					break;
25294 				}
25295 				ire_refrele(ire);
25296 				/* FALLTHRU */
25297 			case IPOPT_TS_TSANDADDR:
25298 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25299 				break;
25300 			default:
25301 				/*
25302 				 * ip_*put_options should have already
25303 				 * dropped this packet.
25304 				 */
25305 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25306 				    "unknown IT - bug in ip_wput_options?\n");
25307 				return;	/* Keep "lint" happy */
25308 			}
25309 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25310 				/* Increase overflow counter */
25311 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25312 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25313 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25314 				    (off << 4);
25315 				break;
25316 			}
25317 			off = opt[IPOPT_OFFSET] - 1;
25318 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25319 			case IPOPT_TS_PRESPEC:
25320 			case IPOPT_TS_PRESPEC_RFC791:
25321 			case IPOPT_TS_TSANDADDR:
25322 				dst = htonl(INADDR_LOOPBACK);
25323 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25324 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25325 				/* FALLTHRU */
25326 			case IPOPT_TS_TSONLY:
25327 				off = opt[IPOPT_OFFSET] - 1;
25328 				/* Compute # of milliseconds since midnight */
25329 				gethrestime(&now);
25330 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25331 				    now.tv_nsec / (NANOSEC / MILLISEC);
25332 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25333 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25334 				break;
25335 			}
25336 			break;
25337 		}
25338 	}
25339 }
25340 
25341 /*
25342  * Send out a multicast packet on interface ipif.
25343  * The sender does not have an conn.
25344  * Caller verifies that this isn't a PHYI_LOOPBACK.
25345  */
25346 void
25347 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25348 {
25349 	ipha_t	*ipha;
25350 	ire_t	*ire;
25351 	ipaddr_t	dst;
25352 	mblk_t		*first_mp;
25353 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25354 
25355 	/* igmp_sendpkt always allocates a ipsec_out_t */
25356 	ASSERT(mp->b_datap->db_type == M_CTL);
25357 	ASSERT(!ipif->ipif_isv6);
25358 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25359 
25360 	first_mp = mp;
25361 	mp = first_mp->b_cont;
25362 	ASSERT(mp->b_datap->db_type == M_DATA);
25363 	ipha = (ipha_t *)mp->b_rptr;
25364 
25365 	/*
25366 	 * Find an IRE which matches the destination and the outgoing
25367 	 * queue (i.e. the outgoing interface.)
25368 	 */
25369 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25370 		dst = ipif->ipif_pp_dst_addr;
25371 	else
25372 		dst = ipha->ipha_dst;
25373 	/*
25374 	 * The source address has already been initialized by the
25375 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25376 	 * be sufficient rather than MATCH_IRE_IPIF.
25377 	 *
25378 	 * This function is used for sending IGMP packets.  For IPMP,
25379 	 * we sidestep IGMP snooping issues by sending all multicast
25380 	 * traffic on a single interface in the IPMP group.
25381 	 */
25382 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25383 	    MATCH_IRE_ILL, ipst);
25384 	if (!ire) {
25385 		/*
25386 		 * Mark this packet to make it be delivered to
25387 		 * ip_wput_ire after the new ire has been
25388 		 * created.
25389 		 */
25390 		mp->b_prev = NULL;
25391 		mp->b_next = NULL;
25392 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25393 		    zoneid, &zero_info);
25394 		return;
25395 	}
25396 
25397 	/*
25398 	 * Honor the RTF_SETSRC flag; this is the only case
25399 	 * where we force this addr whatever the current src addr is,
25400 	 * because this address is set by igmp_sendpkt(), and
25401 	 * cannot be specified by any user.
25402 	 */
25403 	if (ire->ire_flags & RTF_SETSRC) {
25404 		ipha->ipha_src = ire->ire_src_addr;
25405 	}
25406 
25407 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25408 }
25409 
25410 /*
25411  * NOTE : This function does not ire_refrele the ire argument passed in.
25412  *
25413  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25414  * failure. The nce_fp_mp can vanish any time in the case of
25415  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25416  * the ire_lock to access the nce_fp_mp in this case.
25417  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25418  * prepending a fastpath message IPQoS processing must precede it, we also set
25419  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25420  * (IPQoS might have set the b_band for CoS marking).
25421  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25422  * must follow it so that IPQoS can mark the dl_priority field for CoS
25423  * marking, if needed.
25424  */
25425 static mblk_t *
25426 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25427     uint32_t ill_index, ipha_t **iphap)
25428 {
25429 	uint_t	hlen;
25430 	ipha_t *ipha;
25431 	mblk_t *mp1;
25432 	boolean_t qos_done = B_FALSE;
25433 	uchar_t	*ll_hdr;
25434 	ip_stack_t	*ipst = ire->ire_ipst;
25435 
25436 #define	rptr	((uchar_t *)ipha)
25437 
25438 	ipha = (ipha_t *)mp->b_rptr;
25439 	hlen = 0;
25440 	LOCK_IRE_FP_MP(ire);
25441 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25442 		ASSERT(DB_TYPE(mp1) == M_DATA);
25443 		/* Initiate IPPF processing */
25444 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25445 			UNLOCK_IRE_FP_MP(ire);
25446 			ip_process(proc, &mp, ill_index);
25447 			if (mp == NULL)
25448 				return (NULL);
25449 
25450 			ipha = (ipha_t *)mp->b_rptr;
25451 			LOCK_IRE_FP_MP(ire);
25452 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25453 				qos_done = B_TRUE;
25454 				goto no_fp_mp;
25455 			}
25456 			ASSERT(DB_TYPE(mp1) == M_DATA);
25457 		}
25458 		hlen = MBLKL(mp1);
25459 		/*
25460 		 * Check if we have enough room to prepend fastpath
25461 		 * header
25462 		 */
25463 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25464 			ll_hdr = rptr - hlen;
25465 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25466 			/*
25467 			 * Set the b_rptr to the start of the link layer
25468 			 * header
25469 			 */
25470 			mp->b_rptr = ll_hdr;
25471 			mp1 = mp;
25472 		} else {
25473 			mp1 = copyb(mp1);
25474 			if (mp1 == NULL)
25475 				goto unlock_err;
25476 			mp1->b_band = mp->b_band;
25477 			mp1->b_cont = mp;
25478 			/*
25479 			 * XXX disable ICK_VALID and compute checksum
25480 			 * here; can happen if nce_fp_mp changes and
25481 			 * it can't be copied now due to insufficient
25482 			 * space. (unlikely, fp mp can change, but it
25483 			 * does not increase in length)
25484 			 */
25485 		}
25486 		UNLOCK_IRE_FP_MP(ire);
25487 	} else {
25488 no_fp_mp:
25489 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25490 		if (mp1 == NULL) {
25491 unlock_err:
25492 			UNLOCK_IRE_FP_MP(ire);
25493 			freemsg(mp);
25494 			return (NULL);
25495 		}
25496 		UNLOCK_IRE_FP_MP(ire);
25497 		mp1->b_cont = mp;
25498 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25499 			ip_process(proc, &mp1, ill_index);
25500 			if (mp1 == NULL)
25501 				return (NULL);
25502 
25503 			if (mp1->b_cont == NULL)
25504 				ipha = NULL;
25505 			else
25506 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25507 		}
25508 	}
25509 
25510 	*iphap = ipha;
25511 	return (mp1);
25512 #undef rptr
25513 }
25514 
25515 /*
25516  * Finish the outbound IPsec processing for an IPv6 packet. This function
25517  * is called from ipsec_out_process() if the IPsec packet was processed
25518  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25519  * asynchronously.
25520  */
25521 void
25522 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25523     ire_t *ire_arg)
25524 {
25525 	in6_addr_t *v6dstp;
25526 	ire_t *ire;
25527 	mblk_t *mp;
25528 	ip6_t *ip6h1;
25529 	uint_t	ill_index;
25530 	ipsec_out_t *io;
25531 	boolean_t hwaccel;
25532 	uint32_t flags = IP6_NO_IPPOLICY;
25533 	int match_flags;
25534 	zoneid_t zoneid;
25535 	boolean_t ill_need_rele = B_FALSE;
25536 	boolean_t ire_need_rele = B_FALSE;
25537 	ip_stack_t	*ipst;
25538 
25539 	mp = ipsec_mp->b_cont;
25540 	ip6h1 = (ip6_t *)mp->b_rptr;
25541 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25542 	ASSERT(io->ipsec_out_ns != NULL);
25543 	ipst = io->ipsec_out_ns->netstack_ip;
25544 	ill_index = io->ipsec_out_ill_index;
25545 	if (io->ipsec_out_reachable) {
25546 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25547 	}
25548 	hwaccel = io->ipsec_out_accelerated;
25549 	zoneid = io->ipsec_out_zoneid;
25550 	ASSERT(zoneid != ALL_ZONES);
25551 	ASSERT(IPH_HDR_VERSION(ip6h) == IPV6_VERSION);
25552 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25553 	/* Multicast addresses should have non-zero ill_index. */
25554 	v6dstp = &ip6h->ip6_dst;
25555 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25556 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25557 
25558 	if (ill == NULL && ill_index != 0) {
25559 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25560 		/* Failure case frees things for us. */
25561 		if (ill == NULL)
25562 			return;
25563 
25564 		ill_need_rele = B_TRUE;
25565 	}
25566 	ASSERT(mp != NULL);
25567 
25568 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25569 		boolean_t unspec_src;
25570 		ipif_t	*ipif;
25571 
25572 		/*
25573 		 * Use the ill_index to get the right ill.
25574 		 */
25575 		unspec_src = io->ipsec_out_unspec_src;
25576 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25577 		if (ipif == NULL) {
25578 			if (ill_need_rele)
25579 				ill_refrele(ill);
25580 			freemsg(ipsec_mp);
25581 			return;
25582 		}
25583 
25584 		if (ire_arg != NULL) {
25585 			ire = ire_arg;
25586 		} else {
25587 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25588 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25589 			ire_need_rele = B_TRUE;
25590 		}
25591 		if (ire != NULL) {
25592 			ipif_refrele(ipif);
25593 			/*
25594 			 * XXX Do the multicast forwarding now, as the IPsec
25595 			 * processing has been done.
25596 			 */
25597 			goto send;
25598 		}
25599 
25600 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25601 		mp->b_prev = NULL;
25602 		mp->b_next = NULL;
25603 
25604 		/*
25605 		 * If the IPsec packet was processed asynchronously,
25606 		 * drop it now.
25607 		 */
25608 		if (q == NULL) {
25609 			if (ill_need_rele)
25610 				ill_refrele(ill);
25611 			freemsg(ipsec_mp);
25612 			ipif_refrele(ipif);
25613 			return;
25614 		}
25615 
25616 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25617 		    unspec_src, zoneid);
25618 		ipif_refrele(ipif);
25619 	} else {
25620 		if (ire_arg != NULL) {
25621 			ire = ire_arg;
25622 		} else {
25623 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25624 			ire_need_rele = B_TRUE;
25625 		}
25626 		if (ire != NULL)
25627 			goto send;
25628 		/*
25629 		 * ire disappeared underneath.
25630 		 *
25631 		 * What we need to do here is the ip_newroute
25632 		 * logic to get the ire without doing the IPsec
25633 		 * processing. Follow the same old path. But this
25634 		 * time, ip_wput or ire_add_then_send will call us
25635 		 * directly as all the IPsec operations are done.
25636 		 */
25637 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25638 		mp->b_prev = NULL;
25639 		mp->b_next = NULL;
25640 
25641 		/*
25642 		 * If the IPsec packet was processed asynchronously,
25643 		 * drop it now.
25644 		 */
25645 		if (q == NULL) {
25646 			if (ill_need_rele)
25647 				ill_refrele(ill);
25648 			freemsg(ipsec_mp);
25649 			return;
25650 		}
25651 
25652 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25653 		    zoneid, ipst);
25654 	}
25655 	if (ill != NULL && ill_need_rele)
25656 		ill_refrele(ill);
25657 	return;
25658 send:
25659 	if (ill != NULL && ill_need_rele)
25660 		ill_refrele(ill);
25661 
25662 	/* Local delivery */
25663 	if (ire->ire_stq == NULL) {
25664 		ill_t	*out_ill;
25665 		ASSERT(q != NULL);
25666 
25667 		/* PFHooks: LOOPBACK_OUT */
25668 		out_ill = ire_to_ill(ire);
25669 
25670 		/*
25671 		 * DTrace this as ip:::send.  A blocked packet will fire the
25672 		 * send probe, but not the receive probe.
25673 		 */
25674 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25675 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25676 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25677 
25678 		DTRACE_PROBE4(ip6__loopback__out__start,
25679 		    ill_t *, NULL, ill_t *, out_ill,
25680 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25681 
25682 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25683 		    ipst->ips_ipv6firewall_loopback_out,
25684 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25685 
25686 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25687 
25688 		if (ipsec_mp != NULL) {
25689 			ip_wput_local_v6(RD(q), out_ill,
25690 			    ip6h, ipsec_mp, ire, 0, zoneid);
25691 		}
25692 		if (ire_need_rele)
25693 			ire_refrele(ire);
25694 		return;
25695 	}
25696 	/*
25697 	 * Everything is done. Send it out on the wire.
25698 	 * We force the insertion of a fragment header using the
25699 	 * IPH_FRAG_HDR flag in two cases:
25700 	 * - after reception of an ICMPv6 "packet too big" message
25701 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25702 	 * - for multirouted IPv6 packets, so that the receiver can
25703 	 *   discard duplicates according to their fragment identifier
25704 	 */
25705 	/* XXX fix flow control problems. */
25706 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25707 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25708 		if (hwaccel) {
25709 			/*
25710 			 * hardware acceleration does not handle these
25711 			 * "slow path" cases.
25712 			 */
25713 			/* IPsec KSTATS: should bump bean counter here. */
25714 			if (ire_need_rele)
25715 				ire_refrele(ire);
25716 			freemsg(ipsec_mp);
25717 			return;
25718 		}
25719 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25720 		    (mp->b_cont ? msgdsize(mp) :
25721 		    mp->b_wptr - (uchar_t *)ip6h)) {
25722 			/* IPsec KSTATS: should bump bean counter here. */
25723 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25724 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25725 			    msgdsize(mp)));
25726 			if (ire_need_rele)
25727 				ire_refrele(ire);
25728 			freemsg(ipsec_mp);
25729 			return;
25730 		}
25731 		ASSERT(mp->b_prev == NULL);
25732 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25733 		    ntohs(ip6h->ip6_plen) +
25734 		    IPV6_HDR_LEN, ire->ire_max_frag));
25735 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25736 		    ire->ire_max_frag);
25737 	} else {
25738 		UPDATE_OB_PKT_COUNT(ire);
25739 		ire->ire_last_used_time = lbolt;
25740 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25741 	}
25742 	if (ire_need_rele)
25743 		ire_refrele(ire);
25744 	freeb(ipsec_mp);
25745 }
25746 
25747 void
25748 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25749 {
25750 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25751 	da_ipsec_t *hada;	/* data attributes */
25752 	ill_t *ill = (ill_t *)q->q_ptr;
25753 
25754 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25755 
25756 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25757 		/* IPsec KSTATS: Bump lose counter here! */
25758 		freemsg(mp);
25759 		return;
25760 	}
25761 
25762 	/*
25763 	 * It's an IPsec packet that must be
25764 	 * accelerated by the Provider, and the
25765 	 * outbound ill is IPsec acceleration capable.
25766 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25767 	 * to the ill.
25768 	 * IPsec KSTATS: should bump packet counter here.
25769 	 */
25770 
25771 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25772 	if (hada_mp == NULL) {
25773 		/* IPsec KSTATS: should bump packet counter here. */
25774 		freemsg(mp);
25775 		return;
25776 	}
25777 
25778 	hada_mp->b_datap->db_type = M_CTL;
25779 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25780 	hada_mp->b_cont = mp;
25781 
25782 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25783 	bzero(hada, sizeof (da_ipsec_t));
25784 	hada->da_type = IPHADA_M_CTL;
25785 
25786 	putnext(q, hada_mp);
25787 }
25788 
25789 /*
25790  * Finish the outbound IPsec processing. This function is called from
25791  * ipsec_out_process() if the IPsec packet was processed
25792  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25793  * asynchronously.
25794  */
25795 void
25796 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25797     ire_t *ire_arg)
25798 {
25799 	uint32_t v_hlen_tos_len;
25800 	ipaddr_t	dst;
25801 	ipif_t	*ipif = NULL;
25802 	ire_t *ire;
25803 	ire_t *ire1 = NULL;
25804 	mblk_t *next_mp = NULL;
25805 	uint32_t max_frag;
25806 	boolean_t multirt_send = B_FALSE;
25807 	mblk_t *mp;
25808 	ipha_t *ipha1;
25809 	uint_t	ill_index;
25810 	ipsec_out_t *io;
25811 	int match_flags;
25812 	irb_t *irb = NULL;
25813 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25814 	zoneid_t zoneid;
25815 	ipxmit_state_t	pktxmit_state;
25816 	ip_stack_t	*ipst;
25817 
25818 #ifdef	_BIG_ENDIAN
25819 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25820 #else
25821 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25822 #endif
25823 
25824 	mp = ipsec_mp->b_cont;
25825 	ipha1 = (ipha_t *)mp->b_rptr;
25826 	ASSERT(mp != NULL);
25827 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25828 	dst = ipha->ipha_dst;
25829 
25830 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25831 	ill_index = io->ipsec_out_ill_index;
25832 	zoneid = io->ipsec_out_zoneid;
25833 	ASSERT(zoneid != ALL_ZONES);
25834 	ipst = io->ipsec_out_ns->netstack_ip;
25835 	ASSERT(io->ipsec_out_ns != NULL);
25836 
25837 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25838 	if (ill == NULL && ill_index != 0) {
25839 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25840 		/* Failure case frees things for us. */
25841 		if (ill == NULL)
25842 			return;
25843 
25844 		ill_need_rele = B_TRUE;
25845 	}
25846 
25847 	if (CLASSD(dst)) {
25848 		boolean_t conn_dontroute;
25849 		/*
25850 		 * Use the ill_index to get the right ipif.
25851 		 */
25852 		conn_dontroute = io->ipsec_out_dontroute;
25853 		if (ill_index == 0)
25854 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25855 		else
25856 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25857 		if (ipif == NULL) {
25858 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25859 			    " multicast\n"));
25860 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25861 			freemsg(ipsec_mp);
25862 			goto done;
25863 		}
25864 		/*
25865 		 * ipha_src has already been intialized with the
25866 		 * value of the ipif in ip_wput. All we need now is
25867 		 * an ire to send this downstream.
25868 		 */
25869 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25870 		    msg_getlabel(mp), match_flags, ipst);
25871 		if (ire != NULL) {
25872 			ill_t *ill1;
25873 			/*
25874 			 * Do the multicast forwarding now, as the IPsec
25875 			 * processing has been done.
25876 			 */
25877 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25878 			    (ill1 = ire_to_ill(ire))) {
25879 				if (ip_mforward(ill1, ipha, mp)) {
25880 					freemsg(ipsec_mp);
25881 					ip1dbg(("ip_wput_ipsec_out: mforward "
25882 					    "failed\n"));
25883 					ire_refrele(ire);
25884 					goto done;
25885 				}
25886 			}
25887 			goto send;
25888 		}
25889 
25890 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25891 		mp->b_prev = NULL;
25892 		mp->b_next = NULL;
25893 
25894 		/*
25895 		 * If the IPsec packet was processed asynchronously,
25896 		 * drop it now.
25897 		 */
25898 		if (q == NULL) {
25899 			freemsg(ipsec_mp);
25900 			goto done;
25901 		}
25902 
25903 		/*
25904 		 * We may be using a wrong ipif to create the ire.
25905 		 * But it is okay as the source address is assigned
25906 		 * for the packet already. Next outbound packet would
25907 		 * create the IRE with the right IPIF in ip_wput.
25908 		 *
25909 		 * Also handle RTF_MULTIRT routes.
25910 		 */
25911 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25912 		    zoneid, &zero_info);
25913 	} else {
25914 		if (ire_arg != NULL) {
25915 			ire = ire_arg;
25916 			ire_need_rele = B_FALSE;
25917 		} else {
25918 			ire = ire_cache_lookup(dst, zoneid,
25919 			    msg_getlabel(mp), ipst);
25920 		}
25921 		if (ire != NULL) {
25922 			goto send;
25923 		}
25924 
25925 		/*
25926 		 * ire disappeared underneath.
25927 		 *
25928 		 * What we need to do here is the ip_newroute
25929 		 * logic to get the ire without doing the IPsec
25930 		 * processing. Follow the same old path. But this
25931 		 * time, ip_wput or ire_add_then_put will call us
25932 		 * directly as all the IPsec operations are done.
25933 		 */
25934 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25935 		mp->b_prev = NULL;
25936 		mp->b_next = NULL;
25937 
25938 		/*
25939 		 * If the IPsec packet was processed asynchronously,
25940 		 * drop it now.
25941 		 */
25942 		if (q == NULL) {
25943 			freemsg(ipsec_mp);
25944 			goto done;
25945 		}
25946 
25947 		/*
25948 		 * Since we're going through ip_newroute() again, we
25949 		 * need to make sure we don't:
25950 		 *
25951 		 *	1.) Trigger the ASSERT() with the ipha_ident
25952 		 *	    overloading.
25953 		 *	2.) Redo transport-layer checksumming, since we've
25954 		 *	    already done all that to get this far.
25955 		 *
25956 		 * The easiest way not do either of the above is to set
25957 		 * the ipha_ident field to IP_HDR_INCLUDED.
25958 		 */
25959 		ipha->ipha_ident = IP_HDR_INCLUDED;
25960 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25961 		    zoneid, ipst);
25962 	}
25963 	goto done;
25964 send:
25965 	if (ire->ire_stq == NULL) {
25966 		ill_t	*out_ill;
25967 		/*
25968 		 * Loopbacks go through ip_wput_local except for one case.
25969 		 * We come here if we generate a icmp_frag_needed message
25970 		 * after IPsec processing is over. When this function calls
25971 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25972 		 * icmp_frag_needed. The message generated comes back here
25973 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25974 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25975 		 * source address as it is usually set in ip_wput_ire. As
25976 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25977 		 * and we end up here. We can't enter ip_wput_ire once the
25978 		 * IPsec processing is over and hence we need to do it here.
25979 		 */
25980 		ASSERT(q != NULL);
25981 		UPDATE_OB_PKT_COUNT(ire);
25982 		ire->ire_last_used_time = lbolt;
25983 		if (ipha->ipha_src == 0)
25984 			ipha->ipha_src = ire->ire_src_addr;
25985 
25986 		/* PFHooks: LOOPBACK_OUT */
25987 		out_ill = ire_to_ill(ire);
25988 
25989 		/*
25990 		 * DTrace this as ip:::send.  A blocked packet will fire the
25991 		 * send probe, but not the receive probe.
25992 		 */
25993 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25994 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
25995 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
25996 
25997 		DTRACE_PROBE4(ip4__loopback__out__start,
25998 		    ill_t *, NULL, ill_t *, out_ill,
25999 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26000 
26001 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26002 		    ipst->ips_ipv4firewall_loopback_out,
26003 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26004 
26005 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26006 
26007 		if (ipsec_mp != NULL)
26008 			ip_wput_local(RD(q), out_ill,
26009 			    ipha, ipsec_mp, ire, 0, zoneid);
26010 		if (ire_need_rele)
26011 			ire_refrele(ire);
26012 		goto done;
26013 	}
26014 
26015 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26016 		/*
26017 		 * We are through with IPsec processing.
26018 		 * Fragment this and send it on the wire.
26019 		 */
26020 		if (io->ipsec_out_accelerated) {
26021 			/*
26022 			 * The packet has been accelerated but must
26023 			 * be fragmented. This should not happen
26024 			 * since AH and ESP must not accelerate
26025 			 * packets that need fragmentation, however
26026 			 * the configuration could have changed
26027 			 * since the AH or ESP processing.
26028 			 * Drop packet.
26029 			 * IPsec KSTATS: bump bean counter here.
26030 			 */
26031 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26032 			    "fragmented accelerated packet!\n"));
26033 			freemsg(ipsec_mp);
26034 		} else {
26035 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26036 			    zoneid, ipst, NULL);
26037 		}
26038 		if (ire_need_rele)
26039 			ire_refrele(ire);
26040 		goto done;
26041 	}
26042 
26043 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26044 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26045 	    (void *)ire->ire_ipif, (void *)ipif));
26046 
26047 	/*
26048 	 * Multiroute the secured packet.
26049 	 */
26050 	if (ire->ire_flags & RTF_MULTIRT) {
26051 		ire_t *first_ire;
26052 		irb = ire->ire_bucket;
26053 		ASSERT(irb != NULL);
26054 		/*
26055 		 * This ire has been looked up as the one that
26056 		 * goes through the given ipif;
26057 		 * make sure we do not omit any other multiroute ire
26058 		 * that may be present in the bucket before this one.
26059 		 */
26060 		IRB_REFHOLD(irb);
26061 		for (first_ire = irb->irb_ire;
26062 		    first_ire != NULL;
26063 		    first_ire = first_ire->ire_next) {
26064 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26065 			    (first_ire->ire_addr == ire->ire_addr) &&
26066 			    !(first_ire->ire_marks &
26067 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26068 				break;
26069 		}
26070 
26071 		if ((first_ire != NULL) && (first_ire != ire)) {
26072 			/*
26073 			 * Don't change the ire if the packet must
26074 			 * be fragmented if sent via this new one.
26075 			 */
26076 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26077 				IRE_REFHOLD(first_ire);
26078 				if (ire_need_rele)
26079 					ire_refrele(ire);
26080 				else
26081 					ire_need_rele = B_TRUE;
26082 				ire = first_ire;
26083 			}
26084 		}
26085 		IRB_REFRELE(irb);
26086 
26087 		multirt_send = B_TRUE;
26088 		max_frag = ire->ire_max_frag;
26089 	}
26090 
26091 	/*
26092 	 * In most cases, the emission loop below is entered only once.
26093 	 * Only in the case where the ire holds the RTF_MULTIRT
26094 	 * flag, we loop to process all RTF_MULTIRT ires in the
26095 	 * bucket, and send the packet through all crossed
26096 	 * RTF_MULTIRT routes.
26097 	 */
26098 	do {
26099 		if (multirt_send) {
26100 			/*
26101 			 * ire1 holds here the next ire to process in the
26102 			 * bucket. If multirouting is expected,
26103 			 * any non-RTF_MULTIRT ire that has the
26104 			 * right destination address is ignored.
26105 			 */
26106 			ASSERT(irb != NULL);
26107 			IRB_REFHOLD(irb);
26108 			for (ire1 = ire->ire_next;
26109 			    ire1 != NULL;
26110 			    ire1 = ire1->ire_next) {
26111 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26112 					continue;
26113 				if (ire1->ire_addr != ire->ire_addr)
26114 					continue;
26115 				if (ire1->ire_marks &
26116 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26117 					continue;
26118 				/* No loopback here */
26119 				if (ire1->ire_stq == NULL)
26120 					continue;
26121 				/*
26122 				 * Ensure we do not exceed the MTU
26123 				 * of the next route.
26124 				 */
26125 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26126 					ip_multirt_bad_mtu(ire1, max_frag);
26127 					continue;
26128 				}
26129 
26130 				IRE_REFHOLD(ire1);
26131 				break;
26132 			}
26133 			IRB_REFRELE(irb);
26134 			if (ire1 != NULL) {
26135 				/*
26136 				 * We are in a multiple send case, need to
26137 				 * make a copy of the packet.
26138 				 */
26139 				next_mp = copymsg(ipsec_mp);
26140 				if (next_mp == NULL) {
26141 					ire_refrele(ire1);
26142 					ire1 = NULL;
26143 				}
26144 			}
26145 		}
26146 		/*
26147 		 * Everything is done. Send it out on the wire
26148 		 *
26149 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26150 		 * either send it on the wire or, in the case of
26151 		 * HW acceleration, call ipsec_hw_putnext.
26152 		 */
26153 		if (ire->ire_nce &&
26154 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26155 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26156 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26157 			/*
26158 			 * If ire's link-layer is unresolved (this
26159 			 * would only happen if the incomplete ire
26160 			 * was added to cachetable via forwarding path)
26161 			 * don't bother going to ip_xmit_v4. Just drop the
26162 			 * packet.
26163 			 * There is a slight risk here, in that, if we
26164 			 * have the forwarding path create an incomplete
26165 			 * IRE, then until the IRE is completed, any
26166 			 * transmitted IPsec packets will be dropped
26167 			 * instead of being queued waiting for resolution.
26168 			 *
26169 			 * But the likelihood of a forwarding packet and a wput
26170 			 * packet sending to the same dst at the same time
26171 			 * and there not yet be an ARP entry for it is small.
26172 			 * Furthermore, if this actually happens, it might
26173 			 * be likely that wput would generate multiple
26174 			 * packets (and forwarding would also have a train
26175 			 * of packets) for that destination. If this is
26176 			 * the case, some of them would have been dropped
26177 			 * anyway, since ARP only queues a few packets while
26178 			 * waiting for resolution
26179 			 *
26180 			 * NOTE: We should really call ip_xmit_v4,
26181 			 * and let it queue the packet and send the
26182 			 * ARP query and have ARP come back thus:
26183 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26184 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26185 			 * hw accel work. But it's too complex to get
26186 			 * the IPsec hw  acceleration approach to fit
26187 			 * well with ip_xmit_v4 doing ARP without
26188 			 * doing IPsec simplification. For now, we just
26189 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26190 			 * that we can continue with the send on the next
26191 			 * attempt.
26192 			 *
26193 			 * XXX THis should be revisited, when
26194 			 * the IPsec/IP interaction is cleaned up
26195 			 */
26196 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26197 			    " - dropping packet\n"));
26198 			freemsg(ipsec_mp);
26199 			/*
26200 			 * Call ip_xmit_v4() to trigger ARP query
26201 			 * in case the nce_state is ND_INITIAL
26202 			 */
26203 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26204 			goto drop_pkt;
26205 		}
26206 
26207 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26208 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26209 		    mblk_t *, ipsec_mp);
26210 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26211 		    ipst->ips_ipv4firewall_physical_out, NULL,
26212 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26213 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26214 		if (ipsec_mp == NULL)
26215 			goto drop_pkt;
26216 
26217 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26218 		pktxmit_state = ip_xmit_v4(mp, ire,
26219 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26220 
26221 		if ((pktxmit_state ==  SEND_FAILED) ||
26222 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26223 
26224 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26225 drop_pkt:
26226 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26227 			    ipIfStatsOutDiscards);
26228 			if (ire_need_rele)
26229 				ire_refrele(ire);
26230 			if (ire1 != NULL) {
26231 				ire_refrele(ire1);
26232 				freemsg(next_mp);
26233 			}
26234 			goto done;
26235 		}
26236 
26237 		freeb(ipsec_mp);
26238 		if (ire_need_rele)
26239 			ire_refrele(ire);
26240 
26241 		if (ire1 != NULL) {
26242 			ire = ire1;
26243 			ire_need_rele = B_TRUE;
26244 			ASSERT(next_mp);
26245 			ipsec_mp = next_mp;
26246 			mp = ipsec_mp->b_cont;
26247 			ire1 = NULL;
26248 			next_mp = NULL;
26249 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26250 		} else {
26251 			multirt_send = B_FALSE;
26252 		}
26253 	} while (multirt_send);
26254 done:
26255 	if (ill != NULL && ill_need_rele)
26256 		ill_refrele(ill);
26257 	if (ipif != NULL)
26258 		ipif_refrele(ipif);
26259 }
26260 
26261 /*
26262  * Get the ill corresponding to the specified ire, and compare its
26263  * capabilities with the protocol and algorithms specified by the
26264  * the SA obtained from ipsec_out. If they match, annotate the
26265  * ipsec_out structure to indicate that the packet needs acceleration.
26266  *
26267  *
26268  * A packet is eligible for outbound hardware acceleration if the
26269  * following conditions are satisfied:
26270  *
26271  * 1. the packet will not be fragmented
26272  * 2. the provider supports the algorithm
26273  * 3. there is no pending control message being exchanged
26274  * 4. snoop is not attached
26275  * 5. the destination address is not a broadcast or multicast address.
26276  *
26277  * Rationale:
26278  *	- Hardware drivers do not support fragmentation with
26279  *	  the current interface.
26280  *	- snoop, multicast, and broadcast may result in exposure of
26281  *	  a cleartext datagram.
26282  * We check all five of these conditions here.
26283  *
26284  * XXX would like to nuke "ire_t *" parameter here; problem is that
26285  * IRE is only way to figure out if a v4 address is a broadcast and
26286  * thus ineligible for acceleration...
26287  */
26288 static void
26289 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26290 {
26291 	ipsec_out_t *io;
26292 	mblk_t *data_mp;
26293 	uint_t plen, overhead;
26294 	ip_stack_t	*ipst;
26295 	phyint_t	*phyint;
26296 
26297 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26298 		return;
26299 
26300 	if (ill == NULL)
26301 		return;
26302 	ipst = ill->ill_ipst;
26303 	phyint = ill->ill_phyint;
26304 
26305 	/*
26306 	 * Destination address is a broadcast or multicast.  Punt.
26307 	 */
26308 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26309 	    IRE_LOCAL)))
26310 		return;
26311 
26312 	data_mp = ipsec_mp->b_cont;
26313 
26314 	if (ill->ill_isv6) {
26315 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26316 
26317 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26318 			return;
26319 
26320 		plen = ip6h->ip6_plen;
26321 	} else {
26322 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26323 
26324 		if (CLASSD(ipha->ipha_dst))
26325 			return;
26326 
26327 		plen = ipha->ipha_length;
26328 	}
26329 	/*
26330 	 * Is there a pending DLPI control message being exchanged
26331 	 * between IP/IPsec and the DLS Provider? If there is, it
26332 	 * could be a SADB update, and the state of the DLS Provider
26333 	 * SADB might not be in sync with the SADB maintained by
26334 	 * IPsec. To avoid dropping packets or using the wrong keying
26335 	 * material, we do not accelerate this packet.
26336 	 */
26337 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26338 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26339 		    "ill_dlpi_pending! don't accelerate packet\n"));
26340 		return;
26341 	}
26342 
26343 	/*
26344 	 * Is the Provider in promiscous mode? If it does, we don't
26345 	 * accelerate the packet since it will bounce back up to the
26346 	 * listeners in the clear.
26347 	 */
26348 	if (phyint->phyint_flags & PHYI_PROMISC) {
26349 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26350 		    "ill in promiscous mode, don't accelerate packet\n"));
26351 		return;
26352 	}
26353 
26354 	/*
26355 	 * Will the packet require fragmentation?
26356 	 */
26357 
26358 	/*
26359 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26360 	 * as is used elsewhere.
26361 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26362 	 *	+ 2-byte trailer
26363 	 */
26364 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26365 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26366 
26367 	if ((plen + overhead) > ill->ill_max_mtu)
26368 		return;
26369 
26370 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26371 
26372 	/*
26373 	 * Can the ill accelerate this IPsec protocol and algorithm
26374 	 * specified by the SA?
26375 	 */
26376 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26377 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26378 		return;
26379 	}
26380 
26381 	/*
26382 	 * Tell AH or ESP that the outbound ill is capable of
26383 	 * accelerating this packet.
26384 	 */
26385 	io->ipsec_out_is_capab_ill = B_TRUE;
26386 }
26387 
26388 /*
26389  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26390  *
26391  * If this function returns B_TRUE, the requested SA's have been filled
26392  * into the ipsec_out_*_sa pointers.
26393  *
26394  * If the function returns B_FALSE, the packet has been "consumed", most
26395  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26396  *
26397  * The SA references created by the protocol-specific "select"
26398  * function will be released when the ipsec_mp is freed, thanks to the
26399  * ipsec_out_free destructor -- see spd.c.
26400  */
26401 static boolean_t
26402 ipsec_out_select_sa(mblk_t *ipsec_mp)
26403 {
26404 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26405 	ipsec_out_t *io;
26406 	ipsec_policy_t *pp;
26407 	ipsec_action_t *ap;
26408 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26409 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26410 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26411 
26412 	if (!io->ipsec_out_secure) {
26413 		/*
26414 		 * We came here by mistake.
26415 		 * Don't bother with ipsec processing
26416 		 * We should "discourage" this path in the future.
26417 		 */
26418 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26419 		return (B_FALSE);
26420 	}
26421 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26422 	ASSERT((io->ipsec_out_policy != NULL) ||
26423 	    (io->ipsec_out_act != NULL));
26424 
26425 	ASSERT(io->ipsec_out_failed == B_FALSE);
26426 
26427 	/*
26428 	 * IPsec processing has started.
26429 	 */
26430 	io->ipsec_out_proc_begin = B_TRUE;
26431 	ap = io->ipsec_out_act;
26432 	if (ap == NULL) {
26433 		pp = io->ipsec_out_policy;
26434 		ASSERT(pp != NULL);
26435 		ap = pp->ipsp_act;
26436 		ASSERT(ap != NULL);
26437 	}
26438 
26439 	/*
26440 	 * We have an action.  now, let's select SA's.
26441 	 * (In the future, we can cache this in the conn_t..)
26442 	 */
26443 	if (ap->ipa_want_esp) {
26444 		if (io->ipsec_out_esp_sa == NULL) {
26445 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26446 			    IPPROTO_ESP);
26447 		}
26448 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26449 	}
26450 
26451 	if (ap->ipa_want_ah) {
26452 		if (io->ipsec_out_ah_sa == NULL) {
26453 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26454 			    IPPROTO_AH);
26455 		}
26456 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26457 		/*
26458 		 * The ESP and AH processing order needs to be preserved
26459 		 * when both protocols are required (ESP should be applied
26460 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26461 		 * when both ESP and AH are required, and an AH ACQUIRE
26462 		 * is needed.
26463 		 */
26464 		if (ap->ipa_want_esp && need_ah_acquire)
26465 			need_esp_acquire = B_TRUE;
26466 	}
26467 
26468 	/*
26469 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26470 	 * Release SAs that got referenced, but will not be used until we
26471 	 * acquire _all_ of the SAs we need.
26472 	 */
26473 	if (need_ah_acquire || need_esp_acquire) {
26474 		if (io->ipsec_out_ah_sa != NULL) {
26475 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26476 			io->ipsec_out_ah_sa = NULL;
26477 		}
26478 		if (io->ipsec_out_esp_sa != NULL) {
26479 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26480 			io->ipsec_out_esp_sa = NULL;
26481 		}
26482 
26483 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26484 		return (B_FALSE);
26485 	}
26486 
26487 	return (B_TRUE);
26488 }
26489 
26490 /*
26491  * Process an IPSEC_OUT message and see what you can
26492  * do with it.
26493  * IPQoS Notes:
26494  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26495  * IPsec.
26496  * XXX would like to nuke ire_t.
26497  * XXX ill_index better be "real"
26498  */
26499 void
26500 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26501 {
26502 	ipsec_out_t *io;
26503 	ipsec_policy_t *pp;
26504 	ipsec_action_t *ap;
26505 	ipha_t *ipha;
26506 	ip6_t *ip6h;
26507 	mblk_t *mp;
26508 	ill_t *ill;
26509 	zoneid_t zoneid;
26510 	ipsec_status_t ipsec_rc;
26511 	boolean_t ill_need_rele = B_FALSE;
26512 	ip_stack_t	*ipst;
26513 	ipsec_stack_t	*ipss;
26514 
26515 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26516 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26517 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26518 	ipst = io->ipsec_out_ns->netstack_ip;
26519 	mp = ipsec_mp->b_cont;
26520 
26521 	/*
26522 	 * Initiate IPPF processing. We do it here to account for packets
26523 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26524 	 * We can check for ipsec_out_proc_begin even for such packets, as
26525 	 * they will always be false (asserted below).
26526 	 */
26527 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26528 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26529 		    io->ipsec_out_ill_index : ill_index);
26530 		if (mp == NULL) {
26531 			ip2dbg(("ipsec_out_process: packet dropped "\
26532 			    "during IPPF processing\n"));
26533 			freeb(ipsec_mp);
26534 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26535 			return;
26536 		}
26537 	}
26538 
26539 	if (!io->ipsec_out_secure) {
26540 		/*
26541 		 * We came here by mistake.
26542 		 * Don't bother with ipsec processing
26543 		 * Should "discourage" this path in the future.
26544 		 */
26545 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26546 		goto done;
26547 	}
26548 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26549 	ASSERT((io->ipsec_out_policy != NULL) ||
26550 	    (io->ipsec_out_act != NULL));
26551 	ASSERT(io->ipsec_out_failed == B_FALSE);
26552 
26553 	ipss = ipst->ips_netstack->netstack_ipsec;
26554 	if (!ipsec_loaded(ipss)) {
26555 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26556 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26557 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26558 		} else {
26559 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26560 		}
26561 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26562 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26563 		    &ipss->ipsec_dropper);
26564 		return;
26565 	}
26566 
26567 	/*
26568 	 * IPsec processing has started.
26569 	 */
26570 	io->ipsec_out_proc_begin = B_TRUE;
26571 	ap = io->ipsec_out_act;
26572 	if (ap == NULL) {
26573 		pp = io->ipsec_out_policy;
26574 		ASSERT(pp != NULL);
26575 		ap = pp->ipsp_act;
26576 		ASSERT(ap != NULL);
26577 	}
26578 
26579 	/*
26580 	 * Save the outbound ill index. When the packet comes back
26581 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26582 	 * before sending it the accelerated packet.
26583 	 */
26584 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26585 		ill = ire_to_ill(ire);
26586 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26587 	}
26588 
26589 	/*
26590 	 * The order of processing is first insert a IP header if needed.
26591 	 * Then insert the ESP header and then the AH header.
26592 	 */
26593 	if ((io->ipsec_out_se_done == B_FALSE) &&
26594 	    (ap->ipa_want_se)) {
26595 		/*
26596 		 * First get the outer IP header before sending
26597 		 * it to ESP.
26598 		 */
26599 		ipha_t *oipha, *iipha;
26600 		mblk_t *outer_mp, *inner_mp;
26601 
26602 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26603 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26604 			    "ipsec_out_process: "
26605 			    "Self-Encapsulation failed: Out of memory\n");
26606 			freemsg(ipsec_mp);
26607 			if (ill != NULL) {
26608 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26609 			} else {
26610 				BUMP_MIB(&ipst->ips_ip_mib,
26611 				    ipIfStatsOutDiscards);
26612 			}
26613 			return;
26614 		}
26615 		inner_mp = ipsec_mp->b_cont;
26616 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26617 		oipha = (ipha_t *)outer_mp->b_rptr;
26618 		iipha = (ipha_t *)inner_mp->b_rptr;
26619 		*oipha = *iipha;
26620 		outer_mp->b_wptr += sizeof (ipha_t);
26621 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26622 		    sizeof (ipha_t));
26623 		oipha->ipha_protocol = IPPROTO_ENCAP;
26624 		oipha->ipha_version_and_hdr_length =
26625 		    IP_SIMPLE_HDR_VERSION;
26626 		oipha->ipha_hdr_checksum = 0;
26627 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26628 		outer_mp->b_cont = inner_mp;
26629 		ipsec_mp->b_cont = outer_mp;
26630 
26631 		io->ipsec_out_se_done = B_TRUE;
26632 		io->ipsec_out_tunnel = B_TRUE;
26633 	}
26634 
26635 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26636 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26637 	    !ipsec_out_select_sa(ipsec_mp))
26638 		return;
26639 
26640 	/*
26641 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26642 	 * to do the heavy lifting.
26643 	 */
26644 	zoneid = io->ipsec_out_zoneid;
26645 	ASSERT(zoneid != ALL_ZONES);
26646 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26647 		ASSERT(io->ipsec_out_esp_sa != NULL);
26648 		io->ipsec_out_esp_done = B_TRUE;
26649 		/*
26650 		 * Note that since hw accel can only apply one transform,
26651 		 * not two, we skip hw accel for ESP if we also have AH
26652 		 * This is an design limitation of the interface
26653 		 * which should be revisited.
26654 		 */
26655 		ASSERT(ire != NULL);
26656 		if (io->ipsec_out_ah_sa == NULL) {
26657 			ill = (ill_t *)ire->ire_stq->q_ptr;
26658 			ipsec_out_is_accelerated(ipsec_mp,
26659 			    io->ipsec_out_esp_sa, ill, ire);
26660 		}
26661 
26662 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26663 		switch (ipsec_rc) {
26664 		case IPSEC_STATUS_SUCCESS:
26665 			break;
26666 		case IPSEC_STATUS_FAILED:
26667 			if (ill != NULL) {
26668 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26669 			} else {
26670 				BUMP_MIB(&ipst->ips_ip_mib,
26671 				    ipIfStatsOutDiscards);
26672 			}
26673 			/* FALLTHRU */
26674 		case IPSEC_STATUS_PENDING:
26675 			return;
26676 		}
26677 	}
26678 
26679 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26680 		ASSERT(io->ipsec_out_ah_sa != NULL);
26681 		io->ipsec_out_ah_done = B_TRUE;
26682 		if (ire == NULL) {
26683 			int idx = io->ipsec_out_capab_ill_index;
26684 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26685 			    NULL, NULL, NULL, NULL, ipst);
26686 			ill_need_rele = B_TRUE;
26687 		} else {
26688 			ill = (ill_t *)ire->ire_stq->q_ptr;
26689 		}
26690 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26691 		    ire);
26692 
26693 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26694 		switch (ipsec_rc) {
26695 		case IPSEC_STATUS_SUCCESS:
26696 			break;
26697 		case IPSEC_STATUS_FAILED:
26698 			if (ill != NULL) {
26699 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26700 			} else {
26701 				BUMP_MIB(&ipst->ips_ip_mib,
26702 				    ipIfStatsOutDiscards);
26703 			}
26704 			/* FALLTHRU */
26705 		case IPSEC_STATUS_PENDING:
26706 			if (ill != NULL && ill_need_rele)
26707 				ill_refrele(ill);
26708 			return;
26709 		}
26710 	}
26711 	/*
26712 	 * We are done with IPsec processing. Send it over the wire.
26713 	 */
26714 done:
26715 	mp = ipsec_mp->b_cont;
26716 	ipha = (ipha_t *)mp->b_rptr;
26717 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26718 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26719 		    ire);
26720 	} else {
26721 		ip6h = (ip6_t *)ipha;
26722 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26723 		    ire);
26724 	}
26725 	if (ill != NULL && ill_need_rele)
26726 		ill_refrele(ill);
26727 }
26728 
26729 /* ARGSUSED */
26730 void
26731 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26732 {
26733 	opt_restart_t	*or;
26734 	int	err;
26735 	conn_t	*connp;
26736 	cred_t	*cr;
26737 
26738 	ASSERT(CONN_Q(q));
26739 	connp = Q_TO_CONN(q);
26740 
26741 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26742 	or = (opt_restart_t *)first_mp->b_rptr;
26743 	/*
26744 	 * We checked for a db_credp the first time svr4_optcom_req
26745 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26746 	 */
26747 	cr = msg_getcred(first_mp, NULL);
26748 	ASSERT(cr != NULL);
26749 
26750 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26751 		err = svr4_optcom_req(q, first_mp, cr,
26752 		    &ip_opt_obj, B_FALSE);
26753 	} else {
26754 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26755 		err = tpi_optcom_req(q, first_mp, cr,
26756 		    &ip_opt_obj, B_FALSE);
26757 	}
26758 	if (err != EINPROGRESS) {
26759 		/* operation is done */
26760 		CONN_OPER_PENDING_DONE(connp);
26761 	}
26762 }
26763 
26764 /*
26765  * ioctls that go through a down/up sequence may need to wait for the down
26766  * to complete. This involves waiting for the ire and ipif refcnts to go down
26767  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26768  */
26769 /* ARGSUSED */
26770 void
26771 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26772 {
26773 	struct iocblk *iocp;
26774 	mblk_t *mp1;
26775 	ip_ioctl_cmd_t *ipip;
26776 	int err;
26777 	sin_t	*sin;
26778 	struct lifreq *lifr;
26779 	struct ifreq *ifr;
26780 
26781 	iocp = (struct iocblk *)mp->b_rptr;
26782 	ASSERT(ipsq != NULL);
26783 	/* Existence of mp1 verified in ip_wput_nondata */
26784 	mp1 = mp->b_cont->b_cont;
26785 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26786 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26787 		/*
26788 		 * Special case where ipx_current_ipif is not set:
26789 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26790 		 * We are here as were not able to complete the operation in
26791 		 * ipif_set_values because we could not become exclusive on
26792 		 * the new ipsq.
26793 		 */
26794 		ill_t *ill = q->q_ptr;
26795 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26796 	}
26797 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26798 
26799 	if (ipip->ipi_cmd_type == IF_CMD) {
26800 		/* This a old style SIOC[GS]IF* command */
26801 		ifr = (struct ifreq *)mp1->b_rptr;
26802 		sin = (sin_t *)&ifr->ifr_addr;
26803 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26804 		/* This a new style SIOC[GS]LIF* command */
26805 		lifr = (struct lifreq *)mp1->b_rptr;
26806 		sin = (sin_t *)&lifr->lifr_addr;
26807 	} else {
26808 		sin = NULL;
26809 	}
26810 
26811 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26812 	    q, mp, ipip, mp1->b_rptr);
26813 
26814 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26815 }
26816 
26817 /*
26818  * ioctl processing
26819  *
26820  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26821  * the ioctl command in the ioctl tables, determines the copyin data size
26822  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26823  *
26824  * ioctl processing then continues when the M_IOCDATA makes its way down to
26825  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26826  * associated 'conn' is refheld till the end of the ioctl and the general
26827  * ioctl processing function ip_process_ioctl() is called to extract the
26828  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26829  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26830  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26831  * is used to extract the ioctl's arguments.
26832  *
26833  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26834  * so goes thru the serialization primitive ipsq_try_enter. Then the
26835  * appropriate function to handle the ioctl is called based on the entry in
26836  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26837  * which also refreleases the 'conn' that was refheld at the start of the
26838  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26839  *
26840  * Many exclusive ioctls go thru an internal down up sequence as part of
26841  * the operation. For example an attempt to change the IP address of an
26842  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26843  * does all the cleanup such as deleting all ires that use this address.
26844  * Then we need to wait till all references to the interface go away.
26845  */
26846 void
26847 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26848 {
26849 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26850 	ip_ioctl_cmd_t *ipip = arg;
26851 	ip_extract_func_t *extract_funcp;
26852 	cmd_info_t ci;
26853 	int err;
26854 	boolean_t entered_ipsq = B_FALSE;
26855 
26856 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26857 
26858 	if (ipip == NULL)
26859 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26860 
26861 	/*
26862 	 * SIOCLIFADDIF needs to go thru a special path since the
26863 	 * ill may not exist yet. This happens in the case of lo0
26864 	 * which is created using this ioctl.
26865 	 */
26866 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26867 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26868 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26869 		return;
26870 	}
26871 
26872 	ci.ci_ipif = NULL;
26873 	if (ipip->ipi_cmd_type == MISC_CMD) {
26874 		/*
26875 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26876 		 */
26877 		if (ipip->ipi_cmd == IF_UNITSEL) {
26878 			/* ioctl comes down the ill */
26879 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26880 			ipif_refhold(ci.ci_ipif);
26881 		}
26882 		err = 0;
26883 		ci.ci_sin = NULL;
26884 		ci.ci_sin6 = NULL;
26885 		ci.ci_lifr = NULL;
26886 	} else {
26887 		switch (ipip->ipi_cmd_type) {
26888 		case IF_CMD:
26889 		case LIF_CMD:
26890 			extract_funcp = ip_extract_lifreq;
26891 			break;
26892 
26893 		case ARP_CMD:
26894 		case XARP_CMD:
26895 			extract_funcp = ip_extract_arpreq;
26896 			break;
26897 
26898 		case MSFILT_CMD:
26899 			extract_funcp = ip_extract_msfilter;
26900 			break;
26901 
26902 		default:
26903 			ASSERT(0);
26904 		}
26905 
26906 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26907 		if (err != 0) {
26908 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26909 			return;
26910 		}
26911 
26912 		/*
26913 		 * All of the extraction functions return a refheld ipif.
26914 		 */
26915 		ASSERT(ci.ci_ipif != NULL);
26916 	}
26917 
26918 	if (!(ipip->ipi_flags & IPI_WR)) {
26919 		/*
26920 		 * A return value of EINPROGRESS means the ioctl is
26921 		 * either queued and waiting for some reason or has
26922 		 * already completed.
26923 		 */
26924 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26925 		    ci.ci_lifr);
26926 		if (ci.ci_ipif != NULL)
26927 			ipif_refrele(ci.ci_ipif);
26928 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26929 		return;
26930 	}
26931 
26932 	ASSERT(ci.ci_ipif != NULL);
26933 
26934 	/*
26935 	 * If ipsq is non-NULL, we are already being called exclusively.
26936 	 */
26937 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26938 	if (ipsq == NULL) {
26939 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26940 		    NEW_OP, B_TRUE);
26941 		if (ipsq == NULL) {
26942 			ipif_refrele(ci.ci_ipif);
26943 			return;
26944 		}
26945 		entered_ipsq = B_TRUE;
26946 	}
26947 
26948 	/*
26949 	 * Release the ipif so that ipif_down and friends that wait for
26950 	 * references to go away are not misled about the current ipif_refcnt
26951 	 * values. We are writer so we can access the ipif even after releasing
26952 	 * the ipif.
26953 	 */
26954 	ipif_refrele(ci.ci_ipif);
26955 
26956 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26957 
26958 	/*
26959 	 * A return value of EINPROGRESS means the ioctl is
26960 	 * either queued and waiting for some reason or has
26961 	 * already completed.
26962 	 */
26963 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26964 
26965 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26966 
26967 	if (entered_ipsq)
26968 		ipsq_exit(ipsq);
26969 }
26970 
26971 /*
26972  * Complete the ioctl. Typically ioctls use the mi package and need to
26973  * do mi_copyout/mi_copy_done.
26974  */
26975 void
26976 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26977 {
26978 	conn_t	*connp = NULL;
26979 
26980 	if (err == EINPROGRESS)
26981 		return;
26982 
26983 	if (CONN_Q(q)) {
26984 		connp = Q_TO_CONN(q);
26985 		ASSERT(connp->conn_ref >= 2);
26986 	}
26987 
26988 	switch (mode) {
26989 	case COPYOUT:
26990 		if (err == 0)
26991 			mi_copyout(q, mp);
26992 		else
26993 			mi_copy_done(q, mp, err);
26994 		break;
26995 
26996 	case NO_COPYOUT:
26997 		mi_copy_done(q, mp, err);
26998 		break;
26999 
27000 	default:
27001 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27002 		break;
27003 	}
27004 
27005 	/*
27006 	 * The refhold placed at the start of the ioctl is released here.
27007 	 */
27008 	if (connp != NULL)
27009 		CONN_OPER_PENDING_DONE(connp);
27010 
27011 	if (ipsq != NULL)
27012 		ipsq_current_finish(ipsq);
27013 }
27014 
27015 /* Called from ip_wput for all non data messages */
27016 /* ARGSUSED */
27017 void
27018 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27019 {
27020 	mblk_t		*mp1;
27021 	ire_t		*ire, *fake_ire;
27022 	ill_t		*ill;
27023 	struct iocblk	*iocp;
27024 	ip_ioctl_cmd_t	*ipip;
27025 	cred_t		*cr;
27026 	conn_t		*connp;
27027 	int		err;
27028 	nce_t		*nce;
27029 	ipif_t		*ipif;
27030 	ip_stack_t	*ipst;
27031 	char		*proto_str;
27032 
27033 	if (CONN_Q(q)) {
27034 		connp = Q_TO_CONN(q);
27035 		ipst = connp->conn_netstack->netstack_ip;
27036 	} else {
27037 		connp = NULL;
27038 		ipst = ILLQ_TO_IPST(q);
27039 	}
27040 
27041 	switch (DB_TYPE(mp)) {
27042 	case M_IOCTL:
27043 		/*
27044 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27045 		 * will arrange to copy in associated control structures.
27046 		 */
27047 		ip_sioctl_copyin_setup(q, mp);
27048 		return;
27049 	case M_IOCDATA:
27050 		/*
27051 		 * Ensure that this is associated with one of our trans-
27052 		 * parent ioctls.  If it's not ours, discard it if we're
27053 		 * running as a driver, or pass it on if we're a module.
27054 		 */
27055 		iocp = (struct iocblk *)mp->b_rptr;
27056 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27057 		if (ipip == NULL) {
27058 			if (q->q_next == NULL) {
27059 				goto nak;
27060 			} else {
27061 				putnext(q, mp);
27062 			}
27063 			return;
27064 		}
27065 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27066 			/*
27067 			 * the ioctl is one we recognise, but is not
27068 			 * consumed by IP as a module, pass M_IOCDATA
27069 			 * for processing downstream, but only for
27070 			 * common Streams ioctls.
27071 			 */
27072 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27073 				putnext(q, mp);
27074 				return;
27075 			} else {
27076 				goto nak;
27077 			}
27078 		}
27079 
27080 		/* IOCTL continuation following copyin or copyout. */
27081 		if (mi_copy_state(q, mp, NULL) == -1) {
27082 			/*
27083 			 * The copy operation failed.  mi_copy_state already
27084 			 * cleaned up, so we're out of here.
27085 			 */
27086 			return;
27087 		}
27088 		/*
27089 		 * If we just completed a copy in, we become writer and
27090 		 * continue processing in ip_sioctl_copyin_done.  If it
27091 		 * was a copy out, we call mi_copyout again.  If there is
27092 		 * nothing more to copy out, it will complete the IOCTL.
27093 		 */
27094 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27095 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27096 				mi_copy_done(q, mp, EPROTO);
27097 				return;
27098 			}
27099 			/*
27100 			 * Check for cases that need more copying.  A return
27101 			 * value of 0 means a second copyin has been started,
27102 			 * so we return; a return value of 1 means no more
27103 			 * copying is needed, so we continue.
27104 			 */
27105 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27106 			    MI_COPY_COUNT(mp) == 1) {
27107 				if (ip_copyin_msfilter(q, mp) == 0)
27108 					return;
27109 			}
27110 			/*
27111 			 * Refhold the conn, till the ioctl completes. This is
27112 			 * needed in case the ioctl ends up in the pending mp
27113 			 * list. Every mp in the ill_pending_mp list and
27114 			 * the ipx_pending_mp must have a refhold on the conn
27115 			 * to resume processing. The refhold is released when
27116 			 * the ioctl completes. (normally or abnormally)
27117 			 * In all cases ip_ioctl_finish is called to finish
27118 			 * the ioctl.
27119 			 */
27120 			if (connp != NULL) {
27121 				/* This is not a reentry */
27122 				ASSERT(ipsq == NULL);
27123 				CONN_INC_REF(connp);
27124 			} else {
27125 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27126 					mi_copy_done(q, mp, EINVAL);
27127 					return;
27128 				}
27129 			}
27130 
27131 			ip_process_ioctl(ipsq, q, mp, ipip);
27132 
27133 		} else {
27134 			mi_copyout(q, mp);
27135 		}
27136 		return;
27137 nak:
27138 		iocp->ioc_error = EINVAL;
27139 		mp->b_datap->db_type = M_IOCNAK;
27140 		iocp->ioc_count = 0;
27141 		qreply(q, mp);
27142 		return;
27143 
27144 	case M_IOCNAK:
27145 		/*
27146 		 * The only way we could get here is if a resolver didn't like
27147 		 * an IOCTL we sent it.	 This shouldn't happen.
27148 		 */
27149 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27150 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27151 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27152 		freemsg(mp);
27153 		return;
27154 	case M_IOCACK:
27155 		/* /dev/ip shouldn't see this */
27156 		if (CONN_Q(q))
27157 			goto nak;
27158 
27159 		/*
27160 		 * Finish socket ioctls passed through to ARP.  We use the
27161 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27162 		 * we need to become writer before calling ip_sioctl_iocack().
27163 		 * Note that qwriter_ip() will release the refhold, and that a
27164 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27165 		 * ill stream.
27166 		 */
27167 		iocp = (struct iocblk *)mp->b_rptr;
27168 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27169 			ip_sioctl_iocack(NULL, q, mp, NULL);
27170 			return;
27171 		}
27172 
27173 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27174 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27175 		ill = q->q_ptr;
27176 		ill_refhold(ill);
27177 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27178 		return;
27179 	case M_FLUSH:
27180 		if (*mp->b_rptr & FLUSHW)
27181 			flushq(q, FLUSHALL);
27182 		if (q->q_next) {
27183 			putnext(q, mp);
27184 			return;
27185 		}
27186 		if (*mp->b_rptr & FLUSHR) {
27187 			*mp->b_rptr &= ~FLUSHW;
27188 			qreply(q, mp);
27189 			return;
27190 		}
27191 		freemsg(mp);
27192 		return;
27193 	case IRE_DB_REQ_TYPE:
27194 		if (connp == NULL) {
27195 			proto_str = "IRE_DB_REQ_TYPE";
27196 			goto protonak;
27197 		}
27198 		/* An Upper Level Protocol wants a copy of an IRE. */
27199 		ip_ire_req(q, mp);
27200 		return;
27201 	case M_CTL:
27202 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27203 			break;
27204 
27205 		/* M_CTL messages are used by ARP to tell us things. */
27206 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27207 			break;
27208 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27209 		case AR_ENTRY_SQUERY:
27210 			putnext(q, mp);
27211 			return;
27212 		case AR_CLIENT_NOTIFY:
27213 			ip_arp_news(q, mp);
27214 			return;
27215 		case AR_DLPIOP_DONE:
27216 			ASSERT(q->q_next != NULL);
27217 			ill = (ill_t *)q->q_ptr;
27218 			/* qwriter_ip releases the refhold */
27219 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27220 			ill_refhold(ill);
27221 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27222 			return;
27223 		case AR_ARP_CLOSING:
27224 			/*
27225 			 * ARP (above us) is closing. If no ARP bringup is
27226 			 * currently pending, ack the message so that ARP
27227 			 * can complete its close. Also mark ill_arp_closing
27228 			 * so that new ARP bringups will fail. If any
27229 			 * ARP bringup is currently in progress, we will
27230 			 * ack this when the current ARP bringup completes.
27231 			 */
27232 			ASSERT(q->q_next != NULL);
27233 			ill = (ill_t *)q->q_ptr;
27234 			mutex_enter(&ill->ill_lock);
27235 			ill->ill_arp_closing = 1;
27236 			if (!ill->ill_arp_bringup_pending) {
27237 				mutex_exit(&ill->ill_lock);
27238 				qreply(q, mp);
27239 			} else {
27240 				mutex_exit(&ill->ill_lock);
27241 				freemsg(mp);
27242 			}
27243 			return;
27244 		case AR_ARP_EXTEND:
27245 			/*
27246 			 * The ARP module above us is capable of duplicate
27247 			 * address detection.  Old ATM drivers will not send
27248 			 * this message.
27249 			 */
27250 			ASSERT(q->q_next != NULL);
27251 			ill = (ill_t *)q->q_ptr;
27252 			ill->ill_arp_extend = B_TRUE;
27253 			freemsg(mp);
27254 			return;
27255 		default:
27256 			break;
27257 		}
27258 		break;
27259 	case M_PROTO:
27260 	case M_PCPROTO:
27261 		/*
27262 		 * The only PROTO messages we expect are copies of option
27263 		 * negotiation acknowledgements, AH and ESP bind requests
27264 		 * are also expected.
27265 		 */
27266 		switch (((union T_primitives *)mp->b_rptr)->type) {
27267 		case O_T_BIND_REQ:
27268 		case T_BIND_REQ: {
27269 			/* Request can get queued in bind */
27270 			if (connp == NULL) {
27271 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27272 				goto protonak;
27273 			}
27274 			/*
27275 			 * The transports except SCTP call ip_bind_{v4,v6}()
27276 			 * directly instead of a a putnext. SCTP doesn't
27277 			 * generate any T_BIND_REQ since it has its own
27278 			 * fanout data structures. However, ESP and AH
27279 			 * come in for regular binds; all other cases are
27280 			 * bind retries.
27281 			 */
27282 			ASSERT(!IPCL_IS_SCTP(connp));
27283 
27284 			/* Don't increment refcnt if this is a re-entry */
27285 			if (ipsq == NULL)
27286 				CONN_INC_REF(connp);
27287 
27288 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27289 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27290 			ASSERT(mp != NULL);
27291 
27292 			ASSERT(!IPCL_IS_TCP(connp));
27293 			ASSERT(!IPCL_IS_UDP(connp));
27294 			ASSERT(!IPCL_IS_RAWIP(connp));
27295 			ASSERT(!IPCL_IS_IPTUN(connp));
27296 
27297 			/* The case of AH and ESP */
27298 			qreply(q, mp);
27299 			CONN_OPER_PENDING_DONE(connp);
27300 			return;
27301 		}
27302 		case T_SVR4_OPTMGMT_REQ:
27303 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27304 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27305 
27306 			if (connp == NULL) {
27307 				proto_str = "T_SVR4_OPTMGMT_REQ";
27308 				goto protonak;
27309 			}
27310 
27311 			/*
27312 			 * All Solaris components should pass a db_credp
27313 			 * for this TPI message, hence we ASSERT.
27314 			 * But in case there is some other M_PROTO that looks
27315 			 * like a TPI message sent by some other kernel
27316 			 * component, we check and return an error.
27317 			 */
27318 			cr = msg_getcred(mp, NULL);
27319 			ASSERT(cr != NULL);
27320 			if (cr == NULL) {
27321 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27322 				if (mp != NULL)
27323 					qreply(q, mp);
27324 				return;
27325 			}
27326 
27327 			if (!snmpcom_req(q, mp, ip_snmp_set,
27328 			    ip_snmp_get, cr)) {
27329 				/*
27330 				 * Call svr4_optcom_req so that it can
27331 				 * generate the ack. We don't come here
27332 				 * if this operation is being restarted.
27333 				 * ip_restart_optmgmt will drop the conn ref.
27334 				 * In the case of ipsec option after the ipsec
27335 				 * load is complete conn_restart_ipsec_waiter
27336 				 * drops the conn ref.
27337 				 */
27338 				ASSERT(ipsq == NULL);
27339 				CONN_INC_REF(connp);
27340 				if (ip_check_for_ipsec_opt(q, mp))
27341 					return;
27342 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27343 				    B_FALSE);
27344 				if (err != EINPROGRESS) {
27345 					/* Operation is done */
27346 					CONN_OPER_PENDING_DONE(connp);
27347 				}
27348 			}
27349 			return;
27350 		case T_OPTMGMT_REQ:
27351 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27352 			/*
27353 			 * Note: No snmpcom_req support through new
27354 			 * T_OPTMGMT_REQ.
27355 			 * Call tpi_optcom_req so that it can
27356 			 * generate the ack.
27357 			 */
27358 			if (connp == NULL) {
27359 				proto_str = "T_OPTMGMT_REQ";
27360 				goto protonak;
27361 			}
27362 
27363 			/*
27364 			 * All Solaris components should pass a db_credp
27365 			 * for this TPI message, hence we ASSERT.
27366 			 * But in case there is some other M_PROTO that looks
27367 			 * like a TPI message sent by some other kernel
27368 			 * component, we check and return an error.
27369 			 */
27370 			cr = msg_getcred(mp, NULL);
27371 			ASSERT(cr != NULL);
27372 			if (cr == NULL) {
27373 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27374 				if (mp != NULL)
27375 					qreply(q, mp);
27376 				return;
27377 			}
27378 			ASSERT(ipsq == NULL);
27379 			/*
27380 			 * We don't come here for restart. ip_restart_optmgmt
27381 			 * will drop the conn ref. In the case of ipsec option
27382 			 * after the ipsec load is complete
27383 			 * conn_restart_ipsec_waiter drops the conn ref.
27384 			 */
27385 			CONN_INC_REF(connp);
27386 			if (ip_check_for_ipsec_opt(q, mp))
27387 				return;
27388 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27389 			if (err != EINPROGRESS) {
27390 				/* Operation is done */
27391 				CONN_OPER_PENDING_DONE(connp);
27392 			}
27393 			return;
27394 		case T_UNBIND_REQ:
27395 			if (connp == NULL) {
27396 				proto_str = "T_UNBIND_REQ";
27397 				goto protonak;
27398 			}
27399 			ip_unbind(Q_TO_CONN(q));
27400 			mp = mi_tpi_ok_ack_alloc(mp);
27401 			qreply(q, mp);
27402 			return;
27403 		default:
27404 			/*
27405 			 * Have to drop any DLPI messages coming down from
27406 			 * arp (such as an info_req which would cause ip
27407 			 * to receive an extra info_ack if it was passed
27408 			 * through.
27409 			 */
27410 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27411 			    (int)*(uint_t *)mp->b_rptr));
27412 			freemsg(mp);
27413 			return;
27414 		}
27415 		/* NOTREACHED */
27416 	case IRE_DB_TYPE: {
27417 		nce_t		*nce;
27418 		ill_t		*ill;
27419 		in6_addr_t	gw_addr_v6;
27420 
27421 		/*
27422 		 * This is a response back from a resolver.  It
27423 		 * consists of a message chain containing:
27424 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27425 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27426 		 * The LL_HDR_MBLK is the DLPI header to use to get
27427 		 * the attached packet, and subsequent ones for the
27428 		 * same destination, transmitted.
27429 		 */
27430 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27431 			break;
27432 		/*
27433 		 * First, check to make sure the resolution succeeded.
27434 		 * If it failed, the second mblk will be empty.
27435 		 * If it is, free the chain, dropping the packet.
27436 		 * (We must ire_delete the ire; that frees the ire mblk)
27437 		 * We're doing this now to support PVCs for ATM; it's
27438 		 * a partial xresolv implementation. When we fully implement
27439 		 * xresolv interfaces, instead of freeing everything here
27440 		 * we'll initiate neighbor discovery.
27441 		 *
27442 		 * For v4 (ARP and other external resolvers) the resolver
27443 		 * frees the message, so no check is needed. This check
27444 		 * is required, though, for a full xresolve implementation.
27445 		 * Including this code here now both shows how external
27446 		 * resolvers can NACK a resolution request using an
27447 		 * existing design that has no specific provisions for NACKs,
27448 		 * and also takes into account that the current non-ARP
27449 		 * external resolver has been coded to use this method of
27450 		 * NACKing for all IPv6 (xresolv) cases,
27451 		 * whether our xresolv implementation is complete or not.
27452 		 *
27453 		 */
27454 		ire = (ire_t *)mp->b_rptr;
27455 		ill = ire_to_ill(ire);
27456 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27457 		if (mp1->b_rptr == mp1->b_wptr) {
27458 			if (ire->ire_ipversion == IPV6_VERSION) {
27459 				/*
27460 				 * XRESOLV interface.
27461 				 */
27462 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27463 				mutex_enter(&ire->ire_lock);
27464 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27465 				mutex_exit(&ire->ire_lock);
27466 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27467 					nce = ndp_lookup_v6(ill, B_FALSE,
27468 					    &ire->ire_addr_v6, B_FALSE);
27469 				} else {
27470 					nce = ndp_lookup_v6(ill, B_FALSE,
27471 					    &gw_addr_v6, B_FALSE);
27472 				}
27473 				if (nce != NULL) {
27474 					nce_resolv_failed(nce);
27475 					ndp_delete(nce);
27476 					NCE_REFRELE(nce);
27477 				}
27478 			}
27479 			mp->b_cont = NULL;
27480 			freemsg(mp1);		/* frees the pkt as well */
27481 			ASSERT(ire->ire_nce == NULL);
27482 			ire_delete((ire_t *)mp->b_rptr);
27483 			return;
27484 		}
27485 
27486 		/*
27487 		 * Split them into IRE_MBLK and pkt and feed it into
27488 		 * ire_add_then_send. Then in ire_add_then_send
27489 		 * the IRE will be added, and then the packet will be
27490 		 * run back through ip_wput. This time it will make
27491 		 * it to the wire.
27492 		 */
27493 		mp->b_cont = NULL;
27494 		mp = mp1->b_cont;		/* now, mp points to pkt */
27495 		mp1->b_cont = NULL;
27496 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27497 		if (ire->ire_ipversion == IPV6_VERSION) {
27498 			/*
27499 			 * XRESOLV interface. Find the nce and put a copy
27500 			 * of the dl_unitdata_req in nce_res_mp
27501 			 */
27502 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27503 			mutex_enter(&ire->ire_lock);
27504 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27505 			mutex_exit(&ire->ire_lock);
27506 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27507 				nce = ndp_lookup_v6(ill, B_FALSE,
27508 				    &ire->ire_addr_v6, B_FALSE);
27509 			} else {
27510 				nce = ndp_lookup_v6(ill, B_FALSE,
27511 				    &gw_addr_v6, B_FALSE);
27512 			}
27513 			if (nce != NULL) {
27514 				/*
27515 				 * We have to protect nce_res_mp here
27516 				 * from being accessed by other threads
27517 				 * while we change the mblk pointer.
27518 				 * Other functions will also lock the nce when
27519 				 * accessing nce_res_mp.
27520 				 *
27521 				 * The reason we change the mblk pointer
27522 				 * here rather than copying the resolved address
27523 				 * into the template is that, unlike with
27524 				 * ethernet, we have no guarantee that the
27525 				 * resolved address length will be
27526 				 * smaller than or equal to the lla length
27527 				 * with which the template was allocated,
27528 				 * (for ethernet, they're equal)
27529 				 * so we have to use the actual resolved
27530 				 * address mblk - which holds the real
27531 				 * dl_unitdata_req with the resolved address.
27532 				 *
27533 				 * Doing this is the same behavior as was
27534 				 * previously used in the v4 ARP case.
27535 				 */
27536 				mutex_enter(&nce->nce_lock);
27537 				if (nce->nce_res_mp != NULL)
27538 					freemsg(nce->nce_res_mp);
27539 				nce->nce_res_mp = mp1;
27540 				mutex_exit(&nce->nce_lock);
27541 				/*
27542 				 * We do a fastpath probe here because
27543 				 * we have resolved the address without
27544 				 * using Neighbor Discovery.
27545 				 * In the non-XRESOLV v6 case, the fastpath
27546 				 * probe is done right after neighbor
27547 				 * discovery completes.
27548 				 */
27549 				if (nce->nce_res_mp != NULL) {
27550 					int res;
27551 					nce_fastpath_list_add(nce);
27552 					res = ill_fastpath_probe(ill,
27553 					    nce->nce_res_mp);
27554 					if (res != 0 && res != EAGAIN)
27555 						nce_fastpath_list_delete(nce);
27556 				}
27557 
27558 				ire_add_then_send(q, ire, mp);
27559 				/*
27560 				 * Now we have to clean out any packets
27561 				 * that may have been queued on the nce
27562 				 * while it was waiting for address resolution
27563 				 * to complete.
27564 				 */
27565 				mutex_enter(&nce->nce_lock);
27566 				mp1 = nce->nce_qd_mp;
27567 				nce->nce_qd_mp = NULL;
27568 				mutex_exit(&nce->nce_lock);
27569 				while (mp1 != NULL) {
27570 					mblk_t *nxt_mp;
27571 					queue_t *fwdq = NULL;
27572 					ill_t   *inbound_ill;
27573 					uint_t ifindex;
27574 
27575 					nxt_mp = mp1->b_next;
27576 					mp1->b_next = NULL;
27577 					/*
27578 					 * Retrieve ifindex stored in
27579 					 * ip_rput_data_v6()
27580 					 */
27581 					ifindex =
27582 					    (uint_t)(uintptr_t)mp1->b_prev;
27583 					inbound_ill =
27584 					    ill_lookup_on_ifindex(ifindex,
27585 					    B_TRUE, NULL, NULL, NULL,
27586 					    NULL, ipst);
27587 					mp1->b_prev = NULL;
27588 					if (inbound_ill != NULL)
27589 						fwdq = inbound_ill->ill_rq;
27590 
27591 					if (fwdq != NULL) {
27592 						put(fwdq, mp1);
27593 						ill_refrele(inbound_ill);
27594 					} else
27595 						put(WR(ill->ill_rq), mp1);
27596 					mp1 = nxt_mp;
27597 				}
27598 				NCE_REFRELE(nce);
27599 			} else {	/* nce is NULL; clean up */
27600 				ire_delete(ire);
27601 				freemsg(mp);
27602 				freemsg(mp1);
27603 				return;
27604 			}
27605 		} else {
27606 			nce_t *arpce;
27607 			/*
27608 			 * Link layer resolution succeeded. Recompute the
27609 			 * ire_nce.
27610 			 */
27611 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27612 			if ((arpce = ndp_lookup_v4(ill,
27613 			    (ire->ire_gateway_addr != INADDR_ANY ?
27614 			    &ire->ire_gateway_addr : &ire->ire_addr),
27615 			    B_FALSE)) == NULL) {
27616 				freeb(ire->ire_mp);
27617 				freeb(mp1);
27618 				freemsg(mp);
27619 				return;
27620 			}
27621 			mutex_enter(&arpce->nce_lock);
27622 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27623 			if (arpce->nce_state == ND_REACHABLE) {
27624 				/*
27625 				 * Someone resolved this before us;
27626 				 * cleanup the res_mp. Since ire has
27627 				 * not been added yet, the call to ire_add_v4
27628 				 * from ire_add_then_send (when a dup is
27629 				 * detected) will clean up the ire.
27630 				 */
27631 				freeb(mp1);
27632 			} else {
27633 				ASSERT(arpce->nce_res_mp == NULL);
27634 				arpce->nce_res_mp = mp1;
27635 				arpce->nce_state = ND_REACHABLE;
27636 			}
27637 			mutex_exit(&arpce->nce_lock);
27638 			if (ire->ire_marks & IRE_MARK_NOADD) {
27639 				/*
27640 				 * this ire will not be added to the ire
27641 				 * cache table, so we can set the ire_nce
27642 				 * here, as there are no atomicity constraints.
27643 				 */
27644 				ire->ire_nce = arpce;
27645 				/*
27646 				 * We are associating this nce with the ire
27647 				 * so change the nce ref taken in
27648 				 * ndp_lookup_v4() from
27649 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27650 				 */
27651 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27652 			} else {
27653 				NCE_REFRELE(arpce);
27654 			}
27655 			ire_add_then_send(q, ire, mp);
27656 		}
27657 		return;	/* All is well, the packet has been sent. */
27658 	}
27659 	case IRE_ARPRESOLVE_TYPE: {
27660 
27661 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27662 			break;
27663 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27664 		mp->b_cont = NULL;
27665 		/*
27666 		 * First, check to make sure the resolution succeeded.
27667 		 * If it failed, the second mblk will be empty.
27668 		 */
27669 		if (mp1->b_rptr == mp1->b_wptr) {
27670 			/* cleanup  the incomplete ire, free queued packets */
27671 			freemsg(mp); /* fake ire */
27672 			freeb(mp1);  /* dl_unitdata response */
27673 			return;
27674 		}
27675 
27676 		/*
27677 		 * Update any incomplete nce_t found. We search the ctable
27678 		 * and find the nce from the ire->ire_nce because we need
27679 		 * to pass the ire to ip_xmit_v4 later, and can find both
27680 		 * ire and nce in one lookup.
27681 		 */
27682 		fake_ire = (ire_t *)mp->b_rptr;
27683 
27684 		/*
27685 		 * By the time we come back here from ARP the logical outgoing
27686 		 * interface of the incomplete ire we added in ire_forward()
27687 		 * could have disappeared, causing the incomplete ire to also
27688 		 * disappear.  So we need to retreive the proper ipif for the
27689 		 * ire before looking in ctable.  In the case of IPMP, the
27690 		 * ipif may be on the IPMP ill, so look it up based on the
27691 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27692 		 * Then, we can verify that ire_ipif_seqid still exists.
27693 		 */
27694 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27695 		    NULL, NULL, NULL, NULL, ipst);
27696 		if (ill == NULL) {
27697 			ip1dbg(("ill for incomplete ire vanished\n"));
27698 			freemsg(mp); /* fake ire */
27699 			freeb(mp1);  /* dl_unitdata response */
27700 			return;
27701 		}
27702 
27703 		/* Get the outgoing ipif */
27704 		mutex_enter(&ill->ill_lock);
27705 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27706 		if (ipif == NULL) {
27707 			mutex_exit(&ill->ill_lock);
27708 			ill_refrele(ill);
27709 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27710 			freemsg(mp); /* fake_ire */
27711 			freeb(mp1);  /* dl_unitdata response */
27712 			return;
27713 		}
27714 
27715 		ipif_refhold_locked(ipif);
27716 		mutex_exit(&ill->ill_lock);
27717 		ill_refrele(ill);
27718 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27719 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27720 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27721 		ipif_refrele(ipif);
27722 		if (ire == NULL) {
27723 			/*
27724 			 * no ire was found; check if there is an nce
27725 			 * for this lookup; if it has no ire's pointing at it
27726 			 * cleanup.
27727 			 */
27728 			if ((nce = ndp_lookup_v4(q->q_ptr,
27729 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27730 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27731 			    B_FALSE)) != NULL) {
27732 				/*
27733 				 * cleanup:
27734 				 * We check for refcnt 2 (one for the nce
27735 				 * hash list + 1 for the ref taken by
27736 				 * ndp_lookup_v4) to check that there are
27737 				 * no ire's pointing at the nce.
27738 				 */
27739 				if (nce->nce_refcnt == 2)
27740 					ndp_delete(nce);
27741 				NCE_REFRELE(nce);
27742 			}
27743 			freeb(mp1);  /* dl_unitdata response */
27744 			freemsg(mp); /* fake ire */
27745 			return;
27746 		}
27747 
27748 		nce = ire->ire_nce;
27749 		DTRACE_PROBE2(ire__arpresolve__type,
27750 		    ire_t *, ire, nce_t *, nce);
27751 		mutex_enter(&nce->nce_lock);
27752 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27753 		if (nce->nce_state == ND_REACHABLE) {
27754 			/*
27755 			 * Someone resolved this before us;
27756 			 * our response is not needed any more.
27757 			 */
27758 			mutex_exit(&nce->nce_lock);
27759 			freeb(mp1);  /* dl_unitdata response */
27760 		} else {
27761 			ASSERT(nce->nce_res_mp == NULL);
27762 			nce->nce_res_mp = mp1;
27763 			nce->nce_state = ND_REACHABLE;
27764 			mutex_exit(&nce->nce_lock);
27765 			nce_fastpath(nce);
27766 		}
27767 		/*
27768 		 * The cached nce_t has been updated to be reachable;
27769 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27770 		 */
27771 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27772 		freemsg(mp);
27773 		/*
27774 		 * send out queued packets.
27775 		 */
27776 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27777 
27778 		IRE_REFRELE(ire);
27779 		return;
27780 	}
27781 	default:
27782 		break;
27783 	}
27784 	if (q->q_next) {
27785 		putnext(q, mp);
27786 	} else
27787 		freemsg(mp);
27788 	return;
27789 
27790 protonak:
27791 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27792 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27793 		qreply(q, mp);
27794 }
27795 
27796 /*
27797  * Process IP options in an outbound packet.  Modify the destination if there
27798  * is a source route option.
27799  * Returns non-zero if something fails in which case an ICMP error has been
27800  * sent and mp freed.
27801  */
27802 static int
27803 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27804     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27805 {
27806 	ipoptp_t	opts;
27807 	uchar_t		*opt;
27808 	uint8_t		optval;
27809 	uint8_t		optlen;
27810 	ipaddr_t	dst;
27811 	intptr_t	code = 0;
27812 	mblk_t		*mp;
27813 	ire_t		*ire = NULL;
27814 
27815 	ip2dbg(("ip_wput_options\n"));
27816 	mp = ipsec_mp;
27817 	if (mctl_present) {
27818 		mp = ipsec_mp->b_cont;
27819 	}
27820 
27821 	dst = ipha->ipha_dst;
27822 	for (optval = ipoptp_first(&opts, ipha);
27823 	    optval != IPOPT_EOL;
27824 	    optval = ipoptp_next(&opts)) {
27825 		opt = opts.ipoptp_cur;
27826 		optlen = opts.ipoptp_len;
27827 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27828 		    optval, optlen));
27829 		switch (optval) {
27830 			uint32_t off;
27831 		case IPOPT_SSRR:
27832 		case IPOPT_LSRR:
27833 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27834 				ip1dbg((
27835 				    "ip_wput_options: bad option offset\n"));
27836 				code = (char *)&opt[IPOPT_OLEN] -
27837 				    (char *)ipha;
27838 				goto param_prob;
27839 			}
27840 			off = opt[IPOPT_OFFSET];
27841 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27842 			    ntohl(dst)));
27843 			/*
27844 			 * For strict: verify that dst is directly
27845 			 * reachable.
27846 			 */
27847 			if (optval == IPOPT_SSRR) {
27848 				ire = ire_ftable_lookup(dst, 0, 0,
27849 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27850 				    msg_getlabel(mp),
27851 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27852 				if (ire == NULL) {
27853 					ip1dbg(("ip_wput_options: SSRR not"
27854 					    " directly reachable: 0x%x\n",
27855 					    ntohl(dst)));
27856 					goto bad_src_route;
27857 				}
27858 				ire_refrele(ire);
27859 			}
27860 			break;
27861 		case IPOPT_RR:
27862 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27863 				ip1dbg((
27864 				    "ip_wput_options: bad option offset\n"));
27865 				code = (char *)&opt[IPOPT_OLEN] -
27866 				    (char *)ipha;
27867 				goto param_prob;
27868 			}
27869 			break;
27870 		case IPOPT_TS:
27871 			/*
27872 			 * Verify that length >=5 and that there is either
27873 			 * room for another timestamp or that the overflow
27874 			 * counter is not maxed out.
27875 			 */
27876 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27877 			if (optlen < IPOPT_MINLEN_IT) {
27878 				goto param_prob;
27879 			}
27880 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27881 				ip1dbg((
27882 				    "ip_wput_options: bad option offset\n"));
27883 				code = (char *)&opt[IPOPT_OFFSET] -
27884 				    (char *)ipha;
27885 				goto param_prob;
27886 			}
27887 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27888 			case IPOPT_TS_TSONLY:
27889 				off = IPOPT_TS_TIMELEN;
27890 				break;
27891 			case IPOPT_TS_TSANDADDR:
27892 			case IPOPT_TS_PRESPEC:
27893 			case IPOPT_TS_PRESPEC_RFC791:
27894 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27895 				break;
27896 			default:
27897 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27898 				    (char *)ipha;
27899 				goto param_prob;
27900 			}
27901 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27902 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27903 				/*
27904 				 * No room and the overflow counter is 15
27905 				 * already.
27906 				 */
27907 				goto param_prob;
27908 			}
27909 			break;
27910 		}
27911 	}
27912 
27913 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27914 		return (0);
27915 
27916 	ip1dbg(("ip_wput_options: error processing IP options."));
27917 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27918 
27919 param_prob:
27920 	/*
27921 	 * Since ip_wput() isn't close to finished, we fill
27922 	 * in enough of the header for credible error reporting.
27923 	 */
27924 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27925 		/* Failed */
27926 		freemsg(ipsec_mp);
27927 		return (-1);
27928 	}
27929 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27930 	return (-1);
27931 
27932 bad_src_route:
27933 	/*
27934 	 * Since ip_wput() isn't close to finished, we fill
27935 	 * in enough of the header for credible error reporting.
27936 	 */
27937 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27938 		/* Failed */
27939 		freemsg(ipsec_mp);
27940 		return (-1);
27941 	}
27942 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27943 	return (-1);
27944 }
27945 
27946 /*
27947  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27948  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27949  * thru /etc/system.
27950  */
27951 #define	CONN_MAXDRAINCNT	64
27952 
27953 static void
27954 conn_drain_init(ip_stack_t *ipst)
27955 {
27956 	int i, j;
27957 	idl_tx_list_t *itl_tx;
27958 
27959 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27960 
27961 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27962 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27963 		/*
27964 		 * Default value of the number of drainers is the
27965 		 * number of cpus, subject to maximum of 8 drainers.
27966 		 */
27967 		if (boot_max_ncpus != -1)
27968 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27969 		else
27970 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27971 	}
27972 
27973 	ipst->ips_idl_tx_list =
27974 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
27975 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27976 		itl_tx =  &ipst->ips_idl_tx_list[i];
27977 		itl_tx->txl_drain_list =
27978 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27979 		    sizeof (idl_t), KM_SLEEP);
27980 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
27981 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
27982 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
27983 			    MUTEX_DEFAULT, NULL);
27984 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
27985 		}
27986 	}
27987 }
27988 
27989 static void
27990 conn_drain_fini(ip_stack_t *ipst)
27991 {
27992 	int i;
27993 	idl_tx_list_t *itl_tx;
27994 
27995 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27996 		itl_tx =  &ipst->ips_idl_tx_list[i];
27997 		kmem_free(itl_tx->txl_drain_list,
27998 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27999 	}
28000 	kmem_free(ipst->ips_idl_tx_list,
28001 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28002 	ipst->ips_idl_tx_list = NULL;
28003 }
28004 
28005 /*
28006  * Note: For an overview of how flowcontrol is handled in IP please see the
28007  * IP Flowcontrol notes at the top of this file.
28008  *
28009  * Flow control has blocked us from proceeding. Insert the given conn in one
28010  * of the conn drain lists. These conn wq's will be qenabled later on when
28011  * STREAMS flow control does a backenable. conn_walk_drain will enable
28012  * the first conn in each of these drain lists. Each of these qenabled conns
28013  * in turn enables the next in the list, after it runs, or when it closes,
28014  * thus sustaining the drain process.
28015  */
28016 void
28017 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28018 {
28019 	idl_t	*idl = tx_list->txl_drain_list;
28020 	uint_t	index;
28021 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28022 
28023 	mutex_enter(&connp->conn_lock);
28024 	if (connp->conn_state_flags & CONN_CLOSING) {
28025 		/*
28026 		 * The conn is closing as a result of which CONN_CLOSING
28027 		 * is set. Return.
28028 		 */
28029 		mutex_exit(&connp->conn_lock);
28030 		return;
28031 	} else if (connp->conn_idl == NULL) {
28032 		/*
28033 		 * Assign the next drain list round robin. We dont' use
28034 		 * a lock, and thus it may not be strictly round robin.
28035 		 * Atomicity of load/stores is enough to make sure that
28036 		 * conn_drain_list_index is always within bounds.
28037 		 */
28038 		index = tx_list->txl_drain_index;
28039 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28040 		connp->conn_idl = &tx_list->txl_drain_list[index];
28041 		index++;
28042 		if (index == ipst->ips_conn_drain_list_cnt)
28043 			index = 0;
28044 		tx_list->txl_drain_index = index;
28045 	}
28046 	mutex_exit(&connp->conn_lock);
28047 
28048 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28049 	if ((connp->conn_drain_prev != NULL) ||
28050 	    (connp->conn_state_flags & CONN_CLOSING)) {
28051 		/*
28052 		 * The conn is already in the drain list, OR
28053 		 * the conn is closing. We need to check again for
28054 		 * the closing case again since close can happen
28055 		 * after we drop the conn_lock, and before we
28056 		 * acquire the CONN_DRAIN_LIST_LOCK.
28057 		 */
28058 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28059 		return;
28060 	} else {
28061 		idl = connp->conn_idl;
28062 	}
28063 
28064 	/*
28065 	 * The conn is not in the drain list. Insert it at the
28066 	 * tail of the drain list. The drain list is circular
28067 	 * and doubly linked. idl_conn points to the 1st element
28068 	 * in the list.
28069 	 */
28070 	if (idl->idl_conn == NULL) {
28071 		idl->idl_conn = connp;
28072 		connp->conn_drain_next = connp;
28073 		connp->conn_drain_prev = connp;
28074 	} else {
28075 		conn_t *head = idl->idl_conn;
28076 
28077 		connp->conn_drain_next = head;
28078 		connp->conn_drain_prev = head->conn_drain_prev;
28079 		head->conn_drain_prev->conn_drain_next = connp;
28080 		head->conn_drain_prev = connp;
28081 	}
28082 	/*
28083 	 * For non streams based sockets assert flow control.
28084 	 */
28085 	if (IPCL_IS_NONSTR(connp)) {
28086 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28087 		(*connp->conn_upcalls->su_txq_full)
28088 		    (connp->conn_upper_handle, B_TRUE);
28089 	} else {
28090 		conn_setqfull(connp);
28091 		noenable(connp->conn_wq);
28092 	}
28093 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28094 }
28095 
28096 /*
28097  * This conn is closing, and we are called from ip_close. OR
28098  * This conn has been serviced by ip_wsrv, and we need to do the tail
28099  * processing.
28100  * If this conn is part of the drain list, we may need to sustain the drain
28101  * process by qenabling the next conn in the drain list. We may also need to
28102  * remove this conn from the list, if it is done.
28103  */
28104 static void
28105 conn_drain_tail(conn_t *connp, boolean_t closing)
28106 {
28107 	idl_t *idl;
28108 
28109 	/*
28110 	 * connp->conn_idl is stable at this point, and no lock is needed
28111 	 * to check it. If we are called from ip_close, close has already
28112 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28113 	 * called us only because conn_idl is non-null. If we are called thru
28114 	 * service, conn_idl could be null, but it cannot change because
28115 	 * service is single-threaded per queue, and there cannot be another
28116 	 * instance of service trying to call conn_drain_insert on this conn
28117 	 * now.
28118 	 */
28119 	ASSERT(!closing || (connp->conn_idl != NULL));
28120 
28121 	/*
28122 	 * If connp->conn_idl is null, the conn has not been inserted into any
28123 	 * drain list even once since creation of the conn. Just return.
28124 	 */
28125 	if (connp->conn_idl == NULL)
28126 		return;
28127 
28128 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28129 
28130 	if (connp->conn_drain_prev == NULL) {
28131 		/* This conn is currently not in the drain list.  */
28132 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28133 		return;
28134 	}
28135 	idl = connp->conn_idl;
28136 	if (idl->idl_conn_draining == connp) {
28137 		/*
28138 		 * This conn is the current drainer. If this is the last conn
28139 		 * in the drain list, we need to do more checks, in the 'if'
28140 		 * below. Otherwwise we need to just qenable the next conn,
28141 		 * to sustain the draining, and is handled in the 'else'
28142 		 * below.
28143 		 */
28144 		if (connp->conn_drain_next == idl->idl_conn) {
28145 			/*
28146 			 * This conn is the last in this list. This round
28147 			 * of draining is complete. If idl_repeat is set,
28148 			 * it means another flow enabling has happened from
28149 			 * the driver/streams and we need to another round
28150 			 * of draining.
28151 			 * If there are more than 2 conns in the drain list,
28152 			 * do a left rotate by 1, so that all conns except the
28153 			 * conn at the head move towards the head by 1, and the
28154 			 * the conn at the head goes to the tail. This attempts
28155 			 * a more even share for all queues that are being
28156 			 * drained.
28157 			 */
28158 			if ((connp->conn_drain_next != connp) &&
28159 			    (idl->idl_conn->conn_drain_next != connp)) {
28160 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28161 			}
28162 			if (idl->idl_repeat) {
28163 				qenable(idl->idl_conn->conn_wq);
28164 				idl->idl_conn_draining = idl->idl_conn;
28165 				idl->idl_repeat = 0;
28166 			} else {
28167 				idl->idl_conn_draining = NULL;
28168 			}
28169 		} else {
28170 			/*
28171 			 * If the next queue that we are now qenable'ing,
28172 			 * is closing, it will remove itself from this list
28173 			 * and qenable the subsequent queue in ip_close().
28174 			 * Serialization is acheived thru idl_lock.
28175 			 */
28176 			qenable(connp->conn_drain_next->conn_wq);
28177 			idl->idl_conn_draining = connp->conn_drain_next;
28178 		}
28179 	}
28180 	if (!connp->conn_did_putbq || closing) {
28181 		/*
28182 		 * Remove ourself from the drain list, if we did not do
28183 		 * a putbq, or if the conn is closing.
28184 		 * Note: It is possible that q->q_first is non-null. It means
28185 		 * that these messages landed after we did a enableok() in
28186 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28187 		 * service them.
28188 		 */
28189 		if (connp->conn_drain_next == connp) {
28190 			/* Singleton in the list */
28191 			ASSERT(connp->conn_drain_prev == connp);
28192 			idl->idl_conn = NULL;
28193 			idl->idl_conn_draining = NULL;
28194 		} else {
28195 			connp->conn_drain_prev->conn_drain_next =
28196 			    connp->conn_drain_next;
28197 			connp->conn_drain_next->conn_drain_prev =
28198 			    connp->conn_drain_prev;
28199 			if (idl->idl_conn == connp)
28200 				idl->idl_conn = connp->conn_drain_next;
28201 			ASSERT(idl->idl_conn_draining != connp);
28202 
28203 		}
28204 		connp->conn_drain_next = NULL;
28205 		connp->conn_drain_prev = NULL;
28206 
28207 		/*
28208 		 * For non streams based sockets open up flow control.
28209 		 */
28210 		if (IPCL_IS_NONSTR(connp)) {
28211 			(*connp->conn_upcalls->su_txq_full)
28212 			    (connp->conn_upper_handle, B_FALSE);
28213 		} else {
28214 			conn_clrqfull(connp);
28215 			enableok(connp->conn_wq);
28216 		}
28217 	}
28218 
28219 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28220 }
28221 
28222 /*
28223  * Write service routine. Shared perimeter entry point.
28224  * ip_wsrv can be called in any of the following ways.
28225  * 1. The device queue's messages has fallen below the low water mark
28226  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28227  *    the drain lists and backenable the first conn in each list.
28228  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28229  *    qenabled non-tcp upper layers. We start dequeing messages and call
28230  *    ip_wput for each message.
28231  */
28232 
28233 void
28234 ip_wsrv(queue_t *q)
28235 {
28236 	conn_t	*connp;
28237 	ill_t	*ill;
28238 	mblk_t	*mp;
28239 
28240 	if (q->q_next) {
28241 		ill = (ill_t *)q->q_ptr;
28242 		if (ill->ill_state_flags == 0) {
28243 			ip_stack_t *ipst = ill->ill_ipst;
28244 
28245 			/*
28246 			 * The device flow control has opened up.
28247 			 * Walk through conn drain lists and qenable the
28248 			 * first conn in each list. This makes sense only
28249 			 * if the stream is fully plumbed and setup.
28250 			 * Hence the if check above.
28251 			 */
28252 			ip1dbg(("ip_wsrv: walking\n"));
28253 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28254 		}
28255 		return;
28256 	}
28257 
28258 	connp = Q_TO_CONN(q);
28259 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28260 
28261 	/*
28262 	 * 1. Set conn_draining flag to signal that service is active.
28263 	 *
28264 	 * 2. ip_output determines whether it has been called from service,
28265 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28266 	 *    has been called from service.
28267 	 *
28268 	 * 3. Message ordering is preserved by the following logic.
28269 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28270 	 *    the message at the tail, if conn_draining is set (i.e. service
28271 	 *    is running) or if q->q_first is non-null.
28272 	 *
28273 	 *    ii. If ip_output is called from service, and if ip_output cannot
28274 	 *    putnext due to flow control, it does a putbq.
28275 	 *
28276 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28277 	 *    (causing an infinite loop).
28278 	 */
28279 	ASSERT(!connp->conn_did_putbq);
28280 
28281 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28282 		connp->conn_draining = 1;
28283 		noenable(q);
28284 		while ((mp = getq(q)) != NULL) {
28285 			ASSERT(CONN_Q(q));
28286 
28287 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28288 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28289 			if (connp->conn_did_putbq) {
28290 				/* ip_wput did a putbq */
28291 				break;
28292 			}
28293 		}
28294 		/*
28295 		 * At this point, a thread coming down from top, calling
28296 		 * ip_wput, may end up queueing the message. We have not yet
28297 		 * enabled the queue, so ip_wsrv won't be called again.
28298 		 * To avoid this race, check q->q_first again (in the loop)
28299 		 * If the other thread queued the message before we call
28300 		 * enableok(), we will catch it in the q->q_first check.
28301 		 * If the other thread queues the message after we call
28302 		 * enableok(), ip_wsrv will be called again by STREAMS.
28303 		 */
28304 		connp->conn_draining = 0;
28305 		enableok(q);
28306 	}
28307 
28308 	/* Enable the next conn for draining */
28309 	conn_drain_tail(connp, B_FALSE);
28310 
28311 	/*
28312 	 * conn_direct_blocked is used to indicate blocked
28313 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28314 	 * This is the only place where it is set without
28315 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28316 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28317 	 */
28318 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28319 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28320 		connp->conn_direct_blocked = B_FALSE;
28321 	}
28322 
28323 	connp->conn_did_putbq = 0;
28324 }
28325 
28326 /*
28327  * Callback to disable flow control in IP.
28328  *
28329  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28330  * is enabled.
28331  *
28332  * When MAC_TX() is not able to send any more packets, dld sets its queue
28333  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28334  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28335  * function and wakes up corresponding mac worker threads, which in turn
28336  * calls this callback function, and disables flow control.
28337  */
28338 void
28339 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28340 {
28341 	ill_t *ill = (ill_t *)arg;
28342 	ip_stack_t *ipst = ill->ill_ipst;
28343 	idl_tx_list_t *idl_txl;
28344 
28345 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28346 	mutex_enter(&idl_txl->txl_lock);
28347 	/* add code to to set a flag to indicate idl_txl is enabled */
28348 	conn_walk_drain(ipst, idl_txl);
28349 	mutex_exit(&idl_txl->txl_lock);
28350 }
28351 
28352 /*
28353  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28354  * of conns that need to be drained, check if drain is already in progress.
28355  * If so set the idl_repeat bit, indicating that the last conn in the list
28356  * needs to reinitiate the drain once again, for the list. If drain is not
28357  * in progress for the list, initiate the draining, by qenabling the 1st
28358  * conn in the list. The drain is self-sustaining, each qenabled conn will
28359  * in turn qenable the next conn, when it is done/blocked/closing.
28360  */
28361 static void
28362 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28363 {
28364 	int i;
28365 	idl_t *idl;
28366 
28367 	IP_STAT(ipst, ip_conn_walk_drain);
28368 
28369 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28370 		idl = &tx_list->txl_drain_list[i];
28371 		mutex_enter(&idl->idl_lock);
28372 		if (idl->idl_conn == NULL) {
28373 			mutex_exit(&idl->idl_lock);
28374 			continue;
28375 		}
28376 		/*
28377 		 * If this list is not being drained currently by
28378 		 * an ip_wsrv thread, start the process.
28379 		 */
28380 		if (idl->idl_conn_draining == NULL) {
28381 			ASSERT(idl->idl_repeat == 0);
28382 			qenable(idl->idl_conn->conn_wq);
28383 			idl->idl_conn_draining = idl->idl_conn;
28384 		} else {
28385 			idl->idl_repeat = 1;
28386 		}
28387 		mutex_exit(&idl->idl_lock);
28388 	}
28389 }
28390 
28391 /*
28392  * Determine if the ill and multicast aspects of that packets
28393  * "matches" the conn.
28394  */
28395 boolean_t
28396 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28397     zoneid_t zoneid)
28398 {
28399 	ill_t *bound_ill;
28400 	boolean_t found;
28401 	ipif_t *ipif;
28402 	ire_t *ire;
28403 	ipaddr_t dst, src;
28404 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28405 
28406 	dst = ipha->ipha_dst;
28407 	src = ipha->ipha_src;
28408 
28409 	/*
28410 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28411 	 * unicast, broadcast and multicast reception to
28412 	 * conn_incoming_ill. conn_wantpacket itself is called
28413 	 * only for BROADCAST and multicast.
28414 	 */
28415 	bound_ill = connp->conn_incoming_ill;
28416 	if (bound_ill != NULL) {
28417 		if (IS_IPMP(bound_ill)) {
28418 			if (bound_ill->ill_grp != ill->ill_grp)
28419 				return (B_FALSE);
28420 		} else {
28421 			if (bound_ill != ill)
28422 				return (B_FALSE);
28423 		}
28424 	}
28425 
28426 	if (!CLASSD(dst)) {
28427 		if (IPCL_ZONE_MATCH(connp, zoneid))
28428 			return (B_TRUE);
28429 		/*
28430 		 * The conn is in a different zone; we need to check that this
28431 		 * broadcast address is configured in the application's zone.
28432 		 */
28433 		ipif = ipif_get_next_ipif(NULL, ill);
28434 		if (ipif == NULL)
28435 			return (B_FALSE);
28436 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28437 		    connp->conn_zoneid, NULL,
28438 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28439 		ipif_refrele(ipif);
28440 		if (ire != NULL) {
28441 			ire_refrele(ire);
28442 			return (B_TRUE);
28443 		} else {
28444 			return (B_FALSE);
28445 		}
28446 	}
28447 
28448 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28449 	    connp->conn_zoneid == zoneid) {
28450 		/*
28451 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28452 		 * disabled, therefore we don't dispatch the multicast packet to
28453 		 * the sending zone.
28454 		 */
28455 		return (B_FALSE);
28456 	}
28457 
28458 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28459 		/*
28460 		 * Multicast packet on the loopback interface: we only match
28461 		 * conns who joined the group in the specified zone.
28462 		 */
28463 		return (B_FALSE);
28464 	}
28465 
28466 	if (connp->conn_multi_router) {
28467 		/* multicast packet and multicast router socket: send up */
28468 		return (B_TRUE);
28469 	}
28470 
28471 	mutex_enter(&connp->conn_lock);
28472 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28473 	mutex_exit(&connp->conn_lock);
28474 	return (found);
28475 }
28476 
28477 static void
28478 conn_setqfull(conn_t *connp)
28479 {
28480 	queue_t *q = connp->conn_wq;
28481 
28482 	if (!(q->q_flag & QFULL)) {
28483 		mutex_enter(QLOCK(q));
28484 		if (!(q->q_flag & QFULL)) {
28485 			/* still need to set QFULL */
28486 			q->q_flag |= QFULL;
28487 			mutex_exit(QLOCK(q));
28488 		} else {
28489 			mutex_exit(QLOCK(q));
28490 		}
28491 	}
28492 }
28493 
28494 static void
28495 conn_clrqfull(conn_t *connp)
28496 {
28497 	queue_t *q = connp->conn_wq;
28498 
28499 	if (q->q_flag & QFULL) {
28500 		mutex_enter(QLOCK(q));
28501 		if (q->q_flag & QFULL) {
28502 			q->q_flag &= ~QFULL;
28503 			mutex_exit(QLOCK(q));
28504 			if (q->q_flag & QWANTW)
28505 				qbackenable(q, 0);
28506 		} else {
28507 			mutex_exit(QLOCK(q));
28508 		}
28509 	}
28510 }
28511 
28512 /*
28513  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28514  */
28515 /* ARGSUSED */
28516 static void
28517 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28518 {
28519 	ill_t *ill = (ill_t *)q->q_ptr;
28520 	mblk_t	*mp1, *mp2;
28521 	ipif_t  *ipif;
28522 	int err = 0;
28523 	conn_t *connp = NULL;
28524 	ipsq_t	*ipsq;
28525 	arc_t	*arc;
28526 
28527 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28528 
28529 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28530 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28531 
28532 	ASSERT(IAM_WRITER_ILL(ill));
28533 	mp2 = mp->b_cont;
28534 	mp->b_cont = NULL;
28535 
28536 	/*
28537 	 * We have now received the arp bringup completion message
28538 	 * from ARP. Mark the arp bringup as done. Also if the arp
28539 	 * stream has already started closing, send up the AR_ARP_CLOSING
28540 	 * ack now since ARP is waiting in close for this ack.
28541 	 */
28542 	mutex_enter(&ill->ill_lock);
28543 	ill->ill_arp_bringup_pending = 0;
28544 	if (ill->ill_arp_closing) {
28545 		mutex_exit(&ill->ill_lock);
28546 		/* Let's reuse the mp for sending the ack */
28547 		arc = (arc_t *)mp->b_rptr;
28548 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28549 		arc->arc_cmd = AR_ARP_CLOSING;
28550 		qreply(q, mp);
28551 	} else {
28552 		mutex_exit(&ill->ill_lock);
28553 		freeb(mp);
28554 	}
28555 
28556 	ipsq = ill->ill_phyint->phyint_ipsq;
28557 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28558 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28559 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28560 	if (mp1 == NULL) {
28561 		/* bringup was aborted by the user */
28562 		freemsg(mp2);
28563 		return;
28564 	}
28565 
28566 	/*
28567 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28568 	 * must have an associated conn_t.  Otherwise, we're bringing this
28569 	 * interface back up as part of handling an asynchronous event (e.g.,
28570 	 * physical address change).
28571 	 */
28572 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28573 		ASSERT(connp != NULL);
28574 		q = CONNP_TO_WQ(connp);
28575 	} else {
28576 		ASSERT(connp == NULL);
28577 		q = ill->ill_rq;
28578 	}
28579 
28580 	/*
28581 	 * If the DL_BIND_REQ fails, it is noted
28582 	 * in arc_name_offset.
28583 	 */
28584 	err = *((int *)mp2->b_rptr);
28585 	if (err == 0) {
28586 		if (ipif->ipif_isv6) {
28587 			if ((err = ipif_up_done_v6(ipif)) != 0)
28588 				ip0dbg(("ip_arp_done: init failed\n"));
28589 		} else {
28590 			if ((err = ipif_up_done(ipif)) != 0)
28591 				ip0dbg(("ip_arp_done: init failed\n"));
28592 		}
28593 	} else {
28594 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28595 	}
28596 
28597 	freemsg(mp2);
28598 
28599 	if ((err == 0) && (ill->ill_up_ipifs)) {
28600 		err = ill_up_ipifs(ill, q, mp1);
28601 		if (err == EINPROGRESS)
28602 			return;
28603 	}
28604 
28605 	/*
28606 	 * If we have a moved ipif to bring up, and everything has succeeded
28607 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28608 	 * down -- the admin can try to bring it up by hand if need be.
28609 	 */
28610 	if (ill->ill_move_ipif != NULL) {
28611 		ipif = ill->ill_move_ipif;
28612 		ill->ill_move_ipif = NULL;
28613 		if (err == 0) {
28614 			err = ipif_up(ipif, q, mp1);
28615 			if (err == EINPROGRESS)
28616 				return;
28617 		}
28618 	}
28619 
28620 	/*
28621 	 * The operation must complete without EINPROGRESS since
28622 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28623 	 * operation will be stuck forever in the ipsq.
28624 	 */
28625 	ASSERT(err != EINPROGRESS);
28626 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28627 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28628 	else
28629 		ipsq_current_finish(ipsq);
28630 }
28631 
28632 /* Allocate the private structure */
28633 static int
28634 ip_priv_alloc(void **bufp)
28635 {
28636 	void	*buf;
28637 
28638 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28639 		return (ENOMEM);
28640 
28641 	*bufp = buf;
28642 	return (0);
28643 }
28644 
28645 /* Function to delete the private structure */
28646 void
28647 ip_priv_free(void *buf)
28648 {
28649 	ASSERT(buf != NULL);
28650 	kmem_free(buf, sizeof (ip_priv_t));
28651 }
28652 
28653 /*
28654  * The entry point for IPPF processing.
28655  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28656  * routine just returns.
28657  *
28658  * When called, ip_process generates an ipp_packet_t structure
28659  * which holds the state information for this packet and invokes the
28660  * the classifier (via ipp_packet_process). The classification, depending on
28661  * configured filters, results in a list of actions for this packet. Invoking
28662  * an action may cause the packet to be dropped, in which case the resulting
28663  * mblk (*mpp) is NULL. proc indicates the callout position for
28664  * this packet and ill_index is the interface this packet on or will leave
28665  * on (inbound and outbound resp.).
28666  */
28667 void
28668 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28669 {
28670 	mblk_t		*mp;
28671 	ip_priv_t	*priv;
28672 	ipp_action_id_t	aid;
28673 	int		rc = 0;
28674 	ipp_packet_t	*pp;
28675 #define	IP_CLASS	"ip"
28676 
28677 	/* If the classifier is not loaded, return  */
28678 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28679 		return;
28680 	}
28681 
28682 	mp = *mpp;
28683 	ASSERT(mp != NULL);
28684 
28685 	/* Allocate the packet structure */
28686 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28687 	if (rc != 0) {
28688 		*mpp = NULL;
28689 		freemsg(mp);
28690 		return;
28691 	}
28692 
28693 	/* Allocate the private structure */
28694 	rc = ip_priv_alloc((void **)&priv);
28695 	if (rc != 0) {
28696 		*mpp = NULL;
28697 		freemsg(mp);
28698 		ipp_packet_free(pp);
28699 		return;
28700 	}
28701 	priv->proc = proc;
28702 	priv->ill_index = ill_index;
28703 	ipp_packet_set_private(pp, priv, ip_priv_free);
28704 	ipp_packet_set_data(pp, mp);
28705 
28706 	/* Invoke the classifier */
28707 	rc = ipp_packet_process(&pp);
28708 	if (pp != NULL) {
28709 		mp = ipp_packet_get_data(pp);
28710 		ipp_packet_free(pp);
28711 		if (rc != 0) {
28712 			freemsg(mp);
28713 			*mpp = NULL;
28714 		}
28715 	} else {
28716 		*mpp = NULL;
28717 	}
28718 #undef	IP_CLASS
28719 }
28720 
28721 /*
28722  * Propagate a multicast group membership operation (add/drop) on
28723  * all the interfaces crossed by the related multirt routes.
28724  * The call is considered successful if the operation succeeds
28725  * on at least one interface.
28726  */
28727 static int
28728 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28729     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28730     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28731     mblk_t *first_mp)
28732 {
28733 	ire_t		*ire_gw;
28734 	irb_t		*irb;
28735 	int		error = 0;
28736 	opt_restart_t	*or;
28737 	ip_stack_t	*ipst = ire->ire_ipst;
28738 
28739 	irb = ire->ire_bucket;
28740 	ASSERT(irb != NULL);
28741 
28742 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28743 
28744 	or = (opt_restart_t *)first_mp->b_rptr;
28745 	IRB_REFHOLD(irb);
28746 	for (; ire != NULL; ire = ire->ire_next) {
28747 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28748 			continue;
28749 		if (ire->ire_addr != group)
28750 			continue;
28751 
28752 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28753 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28754 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28755 		/* No resolver exists for the gateway; skip this ire. */
28756 		if (ire_gw == NULL)
28757 			continue;
28758 
28759 		/*
28760 		 * This function can return EINPROGRESS. If so the operation
28761 		 * will be restarted from ip_restart_optmgmt which will
28762 		 * call ip_opt_set and option processing will restart for
28763 		 * this option. So we may end up calling 'fn' more than once.
28764 		 * This requires that 'fn' is idempotent except for the
28765 		 * return value. The operation is considered a success if
28766 		 * it succeeds at least once on any one interface.
28767 		 */
28768 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28769 		    NULL, fmode, src, first_mp);
28770 		if (error == 0)
28771 			or->or_private = CGTP_MCAST_SUCCESS;
28772 
28773 		if (ip_debug > 0) {
28774 			ulong_t	off;
28775 			char	*ksym;
28776 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28777 			ip2dbg(("ip_multirt_apply_membership: "
28778 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28779 			    "error %d [success %u]\n",
28780 			    ksym ? ksym : "?",
28781 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28782 			    error, or->or_private));
28783 		}
28784 
28785 		ire_refrele(ire_gw);
28786 		if (error == EINPROGRESS) {
28787 			IRB_REFRELE(irb);
28788 			return (error);
28789 		}
28790 	}
28791 	IRB_REFRELE(irb);
28792 	/*
28793 	 * Consider the call as successful if we succeeded on at least
28794 	 * one interface. Otherwise, return the last encountered error.
28795 	 */
28796 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28797 }
28798 
28799 /*
28800  * Issue a warning regarding a route crossing an interface with an
28801  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28802  * amount of time is logged.
28803  */
28804 static void
28805 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28806 {
28807 	hrtime_t	current = gethrtime();
28808 	char		buf[INET_ADDRSTRLEN];
28809 	ip_stack_t	*ipst = ire->ire_ipst;
28810 
28811 	/* Convert interval in ms to hrtime in ns */
28812 	if (ipst->ips_multirt_bad_mtu_last_time +
28813 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28814 	    current) {
28815 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28816 		    "to %s, incorrect MTU %u (expected %u)\n",
28817 		    ip_dot_addr(ire->ire_addr, buf),
28818 		    ire->ire_max_frag, max_frag);
28819 
28820 		ipst->ips_multirt_bad_mtu_last_time = current;
28821 	}
28822 }
28823 
28824 /*
28825  * Get the CGTP (multirouting) filtering status.
28826  * If 0, the CGTP hooks are transparent.
28827  */
28828 /* ARGSUSED */
28829 static int
28830 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28831 {
28832 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28833 
28834 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28835 	return (0);
28836 }
28837 
28838 /*
28839  * Set the CGTP (multirouting) filtering status.
28840  * If the status is changed from active to transparent
28841  * or from transparent to active, forward the new status
28842  * to the filtering module (if loaded).
28843  */
28844 /* ARGSUSED */
28845 static int
28846 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28847     cred_t *ioc_cr)
28848 {
28849 	long		new_value;
28850 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28851 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28852 
28853 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28854 		return (EPERM);
28855 
28856 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28857 	    new_value < 0 || new_value > 1) {
28858 		return (EINVAL);
28859 	}
28860 
28861 	if ((!*ip_cgtp_filter_value) && new_value) {
28862 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28863 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28864 		    " (module not loaded)" : "");
28865 	}
28866 	if (*ip_cgtp_filter_value && (!new_value)) {
28867 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28868 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28869 		    " (module not loaded)" : "");
28870 	}
28871 
28872 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28873 		int	res;
28874 		netstackid_t stackid;
28875 
28876 		stackid = ipst->ips_netstack->netstack_stackid;
28877 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28878 		    new_value);
28879 		if (res)
28880 			return (res);
28881 	}
28882 
28883 	*ip_cgtp_filter_value = (boolean_t)new_value;
28884 
28885 	return (0);
28886 }
28887 
28888 /*
28889  * Return the expected CGTP hooks version number.
28890  */
28891 int
28892 ip_cgtp_filter_supported(void)
28893 {
28894 	return (ip_cgtp_filter_rev);
28895 }
28896 
28897 /*
28898  * CGTP hooks can be registered by invoking this function.
28899  * Checks that the version number matches.
28900  */
28901 int
28902 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28903 {
28904 	netstack_t *ns;
28905 	ip_stack_t *ipst;
28906 
28907 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28908 		return (ENOTSUP);
28909 
28910 	ns = netstack_find_by_stackid(stackid);
28911 	if (ns == NULL)
28912 		return (EINVAL);
28913 	ipst = ns->netstack_ip;
28914 	ASSERT(ipst != NULL);
28915 
28916 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28917 		netstack_rele(ns);
28918 		return (EALREADY);
28919 	}
28920 
28921 	ipst->ips_ip_cgtp_filter_ops = ops;
28922 	netstack_rele(ns);
28923 	return (0);
28924 }
28925 
28926 /*
28927  * CGTP hooks can be unregistered by invoking this function.
28928  * Returns ENXIO if there was no registration.
28929  * Returns EBUSY if the ndd variable has not been turned off.
28930  */
28931 int
28932 ip_cgtp_filter_unregister(netstackid_t stackid)
28933 {
28934 	netstack_t *ns;
28935 	ip_stack_t *ipst;
28936 
28937 	ns = netstack_find_by_stackid(stackid);
28938 	if (ns == NULL)
28939 		return (EINVAL);
28940 	ipst = ns->netstack_ip;
28941 	ASSERT(ipst != NULL);
28942 
28943 	if (ipst->ips_ip_cgtp_filter) {
28944 		netstack_rele(ns);
28945 		return (EBUSY);
28946 	}
28947 
28948 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28949 		netstack_rele(ns);
28950 		return (ENXIO);
28951 	}
28952 	ipst->ips_ip_cgtp_filter_ops = NULL;
28953 	netstack_rele(ns);
28954 	return (0);
28955 }
28956 
28957 /*
28958  * Check whether there is a CGTP filter registration.
28959  * Returns non-zero if there is a registration, otherwise returns zero.
28960  * Note: returns zero if bad stackid.
28961  */
28962 int
28963 ip_cgtp_filter_is_registered(netstackid_t stackid)
28964 {
28965 	netstack_t *ns;
28966 	ip_stack_t *ipst;
28967 	int ret;
28968 
28969 	ns = netstack_find_by_stackid(stackid);
28970 	if (ns == NULL)
28971 		return (0);
28972 	ipst = ns->netstack_ip;
28973 	ASSERT(ipst != NULL);
28974 
28975 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28976 		ret = 1;
28977 	else
28978 		ret = 0;
28979 
28980 	netstack_rele(ns);
28981 	return (ret);
28982 }
28983 
28984 static int
28985 ip_squeue_switch(int val)
28986 {
28987 	int rval = SQ_FILL;
28988 
28989 	switch (val) {
28990 	case IP_SQUEUE_ENTER_NODRAIN:
28991 		rval = SQ_NODRAIN;
28992 		break;
28993 	case IP_SQUEUE_ENTER:
28994 		rval = SQ_PROCESS;
28995 		break;
28996 	default:
28997 		break;
28998 	}
28999 	return (rval);
29000 }
29001 
29002 /* ARGSUSED */
29003 static int
29004 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29005     caddr_t addr, cred_t *cr)
29006 {
29007 	int *v = (int *)addr;
29008 	long new_value;
29009 
29010 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29011 		return (EPERM);
29012 
29013 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29014 		return (EINVAL);
29015 
29016 	ip_squeue_flag = ip_squeue_switch(new_value);
29017 	*v = new_value;
29018 	return (0);
29019 }
29020 
29021 /*
29022  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29023  * ip_debug.
29024  */
29025 /* ARGSUSED */
29026 static int
29027 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29028     caddr_t addr, cred_t *cr)
29029 {
29030 	int *v = (int *)addr;
29031 	long new_value;
29032 
29033 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29034 		return (EPERM);
29035 
29036 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29037 		return (EINVAL);
29038 
29039 	*v = new_value;
29040 	return (0);
29041 }
29042 
29043 static void *
29044 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29045 {
29046 	kstat_t *ksp;
29047 
29048 	ip_stat_t template = {
29049 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29050 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29051 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29052 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29053 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29054 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29055 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29056 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29057 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29058 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29059 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29060 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29061 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29062 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29063 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29064 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29065 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29066 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29067 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29068 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29069 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29070 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29071 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29072 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29073 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29074 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29075 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29076 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29077 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29078 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29079 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29080 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29081 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29082 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29083 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29084 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29085 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29086 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29087 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29088 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29089 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29090 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29091 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29092 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29093 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29094 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29095 	};
29096 
29097 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29098 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29099 	    KSTAT_FLAG_VIRTUAL, stackid);
29100 
29101 	if (ksp == NULL)
29102 		return (NULL);
29103 
29104 	bcopy(&template, ip_statisticsp, sizeof (template));
29105 	ksp->ks_data = (void *)ip_statisticsp;
29106 	ksp->ks_private = (void *)(uintptr_t)stackid;
29107 
29108 	kstat_install(ksp);
29109 	return (ksp);
29110 }
29111 
29112 static void
29113 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29114 {
29115 	if (ksp != NULL) {
29116 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29117 		kstat_delete_netstack(ksp, stackid);
29118 	}
29119 }
29120 
29121 static void *
29122 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29123 {
29124 	kstat_t	*ksp;
29125 
29126 	ip_named_kstat_t template = {
29127 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29128 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29129 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29130 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29131 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29132 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29133 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29134 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29135 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29136 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29137 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29138 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29139 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29140 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29141 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29142 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29143 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29144 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29145 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29146 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29147 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29148 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29149 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29150 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29151 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29152 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29153 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29154 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29155 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29156 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29157 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29158 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29159 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29160 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29161 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29162 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29163 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29164 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29165 	};
29166 
29167 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29168 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29169 	if (ksp == NULL || ksp->ks_data == NULL)
29170 		return (NULL);
29171 
29172 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29173 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29174 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29175 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29176 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29177 
29178 	template.netToMediaEntrySize.value.i32 =
29179 	    sizeof (mib2_ipNetToMediaEntry_t);
29180 
29181 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29182 
29183 	bcopy(&template, ksp->ks_data, sizeof (template));
29184 	ksp->ks_update = ip_kstat_update;
29185 	ksp->ks_private = (void *)(uintptr_t)stackid;
29186 
29187 	kstat_install(ksp);
29188 	return (ksp);
29189 }
29190 
29191 static void
29192 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29193 {
29194 	if (ksp != NULL) {
29195 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29196 		kstat_delete_netstack(ksp, stackid);
29197 	}
29198 }
29199 
29200 static int
29201 ip_kstat_update(kstat_t *kp, int rw)
29202 {
29203 	ip_named_kstat_t *ipkp;
29204 	mib2_ipIfStatsEntry_t ipmib;
29205 	ill_walk_context_t ctx;
29206 	ill_t *ill;
29207 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29208 	netstack_t	*ns;
29209 	ip_stack_t	*ipst;
29210 
29211 	if (kp == NULL || kp->ks_data == NULL)
29212 		return (EIO);
29213 
29214 	if (rw == KSTAT_WRITE)
29215 		return (EACCES);
29216 
29217 	ns = netstack_find_by_stackid(stackid);
29218 	if (ns == NULL)
29219 		return (-1);
29220 	ipst = ns->netstack_ip;
29221 	if (ipst == NULL) {
29222 		netstack_rele(ns);
29223 		return (-1);
29224 	}
29225 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29226 
29227 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29228 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29229 	ill = ILL_START_WALK_V4(&ctx, ipst);
29230 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29231 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29232 	rw_exit(&ipst->ips_ill_g_lock);
29233 
29234 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29235 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29236 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29237 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29238 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29239 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29240 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29241 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29242 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29243 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29244 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29245 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29246 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29247 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29248 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29249 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29250 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29251 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29252 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29253 
29254 	ipkp->routingDiscards.value.ui32 =	0;
29255 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29256 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29257 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29258 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29259 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29260 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29261 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29262 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29263 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29264 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29265 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29266 
29267 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29268 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29269 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29270 
29271 	netstack_rele(ns);
29272 
29273 	return (0);
29274 }
29275 
29276 static void *
29277 icmp_kstat_init(netstackid_t stackid)
29278 {
29279 	kstat_t	*ksp;
29280 
29281 	icmp_named_kstat_t template = {
29282 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29283 		{ "inErrors",		KSTAT_DATA_UINT32 },
29284 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29285 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29286 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29287 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29288 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29289 		{ "inEchos",		KSTAT_DATA_UINT32 },
29290 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29291 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29292 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29293 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29294 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29295 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29296 		{ "outErrors",		KSTAT_DATA_UINT32 },
29297 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29298 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29299 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29300 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29301 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29302 		{ "outEchos",		KSTAT_DATA_UINT32 },
29303 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29304 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29305 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29306 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29307 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29308 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29309 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29310 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29311 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29312 		{ "outDrops",		KSTAT_DATA_UINT32 },
29313 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29314 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29315 	};
29316 
29317 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29318 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29319 	if (ksp == NULL || ksp->ks_data == NULL)
29320 		return (NULL);
29321 
29322 	bcopy(&template, ksp->ks_data, sizeof (template));
29323 
29324 	ksp->ks_update = icmp_kstat_update;
29325 	ksp->ks_private = (void *)(uintptr_t)stackid;
29326 
29327 	kstat_install(ksp);
29328 	return (ksp);
29329 }
29330 
29331 static void
29332 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29333 {
29334 	if (ksp != NULL) {
29335 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29336 		kstat_delete_netstack(ksp, stackid);
29337 	}
29338 }
29339 
29340 static int
29341 icmp_kstat_update(kstat_t *kp, int rw)
29342 {
29343 	icmp_named_kstat_t *icmpkp;
29344 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29345 	netstack_t	*ns;
29346 	ip_stack_t	*ipst;
29347 
29348 	if ((kp == NULL) || (kp->ks_data == NULL))
29349 		return (EIO);
29350 
29351 	if (rw == KSTAT_WRITE)
29352 		return (EACCES);
29353 
29354 	ns = netstack_find_by_stackid(stackid);
29355 	if (ns == NULL)
29356 		return (-1);
29357 	ipst = ns->netstack_ip;
29358 	if (ipst == NULL) {
29359 		netstack_rele(ns);
29360 		return (-1);
29361 	}
29362 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29363 
29364 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29365 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29366 	icmpkp->inDestUnreachs.value.ui32 =
29367 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29368 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29369 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29370 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29371 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29372 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29373 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29374 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29375 	icmpkp->inTimestampReps.value.ui32 =
29376 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29377 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29378 	icmpkp->inAddrMaskReps.value.ui32 =
29379 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29380 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29381 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29382 	icmpkp->outDestUnreachs.value.ui32 =
29383 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29384 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29385 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29386 	icmpkp->outSrcQuenchs.value.ui32 =
29387 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29388 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29389 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29390 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29391 	icmpkp->outTimestamps.value.ui32 =
29392 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29393 	icmpkp->outTimestampReps.value.ui32 =
29394 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29395 	icmpkp->outAddrMasks.value.ui32 =
29396 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29397 	icmpkp->outAddrMaskReps.value.ui32 =
29398 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29399 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29400 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29401 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29402 	icmpkp->outFragNeeded.value.ui32 =
29403 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29404 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29405 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29406 	icmpkp->inBadRedirects.value.ui32 =
29407 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29408 
29409 	netstack_rele(ns);
29410 	return (0);
29411 }
29412 
29413 /*
29414  * This is the fanout function for raw socket opened for SCTP.  Note
29415  * that it is called after SCTP checks that there is no socket which
29416  * wants a packet.  Then before SCTP handles this out of the blue packet,
29417  * this function is called to see if there is any raw socket for SCTP.
29418  * If there is and it is bound to the correct address, the packet will
29419  * be sent to that socket.  Note that only one raw socket can be bound to
29420  * a port.  This is assured in ipcl_sctp_hash_insert();
29421  */
29422 void
29423 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29424     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29425     zoneid_t zoneid)
29426 {
29427 	conn_t		*connp;
29428 	queue_t		*rq;
29429 	mblk_t		*first_mp;
29430 	boolean_t	secure;
29431 	ip6_t		*ip6h;
29432 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29433 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29434 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29435 	boolean_t	sctp_csum_err = B_FALSE;
29436 
29437 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29438 		sctp_csum_err = B_TRUE;
29439 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29440 	}
29441 
29442 	first_mp = mp;
29443 	if (mctl_present) {
29444 		mp = first_mp->b_cont;
29445 		secure = ipsec_in_is_secure(first_mp);
29446 		ASSERT(mp != NULL);
29447 	} else {
29448 		secure = B_FALSE;
29449 	}
29450 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29451 
29452 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29453 	if (connp == NULL) {
29454 		/*
29455 		 * Although raw sctp is not summed, OOB chunks must be.
29456 		 * Drop the packet here if the sctp checksum failed.
29457 		 */
29458 		if (sctp_csum_err) {
29459 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29460 			freemsg(first_mp);
29461 			return;
29462 		}
29463 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29464 		return;
29465 	}
29466 	rq = connp->conn_rq;
29467 	if (!canputnext(rq)) {
29468 		CONN_DEC_REF(connp);
29469 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29470 		freemsg(first_mp);
29471 		return;
29472 	}
29473 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29474 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29475 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29476 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29477 		if (first_mp == NULL) {
29478 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29479 			CONN_DEC_REF(connp);
29480 			return;
29481 		}
29482 	}
29483 	/*
29484 	 * We probably should not send M_CTL message up to
29485 	 * raw socket.
29486 	 */
29487 	if (mctl_present)
29488 		freeb(first_mp);
29489 
29490 	/* Initiate IPPF processing here if needed. */
29491 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29492 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29493 		ip_process(IPP_LOCAL_IN, &mp,
29494 		    recv_ill->ill_phyint->phyint_ifindex);
29495 		if (mp == NULL) {
29496 			CONN_DEC_REF(connp);
29497 			return;
29498 		}
29499 	}
29500 
29501 	if (connp->conn_recvif || connp->conn_recvslla ||
29502 	    ((connp->conn_ip_recvpktinfo ||
29503 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29504 	    (flags & IP_FF_IPINFO))) {
29505 		int in_flags = 0;
29506 
29507 		/*
29508 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29509 		 * IPF_RECVIF.
29510 		 */
29511 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29512 			in_flags = IPF_RECVIF;
29513 		}
29514 		if (connp->conn_recvslla) {
29515 			in_flags |= IPF_RECVSLLA;
29516 		}
29517 		if (isv4) {
29518 			mp = ip_add_info(mp, recv_ill, in_flags,
29519 			    IPCL_ZONEID(connp), ipst);
29520 		} else {
29521 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29522 			if (mp == NULL) {
29523 				BUMP_MIB(recv_ill->ill_ip_mib,
29524 				    ipIfStatsInDiscards);
29525 				CONN_DEC_REF(connp);
29526 				return;
29527 			}
29528 		}
29529 	}
29530 
29531 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29532 	/*
29533 	 * We are sending the IPSEC_IN message also up. Refer
29534 	 * to comments above this function.
29535 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29536 	 */
29537 	(connp->conn_recv)(connp, mp, NULL);
29538 	CONN_DEC_REF(connp);
29539 }
29540 
29541 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29542 {									\
29543 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29544 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29545 }
29546 /*
29547  * This function should be called only if all packet processing
29548  * including fragmentation is complete. Callers of this function
29549  * must set mp->b_prev to one of these values:
29550  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29551  * prior to handing over the mp as first argument to this function.
29552  *
29553  * If the ire passed by caller is incomplete, this function
29554  * queues the packet and if necessary, sends ARP request and bails.
29555  * If the ire passed is fully resolved, we simply prepend
29556  * the link-layer header to the packet, do ipsec hw acceleration
29557  * work if necessary, and send the packet out on the wire.
29558  *
29559  * NOTE: IPsec will only call this function with fully resolved
29560  * ires if hw acceleration is involved.
29561  * TODO list :
29562  * 	a Handle M_MULTIDATA so that
29563  *	  tcp_multisend->tcp_multisend_data can
29564  *	  call ip_xmit_v4 directly
29565  *	b Handle post-ARP work for fragments so that
29566  *	  ip_wput_frag can call this function.
29567  */
29568 ipxmit_state_t
29569 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29570     boolean_t flow_ctl_enabled, conn_t *connp)
29571 {
29572 	nce_t		*arpce;
29573 	ipha_t		*ipha;
29574 	queue_t		*q;
29575 	int		ill_index;
29576 	mblk_t		*nxt_mp, *first_mp;
29577 	boolean_t	xmit_drop = B_FALSE;
29578 	ip_proc_t	proc;
29579 	ill_t		*out_ill;
29580 	int		pkt_len;
29581 
29582 	arpce = ire->ire_nce;
29583 	ASSERT(arpce != NULL);
29584 
29585 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29586 
29587 	mutex_enter(&arpce->nce_lock);
29588 	switch (arpce->nce_state) {
29589 	case ND_REACHABLE:
29590 		/* If there are other queued packets, queue this packet */
29591 		if (arpce->nce_qd_mp != NULL) {
29592 			if (mp != NULL)
29593 				nce_queue_mp_common(arpce, mp, B_FALSE);
29594 			mp = arpce->nce_qd_mp;
29595 		}
29596 		arpce->nce_qd_mp = NULL;
29597 		mutex_exit(&arpce->nce_lock);
29598 
29599 		/*
29600 		 * Flush the queue.  In the common case, where the
29601 		 * ARP is already resolved,  it will go through the
29602 		 * while loop only once.
29603 		 */
29604 		while (mp != NULL) {
29605 
29606 			nxt_mp = mp->b_next;
29607 			mp->b_next = NULL;
29608 			ASSERT(mp->b_datap->db_type != M_CTL);
29609 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29610 			/*
29611 			 * This info is needed for IPQOS to do COS marking
29612 			 * in ip_wput_attach_llhdr->ip_process.
29613 			 */
29614 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29615 			mp->b_prev = NULL;
29616 
29617 			/* set up ill index for outbound qos processing */
29618 			out_ill = ire_to_ill(ire);
29619 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29620 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29621 			    ill_index, &ipha);
29622 			if (first_mp == NULL) {
29623 				xmit_drop = B_TRUE;
29624 				BUMP_MIB(out_ill->ill_ip_mib,
29625 				    ipIfStatsOutDiscards);
29626 				goto next_mp;
29627 			}
29628 
29629 			/* non-ipsec hw accel case */
29630 			if (io == NULL || !io->ipsec_out_accelerated) {
29631 				/* send it */
29632 				q = ire->ire_stq;
29633 				if (proc == IPP_FWD_OUT) {
29634 					UPDATE_IB_PKT_COUNT(ire);
29635 				} else {
29636 					UPDATE_OB_PKT_COUNT(ire);
29637 				}
29638 				ire->ire_last_used_time = lbolt;
29639 
29640 				if (flow_ctl_enabled || canputnext(q)) {
29641 					if (proc == IPP_FWD_OUT) {
29642 
29643 					BUMP_MIB(out_ill->ill_ip_mib,
29644 					    ipIfStatsHCOutForwDatagrams);
29645 
29646 					}
29647 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29648 					    pkt_len);
29649 
29650 					DTRACE_IP7(send, mblk_t *, first_mp,
29651 					    conn_t *, NULL, void_ip_t *, ipha,
29652 					    __dtrace_ipsr_ill_t *, out_ill,
29653 					    ipha_t *, ipha, ip6_t *, NULL, int,
29654 					    0);
29655 
29656 					ILL_SEND_TX(out_ill,
29657 					    ire, connp, first_mp, 0, connp);
29658 				} else {
29659 					BUMP_MIB(out_ill->ill_ip_mib,
29660 					    ipIfStatsOutDiscards);
29661 					xmit_drop = B_TRUE;
29662 					freemsg(first_mp);
29663 				}
29664 			} else {
29665 				/*
29666 				 * Safety Pup says: make sure this
29667 				 *  is going to the right interface!
29668 				 */
29669 				ill_t *ill1 =
29670 				    (ill_t *)ire->ire_stq->q_ptr;
29671 				int ifindex =
29672 				    ill1->ill_phyint->phyint_ifindex;
29673 				if (ifindex !=
29674 				    io->ipsec_out_capab_ill_index) {
29675 					xmit_drop = B_TRUE;
29676 					freemsg(mp);
29677 				} else {
29678 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29679 					    pkt_len);
29680 
29681 					DTRACE_IP7(send, mblk_t *, first_mp,
29682 					    conn_t *, NULL, void_ip_t *, ipha,
29683 					    __dtrace_ipsr_ill_t *, ill1,
29684 					    ipha_t *, ipha, ip6_t *, NULL,
29685 					    int, 0);
29686 
29687 					ipsec_hw_putnext(ire->ire_stq, mp);
29688 				}
29689 			}
29690 next_mp:
29691 			mp = nxt_mp;
29692 		} /* while (mp != NULL) */
29693 		if (xmit_drop)
29694 			return (SEND_FAILED);
29695 		else
29696 			return (SEND_PASSED);
29697 
29698 	case ND_INITIAL:
29699 	case ND_INCOMPLETE:
29700 
29701 		/*
29702 		 * While we do send off packets to dests that
29703 		 * use fully-resolved CGTP routes, we do not
29704 		 * handle unresolved CGTP routes.
29705 		 */
29706 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29707 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29708 
29709 		if (mp != NULL) {
29710 			/* queue the packet */
29711 			nce_queue_mp_common(arpce, mp, B_FALSE);
29712 		}
29713 
29714 		if (arpce->nce_state == ND_INCOMPLETE) {
29715 			mutex_exit(&arpce->nce_lock);
29716 			DTRACE_PROBE3(ip__xmit__incomplete,
29717 			    (ire_t *), ire, (mblk_t *), mp,
29718 			    (ipsec_out_t *), io);
29719 			return (LOOKUP_IN_PROGRESS);
29720 		}
29721 
29722 		arpce->nce_state = ND_INCOMPLETE;
29723 		mutex_exit(&arpce->nce_lock);
29724 
29725 		/*
29726 		 * Note that ire_add() (called from ire_forward())
29727 		 * holds a ref on the ire until ARP is completed.
29728 		 */
29729 		ire_arpresolve(ire);
29730 		return (LOOKUP_IN_PROGRESS);
29731 	default:
29732 		ASSERT(0);
29733 		mutex_exit(&arpce->nce_lock);
29734 		return (LLHDR_RESLV_FAILED);
29735 	}
29736 }
29737 
29738 #undef	UPDATE_IP_MIB_OB_COUNTERS
29739 
29740 /*
29741  * Return B_TRUE if the buffers differ in length or content.
29742  * This is used for comparing extension header buffers.
29743  * Note that an extension header would be declared different
29744  * even if all that changed was the next header value in that header i.e.
29745  * what really changed is the next extension header.
29746  */
29747 boolean_t
29748 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29749     uint_t blen)
29750 {
29751 	if (!b_valid)
29752 		blen = 0;
29753 
29754 	if (alen != blen)
29755 		return (B_TRUE);
29756 	if (alen == 0)
29757 		return (B_FALSE);	/* Both zero length */
29758 	return (bcmp(abuf, bbuf, alen));
29759 }
29760 
29761 /*
29762  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29763  * Return B_FALSE if memory allocation fails - don't change any state!
29764  */
29765 boolean_t
29766 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29767     const void *src, uint_t srclen)
29768 {
29769 	void *dst;
29770 
29771 	if (!src_valid)
29772 		srclen = 0;
29773 
29774 	ASSERT(*dstlenp == 0);
29775 	if (src != NULL && srclen != 0) {
29776 		dst = mi_alloc(srclen, BPRI_MED);
29777 		if (dst == NULL)
29778 			return (B_FALSE);
29779 	} else {
29780 		dst = NULL;
29781 	}
29782 	if (*dstp != NULL)
29783 		mi_free(*dstp);
29784 	*dstp = dst;
29785 	*dstlenp = dst == NULL ? 0 : srclen;
29786 	return (B_TRUE);
29787 }
29788 
29789 /*
29790  * Replace what is in *dst, *dstlen with the source.
29791  * Assumes ip_allocbuf has already been called.
29792  */
29793 void
29794 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29795     const void *src, uint_t srclen)
29796 {
29797 	if (!src_valid)
29798 		srclen = 0;
29799 
29800 	ASSERT(*dstlenp == srclen);
29801 	if (src != NULL && srclen != 0)
29802 		bcopy(src, *dstp, srclen);
29803 }
29804 
29805 /*
29806  * Free the storage pointed to by the members of an ip6_pkt_t.
29807  */
29808 void
29809 ip6_pkt_free(ip6_pkt_t *ipp)
29810 {
29811 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29812 
29813 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29814 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29815 		ipp->ipp_hopopts = NULL;
29816 		ipp->ipp_hopoptslen = 0;
29817 	}
29818 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29819 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29820 		ipp->ipp_rtdstopts = NULL;
29821 		ipp->ipp_rtdstoptslen = 0;
29822 	}
29823 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29824 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29825 		ipp->ipp_dstopts = NULL;
29826 		ipp->ipp_dstoptslen = 0;
29827 	}
29828 	if (ipp->ipp_fields & IPPF_RTHDR) {
29829 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29830 		ipp->ipp_rthdr = NULL;
29831 		ipp->ipp_rthdrlen = 0;
29832 	}
29833 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29834 	    IPPF_RTHDR);
29835 }
29836 
29837 zoneid_t
29838 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29839     zoneid_t lookup_zoneid)
29840 {
29841 	ire_t		*ire;
29842 	int		ire_flags = MATCH_IRE_TYPE;
29843 	zoneid_t	zoneid = ALL_ZONES;
29844 
29845 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29846 		return (ALL_ZONES);
29847 
29848 	if (lookup_zoneid != ALL_ZONES)
29849 		ire_flags |= MATCH_IRE_ZONEONLY;
29850 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29851 	    lookup_zoneid, NULL, ire_flags, ipst);
29852 	if (ire != NULL) {
29853 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29854 		ire_refrele(ire);
29855 	}
29856 	return (zoneid);
29857 }
29858 
29859 zoneid_t
29860 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29861     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29862 {
29863 	ire_t		*ire;
29864 	int		ire_flags = MATCH_IRE_TYPE;
29865 	zoneid_t	zoneid = ALL_ZONES;
29866 	ipif_t		*ipif_arg = NULL;
29867 
29868 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29869 		return (ALL_ZONES);
29870 
29871 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29872 		ire_flags |= MATCH_IRE_ILL;
29873 		ipif_arg = ill->ill_ipif;
29874 	}
29875 	if (lookup_zoneid != ALL_ZONES)
29876 		ire_flags |= MATCH_IRE_ZONEONLY;
29877 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29878 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29879 	if (ire != NULL) {
29880 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29881 		ire_refrele(ire);
29882 	}
29883 	return (zoneid);
29884 }
29885 
29886 /*
29887  * IP obserability hook support functions.
29888  */
29889 static void
29890 ipobs_init(ip_stack_t *ipst)
29891 {
29892 	netid_t id;
29893 
29894 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
29895 
29896 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
29897 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
29898 
29899 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
29900 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
29901 }
29902 
29903 static void
29904 ipobs_fini(ip_stack_t *ipst)
29905 {
29906 
29907 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
29908 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
29909 }
29910 
29911 /*
29912  * hook_pkt_observe_t is composed in network byte order so that the
29913  * entire mblk_t chain handed into hook_run can be used as-is.
29914  * The caveat is that use of the fields, such as the zone fields,
29915  * requires conversion into host byte order first.
29916  */
29917 void
29918 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
29919     const ill_t *ill, ip_stack_t *ipst)
29920 {
29921 	hook_pkt_observe_t *hdr;
29922 	uint64_t grifindex;
29923 	mblk_t *imp;
29924 
29925 	imp = allocb(sizeof (*hdr), BPRI_HI);
29926 	if (imp == NULL)
29927 		return;
29928 
29929 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
29930 	/*
29931 	 * b_wptr is set to make the apparent size of the data in the mblk_t
29932 	 * to exclude the pointers at the end of hook_pkt_observer_t.
29933 	 */
29934 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
29935 	imp->b_cont = mp;
29936 
29937 	ASSERT(DB_TYPE(mp) == M_DATA);
29938 
29939 	if (IS_UNDER_IPMP(ill))
29940 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
29941 	else
29942 		grifindex = 0;
29943 
29944 	hdr->hpo_version = 1;
29945 	hdr->hpo_htype = htype;
29946 	hdr->hpo_pktlen = htons((ushort_t)msgdsize(mp));
29947 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
29948 	hdr->hpo_grifindex = htonl(grifindex);
29949 	hdr->hpo_zsrc = htonl(zsrc);
29950 	hdr->hpo_zdst = htonl(zdst);
29951 	hdr->hpo_pkt = imp;
29952 	hdr->hpo_ctx = ipst->ips_netstack;
29953 
29954 	if (ill->ill_isv6) {
29955 		hdr->hpo_family = AF_INET6;
29956 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
29957 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
29958 	} else {
29959 		hdr->hpo_family = AF_INET;
29960 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
29961 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
29962 	}
29963 
29964 	imp->b_cont = NULL;
29965 	freemsg(imp);
29966 }
29967